I need to transform this encryption function developed in C# to PHP. Thank you in advance.
private static byte[] Encrypt3DES(string codigoCliente, byte[] key)
{
var codigoClienteBytes = System.Text.Encoding.UTF8.GetBytes(codigoCliente);
TripleDESCryptoServiceProvider tdes = new TripleDESCryptoServiceProvider();
byte[] SALT = new byte[8] { 0, 0, 0, 0, 0, 0, 0, 0 };
tdes.BlockSize = 64;
tdes.KeySize = 192;
tdes.Mode = CipherMode.CBC;
tdes.Padding = PaddingMode.Zeros;
tdes.IV = SALT;
tdes.Key = key;
var cTransform = tdes.CreateEncryptor();
byte[] resultArray = cTransform.TransformFinalBlock(codigoClienteBytes, 0, codigoClienteBytes.Length);
tdes.Clear();
return resultArray;
}
I've tried something like this in PHP but the string result is the same but not the same length.
function encrypt_3DES($message, $key)
{
// Se cifra
$l = ceil(strlen($message) / 8) * 8;
return encodeBase64(
openssl_encrypt($message . str_repeat("\0", $l - strlen($message)),
'des-ede3-cbc',
$key,
OPENSSL_RAW_DATA,
"\0\0\0\0\0\0\0\0")
);
}
You were very nearby to get the correct ciphertext in PHP.
Using below code will generate the same result as your C# function.
Security warning: 3DES (Triple DES) is outdated and should be substituted with modern algorithms like AES.
code:
function encrypt_3DES($message, $key)
{
$method = 'des-ede3-cbc';
if (strlen($message) % 8) {
$message = str_pad($message, strlen($message) + 8 - strlen($message) % 8, "\0");
}
$iv = "\0\0\0\0\0\0\0\0";
$encrypted = openssl_encrypt($message, $method, $key, OPENSSL_RAW_DATA | OPENSSL_ZERO_PADDING, $iv); //Force zero padding.
return base64_encode($encrypted);
}
Related
Long story short have a membership system built in .NET that we are porting to WordPress and need to replicate the PBKDF2 encryption so users don't need to reset their passwords.
Using a know hashed password I've been able to replicate this in .NET easily, with the following code:
static void Main(string[] args)
{
var isValid = CheckPassword("#0zEZcD7uNmv", "5SyOX+Rbclzvvit3MEM2nBRaPVo2M7ZTs7n3znXTfyW4OhwTlJLvpcUlCryblgkQ");
}
public static int PBKDF2IterCount = 10000;
public static int PBKDF2SubkeyLength = 256 / 8; // 256 bits
public static int SaltSize = 128 / 8; // 128 bits
private static bool CheckPassword(string Password, string ExistingHashedPassword)
{
byte[] saltAndPassword = Convert.FromBase64String(ExistingHashedPassword);
byte[] salt = new byte[SaltSize];
Array.Copy(saltAndPassword, 0, salt, 0, SaltSize);
Console.WriteLine("--Salt--");
Console.WriteLine(Convert.ToBase64String(salt));
string hashedPassword = HashPassword(Password, salt);
Console.WriteLine("--HashedPassword--");
Console.WriteLine(hashedPassword);
return hashedPassword == ExistingHashedPassword;
}
private static string HashPassword(string Password, byte[] salt)
{
byte[] hash = new byte[PBKDF2SubkeyLength];
using (var pbkdf2 = new Rfc2898DeriveBytes(Password, salt, PBKDF2IterCount))
{
hash = pbkdf2.GetBytes(PBKDF2SubkeyLength);
}
byte[] hashBytes = new byte[PBKDF2SubkeyLength + SaltSize];
Array.Copy(salt, 0, hashBytes, 0, SaltSize);
Array.Copy(hash, 0, hashBytes, SaltSize, PBKDF2SubkeyLength);
string hashedPassword = Convert.ToBase64String(hashBytes);
return hashedPassword;
}
The console app will produce the following:
--Salt--
5SyOX+Rbclzvvit3MEM2nA==
--HashedPassword--
5SyOX+Rbclzvvit3MEM2nBRaPVo2M7ZTs7n3znXTfyW4OhwTlJLvpcUlCryblgkQ
--IsValid--
True
However in the PHP side I can't get the same results. My code so far is below.
$mySalt = base64_decode('5SyOX+Rbclzvvit3MEM2nA==');
$dev = pbkdf2('sha1', '#0zEZcD7uNmv', $mySalt, 10000, 48, true);
$key = substr($dev, 0, 32); //Keylength: 32
$iv = substr($dev, 32, 16); // IV-length: 16
echo 'PHP<br/>';
echo 'PASS: '.base64_encode($dev).'<br/>';
echo 'SALT: '.base64_encode($iv).'<br/><br/>';
echo '.NET<br/>';
echo 'PASS: 5SyOX+Rbclzvvit3MEM2nBRaPVo2M7ZTs7n3znXTfyW4OhwTlJLvpcUlCryblgkQ<br/>';
echo 'SALT: 5SyOX+Rbclzvvit3MEM2nA==<br/><br/>';
function pbkdf2($algorithm, $password, $salt, $count, $key_length, $raw_output = false)
{
$algorithm = strtolower($algorithm);
if(!in_array($algorithm, hash_algos(), true))
die('PBKDF2 ERROR: Invalid hash algorithm.');
if($count <= 0 || $key_length <= 0)
die('PBKDF2 ERROR: Invalid parameters.');
$hash_length = strlen(hash($algorithm, "", true));
$block_count = ceil($key_length / $hash_length);
$output = "";
for($i = 1; $i <= $block_count; $i++) {
// $i encoded as 4 bytes, big endian.
$last = $salt . pack("N", $i);
// first iteration
$last = $xorsum = hash_hmac($algorithm, $last, $password, true);
// perform the other $count - 1 iterations
for ($j = 1; $j < $count; $j++) {
$xorsum ^= ($last = hash_hmac($algorithm, $last, $password, true));
}
$output .= $xorsum;
}
return substr($output, 0, $key_length);
}
And the results are:
PHP
PASS: FFo9WjYztlOzuffOddN/Jbg6HBOUku+lxSUKvJuWCRCsYe+1Tgbb8Ob4FtxumMal
SALT: rGHvtU4G2/Dm+BbcbpjGpQ==
.NET
PASS: 5SyOX+Rbclzvvit3MEM2nBRaPVo2M7ZTs7n3znXTfyW4OhwTlJLvpcUlCryblgkQ
SALT: 5SyOX+Rbclzvvit3MEM2nA==
Any help would be appreciated.
Ended up getting it working using the https://github.com/defuse/password-hashing libraries, with some minor changes match the format of hashes I was working with database I'm importing.
But my main problem was with these lines where I'm trying to get a key out of a hash.
$dev = pbkdf2('sha1', '#0zEZcD7uNmv', $mySalt, 10000, 48, true);
$key = substr($dev, 0, 32); //Keylength: 32
$iv = substr($dev, 32, 16); // IV-length: 16
Changing it to the below, so that it is creating a hash hash that is 32 bits long and joining the returning hash to the salt fixed the issue.
$dev = pbkdf2('sha1', '#0zEZcD7uNmv', $mySalt, 10000, 32, true);
echo 'PASS: '.base64_encode($mySalt.$dev).'<br />';
With the output below now matching .NET:
PASS: 5SyOX+Rbclzvvit3MEM2nBRaPVo2M7ZTs7n3znXTfyW4OhwTlJLvpcUlCryblgkQ
I ran into this post while searching for a way to migrate passwords from a legacy Asp.Net MVC application to Laravel.
For those interested in just comparing the generated hash (ie. for authentication purpose), please consider the following:
function legacyHashCheck($hash, $password)
{
$raw = base64_decode($hash);
$salt = substr($raw, 1, 16);
$payload = substr($raw, 17, 32);
//new Rfc2898DeriveBytes(password, salt, 1000).GetBytes(32)
$check = hash_pbkdf2('sha1', $password, $salt, 1000, 32, true);
return $payload === $check;
}
It seems .NET core implements 2 formats now (2022).
Source
https://github.com/dotnet/AspNetCore/blob/main/src/Identity/Extensions.Core/src/PasswordHasher.cs
I needed to implement both for Laravel, so here is my contribution:
private function dotNetVerifyHash($hash, $password) {
$version = ord($hash[0]);
if ($version !== 0 && $version !== 1) {
throw new \Exception('wrong version header: ' . $version);
}
if ($version === 0) {
// Format: { 0x00, salt, subkey }
$iterations = 1000;
$subKeyLength = 32;
$saltSize = 16;
$salt = substr($hash, 1, $saltSize);
$derived = hash_pbkdf2('sha1', $password, $salt, $iterations, $subKeyLength, true);
$newHash = chr(0x00) . $salt . $derived;
} else if ($version === 1) {
// Format: { 0x01, prf (UInt32), iter count (UInt32), salt length (UInt32), salt, subkey }
$unp = unpack('N3', substr($hash, 1, 12));
$prf = $unp[1];
$algorithm = '';
switch ($prf) {
case 0: $algorithm = 'sha1'; break;
case 1: $algorithm = 'sha256'; break;
case 2: $algorithm = 'sha512'; break;
default: throw new \Exception('invalid prf: ' . $prf);
}
$iterations = $unp[2];
$saltLength = $unp[3];
$subKeyLength = 32;
$salt = substr($hash, 13, $saltLength);
$derived = hash_pbkdf2($algorithm, $password, $salt, $iterations, $subKeyLength, true);
$newHash = chr(0x01) . pack('N3', $prf, $iterations, $saltLength) . $salt . $derived;
}
return $hash === $newHash;
}
function dotNetCreateHash($password, $version = 1) {
if ($version !== 0 && $version !== 1) {
throw new \Exception('invalid version: ' . ord($hash[0]));
}
$salt = Str::random(16);
if ($version === 0) {
// Format: { 0x00, salt, subkey }
$dev = hash_pbkdf2('sha1', $password, $salt, 1000, 32, true);
return base64_encode(chr(0x00) . $salt . $dev);
} else if ($version === 1) {
// Format: { 0x01, prf (UInt32), iter count (UInt32), salt length (UInt32), salt, subkey }
$algorithm = 'sha256';
$prf = 1;
$iterations = 10000;
$saltLength = strlen($salt);
$subKeyLength = 32;
$derived = hash_pbkdf2($algorithm, $password, $salt, $iterations, $subKeyLength, true);
return base64_encode(chr(0x01) . pack('N3', $prf, $iterations, $saltLength) . $salt . $derived);
}
}
And you can also extend Laravel with custom hasher:
https://gist.github.com/tonila/5719aea8ad57df6821d7acdd1ed4ef1a
C# Code looks like that (can't change it as it's in a client's system).
namespace Common {
public static class EncryptionHelper
{
private const string cryptoKey = "password";
// The Initialization Vector for the DES encryption routine
private static readonly byte[] IV = new byte[8] { 240, 3, 45, 29, 0, 76, 173, 59 };
/// <summary>
/// Encrypts provided string parameter
/// </summary>
public static string Encrypt(string s)
{
string result = string.Empty;
byte[] buffer = Encoding.ASCII.GetBytes(s);
byte[] k = Encoding.ASCII.GetBytes(cryptoKey);
TripleDESCryptoServiceProvider des = new TripleDESCryptoServiceProvider();
MD5CryptoServiceProvider MD5 = new MD5CryptoServiceProvider();
des.Key = MD5.ComputeHash(ASCIIEncoding.ASCII.GetBytes(cryptoKey));
des.IV = IV;
result = Convert.ToBase64String(des.CreateEncryptor().TransformFinalBlock(buffer, 0, buffer.Length));
return result;
}
}
}
I found client took this class from here: http://johnnycoder.com/blog/2008/07/03/c-encryption-decryption-helper-class/
I'm not very familiar with C# and I need to Decrypt string in PHP encrypted with
this code.
When I do "md5($key, true)" I don't get the same result as "MD5.ComputeHash(ASCIIEncoding.ASCII.GetBytes(cryptoKey));", not sure why.
How to convert "byte[] IV" to PHP string ?
Any help would be appreciated.
Thank you.
Managed to get it working:
class Crypter
{
/**
*
* Encryption key
*
* #var
*/
protected $key;
/**
*
* Encryption vector
*
* #var
*/
protected $iv;
public function __construct()
{
$this->key = config('auth.triple_des_key');
$this->iv = implode(array_map("chr", config('auth.triple_des_iv')));
}
/**
*
* Decrypts string using tripleDES method.
*
* #param $input String
* #return String
*/
public function decryptTripleDES($input)
{
$td = mcrypt_module_open(MCRYPT_3DES, '', MCRYPT_MODE_CBC, '');
$encryptedData = base64_decode($input);
$key = iconv('utf-8', 'us-ascii//TRANSLIT', $this->key);
$key = md5($key, true);
$key .= substr($key, 0, 8);
mcrypt_generic_init($td, $key, $this->iv);
$decryptedData = mdecrypt_generic($td, $encryptedData);
mcrypt_generic_deinit($td);
//remove the padding text
$block = mcrypt_get_block_size("tripledes", "cbc");
$packing = ord($decryptedData{strlen($decryptedData) - 1});
if ($packing and ($packing < $block)) {
for ($P = strlen($decryptedData) - 1; $P >= strlen($decryptedData) - $packing; $P--) {
if (ord($decryptedData[$P]) != $packing) {
$packing = 0;
}
}
}
$decryptedData = substr($decryptedData, 0, strlen($decryptedData) - $packing);
return $decryptedData;
}
}
This code is working well in Windows Phone Silverlight project.
but this not working in Windows RT project.
its syay cryptographic and Aes and AesManaged classes missing etc.
please help me thanks.
i dont really need password and salt. its just simple take string and decrypt it.
public class DecryptionHelper
{
public static string Decrypt(string base64StringToDecrypt)
{
if (string.IsNullOrEmpty(base64StringToDecrypt))
return string.Empty;
//Set up the encryption objects
using (Aes acsp = GetProvider(Encoding.UTF8.GetBytes
(Constants.EncryptionKey)))
{
byte[] RawBytes = Convert.FromBase64String(base64StringToDecrypt);
ICryptoTransform ictD = acsp.CreateDecryptor();
//RawBytes now contains original byte array, still in Encrypted state
//Decrypt into stream
MemoryStream msD = new MemoryStream(RawBytes, 0, RawBytes.Length);
CryptoStream csD = new CryptoStream(msD, ictD, CryptoStreamMode.Read);
//csD now contains original byte array, fully decrypted
//return the content of msD as a regular string
return (new StreamReader(csD)).ReadToEnd();
}
}
private static Aes GetProvider(byte[] key)
{
Aes result = new AesManaged();
result.GenerateIV();
result.IV = new byte[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
byte[] RealKey = GetKey(key, result);
result.Key = RealKey;
return result;
}
private static byte[] GetKey(byte[] suggestedKey, SymmetricAlgorithm p)
{
byte[] kRaw = suggestedKey;
List<byte> kList = new List<byte>();
for (int i = 0; i < p.LegalKeySizes[0].MinSize; i += 8)
{
kList.Add(kRaw[(i / 8) % kRaw.Length]);
}
byte[] k = kList.ToArray();
return k;
}
}
I have the following code in Java doing key unwrap using bouncy castle provider:
private static byte[] unwrapKey(byte[] toUnwrap, String key) throws Exception {
byte[] decoded = Base64.decode(toUnwrap);
if (decoded == null || decoded.length <= 16) {
throw new RuntimeException("Bad input data.");
}
byte[] salt = new byte[16];
byte[] wrappedKey = new byte[decoded.length - 16];
System.arraycopy(decoded, 0, salt, 0, 16);
System.arraycopy(decoded, 16, wrappedKey, 0, decoded.length - 16);
PBEKeySpec pbeKeySpec = new PBEKeySpec(key.toCharArray());
SecretKey wrapperKey = SecretKeyFactory.getInstance("PBEWITHSHA256AND256BITAES-CBC-BC").generateSecret(pbeKeySpec);
PBEParameterSpec parameterSpec = new PBEParameterSpec(salt, 10);
Cipher decCipher = Cipher.getInstance("AES/GCM/NoPadding", bcProvider);
decCipher.init(Cipher.UNWRAP_MODE, wrapperKey, parameterSpec);
return decCipher.unwrap(wrappedKey, "AES", Cipher.SECRET_KEY).getEncoded();
}
Now, I need to do the same in C#. The problem is that even though there's a port of BC to C#, I still can not get it working. Tried different things, and always get some exceptions.
For example, this code throws "pad block corrupted" exception at the second last line:
byte[] decoded = Convert.FromBase64String(toUnwrap);
if (decoded == null || decoded.Length <= 16) {
throw new System.ArgumentException("Bad input data", "toUnwrap");
}
byte[] salt = new byte[16];
byte[] wrappedKey = new byte[decoded.Length - 16];
Array.Copy(decoded, 0, salt, 0, 16);
Array.Copy(decoded, 16, wrappedKey, 0, decoded.Length - 16);
int iterationCount = 10;
String alg = "PBEWithSHA256And256BitAES-CBC-BC";
Asn1Encodable defParams = PbeUtilities.GenerateAlgorithmParameters(alg, salt, iterationCount);
char[] password = key.ToCharArray();
IWrapper wrapper = WrapperUtilities.GetWrapper(alg);
ICipherParameters parameters = PbeUtilities.GenerateCipherParameters(alg, password, defParams);
wrapper.Init(false, parameters);
byte[] pText = wrapper.Unwrap(wrappedKey, 0, wrappedKey.Length);
return pText.ToString();
I suspect that C# uses different type of padding by default, but no idea how to force "NoPadding" as in Java code.
I'm not sure, if JAVA code use rfc3994 is this case or not, because in RFC you need to provide IV, while here there's a salt, but no IV.
I wonder if anyone did it before and if so, what would be c# analogy.
I finally figured that out:
public static String unwrapKey(String toUnwrap, String key)
{
byte[] decoded = Convert.FromBase64String(toUnwrap);
if (decoded == null || decoded.Length <= 16)
{
throw new System.ArgumentException("Bad input data", "toUnwrap");
}
byte[] salt = new byte[16];
byte[] wrappedKey = new byte[decoded.Length - 16];
Array.Copy(decoded, 0, salt, 0, 16);
Array.Copy(decoded, 16, wrappedKey, 0, decoded.Length - 16);
int iterationCount = 10;
String algSpec = "AES/GCM/NoPadding";
String algName = "PBEWithSHA256And256BitAES-CBC-BC";
Asn1Encodable defParams = PbeUtilities.GenerateAlgorithmParameters(algName, salt, iterationCount);
char[] password = key.ToCharArray();
IWrapper wrapper = WrapperUtilities.GetWrapper(algSpec);
ICipherParameters parameters = PbeUtilities.GenerateCipherParameters(algName, password, defParams);
wrapper.Init(false, parameters);
byte[] keyText = wrapper.Unwrap(wrappedKey, 0, wrappedKey.Length);
return Convert.ToBase64String(keyText);
}
This will do exactly the same as the JAVA code above.
I have with this code:
RijndaelManaged rijndaelCipher = new RijndaelManaged();
// Set key and IV
rijndaelCipher.Key = Convert.FromBase64String("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz012345678912");
rijndaelCipher.IV = Convert.FromBase64String("1234567890123456789012345678901234567890123456789012345678901234");
I get this exception thrown:
Specified key is not a valid size for this algorithm.
Specified initialization vector (IV) does not match the block size for this algorithm.
What's wrong with this strings ? Can I count at some examples strings from you?
The string "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz012345678912" when base64-decoded yields 48 bytes (384 bits). RijndaelManaged supports 128, 192 and 256 bit keys.
A valid 128-bit key is new byte[]{ 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F } or if you need to get it from base64 : Convert.FromBase64String("AAECAwQFBgcICQoLDA0ODw==").
The default blocksize is 128 bits, so the same byte-array will work as the IV.
Use the random number generator class (RNGCryptoServiceProvider) to fill a specified buffer with random bytes as follows:
var numberOfBits = 256; // or 192 or 128, however using a larger bit size renders the encrypted data harder to decipher
var ivBytes = new byte[numberOfBits / 8]; // 8 bits per byte
new RNGCryptoServiceProvider().GetBytes(ivBytes);
var rijndaelManagedCipher = new RijndaelManaged();
//Don't forget to set the explicitly set the block size for the IV if you're not using the default of 128
rijndaelManagedCipher.BlockSize = 256;
rijndaelManagedCipher.IV = ivBytes;
Note the same process could be used to derive a key. Hope this helps.
The RijndaelManaged algorithm supports key lengths of 128, 192, or 256 bits. Is your key one of these sizes?
here is the class i created
public class ByteCipher
{
// This constant is used to determine the keysize of the encryption algorithm in bits.
// We divide this by 8 within the code below to get the equivalent number of bytes.
private int _Keysize = (int)GlobalConfiguration.DataEncode_Key_Size;
private byte[] saltStringBytes;
private byte[] ivStringBytes;
// This constant determines the number of iterations for the password bytes generation function.
private const int DerivationIterations = 1000;
private string _passPhrase = GlobalConfiguration.DataEncode_Key;
private const string salt128 = "kljsdkkdlo4454GG";
private const string salt256 = "kljsdkkdlo4454GG00155sajuklmbkdl";
public ByteCipher(string passPhrase = null, DataCipherKeySize keySize = DataCipherKeySize.Key_128)
{
if (!string.IsNullOrEmpty(passPhrase?.Trim()))
_passPhrase = passPhrase;
_Keysize = keySize == DataCipherKeySize.Key_256 ? 256 : 128;
saltStringBytes = _Keysize == 256 ? Encoding.UTF8.GetBytes(salt256) : Encoding.UTF8.GetBytes(salt128);
ivStringBytes = _Keysize == 256 ? Encoding.UTF8.GetBytes("SSljsdkkdlo4454Maakikjhsd55GaRTP") : Encoding.UTF8.GetBytes("SSljsdkkdlo4454M");
}
public byte[] Encrypt(byte[] plainTextBytes)
{
if (plainTextBytes.Length <= 0)
return plainTextBytes;
using (var password = new Rfc2898DeriveBytes(_passPhrase, saltStringBytes, DerivationIterations))
{
var keyBytes = password.GetBytes(_Keysize / 8);
using (var symmetricKey = new RijndaelManaged())
{
symmetricKey.BlockSize = _Keysize;
symmetricKey.Mode = CipherMode.CBC;
symmetricKey.Padding = PaddingMode.PKCS7;
using (var encryptor = symmetricKey.CreateEncryptor(keyBytes, ivStringBytes))
{
using (var memoryStream = new MemoryStream())
{
using (var cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write))
{
cryptoStream.Write(plainTextBytes, 0, plainTextBytes.Length);
cryptoStream.FlushFinalBlock();
// Create the final bytes as a concatenation of the random salt bytes, the random iv bytes and the cipher bytes.
var cipherTextBytes = saltStringBytes;
cipherTextBytes = cipherTextBytes.Concat(ivStringBytes).ToArray();
cipherTextBytes = cipherTextBytes.Concat(memoryStream.ToArray()).ToArray();
memoryStream.Close();
cryptoStream.Close();
return cipherTextBytes;
}
}
}
}
}
}
public byte[] Decrypt(byte[] cipherTextBytesWithSaltAndIv)
{
if (cipherTextBytesWithSaltAndIv.Length <= 0)
return cipherTextBytesWithSaltAndIv;
var v = Encoding.UTF8.GetString(cipherTextBytesWithSaltAndIv.Take(_Keysize / 8).ToArray());
if (v != salt256 && v != salt128)
return cipherTextBytesWithSaltAndIv;
var cipherTextBytes = cipherTextBytesWithSaltAndIv.Skip((_Keysize / 8) * 2).Take(cipherTextBytesWithSaltAndIv.Length - ((_Keysize / 8) * 2)).ToArray();
using (var password = new Rfc2898DeriveBytes(_passPhrase, saltStringBytes, DerivationIterations))
{
var keyBytes = password.GetBytes(_Keysize / 8);
using (var symmetricKey = new RijndaelManaged())
{
symmetricKey.Mode = CipherMode.CBC;
symmetricKey.Padding = PaddingMode.PKCS7;
symmetricKey.BlockSize = _Keysize;
using (var decryptor = symmetricKey.CreateDecryptor(keyBytes, ivStringBytes))
{
using (var memoryStream = new MemoryStream(cipherTextBytes))
{
using (var cryptoStream = new CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read))
{
var plainTextBytes = new byte[cipherTextBytes.Length];
var decryptedByteCount = cryptoStream.Read(plainTextBytes, 0, plainTextBytes.Length);
memoryStream.Close();
cryptoStream.Close();
return plainTextBytes;
}
}
}
}
}
}
}
I don't know the length of rijndaelCipher.Key
if it is 24, then rijndaelCipher.Key = s.SubString(0, 24);
So easy.