在PHP中解密c#加密字符串(StringCipher库)



我想解密一个字符串,我用c#加密使用StringCipher库

迄今为止我所做的尝试都没有成功:

function decrypt($cipherText, $passPhrase)
{
$Keysize = 256;
$DerivationIterations = 1000;
$cipher_algo = "aes-256-cbc";
//$iv = openssl_random_pseudo_bytes(openssl_cipher_iv_length($cipher_algo));
$cipherTextBytesWithSaltAndIv = base64_decode($cipherText);
$saltStringBytes = substr($cipherTextBytesWithSaltAndIv, 0, ($Keysize / 8));
$ivStringBytes = substr($cipherTextBytesWithSaltAndIv, ($Keysize / 8), ($Keysize / 8));
$cipherTextBytes = substr($cipherTextBytesWithSaltAndIv, (($Keysize / 8) * 2), strlen($cipherTextBytesWithSaltAndIv) - (($Keysize / 8) * 2));
$keyBytes = hash_pbkdf2("sha1", $passPhrase, $saltStringBytes, $DerivationIterations, ($Keysize / 8), true);
return openssl_decrypt($cipherTextBytes, $cipher_algo, $keyBytes, 0, $ivStringBytes);
}

PHP中的128位变体:

<?php
class StringCipher
{
private const Keysize = 128;
private const DerivationIterations = 1000;
private const cipher_algo = "aes-128-cbc";
public static function Encrypt($plainText, $passPhrase)
{
$saltStringBytes = self::Generate128BitsOfRandomEntropy();
$ivStringBytes = self::Generate128BitsOfRandomEntropy();
$keyBytes = hash_pbkdf2("sha1", $passPhrase, $saltStringBytes, self::DerivationIterations, (self::Keysize / 8), true);
$cipherTextBytes = $saltStringBytes . $ivStringBytes . openssl_encrypt($plainText, self::cipher_algo, $keyBytes, OPENSSL_RAW_DATA, $ivStringBytes);
return base64_encode($cipherTextBytes);
}
public static function Decrypt($cipherText, $passPhrase)
{
$cipherTextBytesWithSaltAndIv = base64_decode($cipherText);
$saltStringBytes = substr($cipherTextBytesWithSaltAndIv, 0, (self::Keysize / 8));
$ivStringBytes = substr($cipherTextBytesWithSaltAndIv, (self::Keysize / 8), (self::Keysize / 8));
$cipherTextBytes = substr($cipherTextBytesWithSaltAndIv, ((self::Keysize / 8) * 2), strlen($cipherTextBytesWithSaltAndIv) - ((self::Keysize / 8) * 2));
$keyBytes = hash_pbkdf2("sha1", $passPhrase, $saltStringBytes, self::DerivationIterations, (self::Keysize / 8), true);
return openssl_decrypt($cipherTextBytes, self::cipher_algo, $keyBytes, OPENSSL_RAW_DATA, $ivStringBytes);
}
private static function Generate128BitsOfRandomEntropy()
{
return openssl_random_pseudo_bytes(openssl_cipher_iv_length(self::cipher_algo));
}
}

最新更新