I'm trying to decode a string crypted using AES 128 in Salesforce and passed me via web by a vendor.
I know how they encrypt the string and the vendor gave me a "decryption script" written in Apex (see below), but I'm not able to transpose that in C# (or VB.NET).
Encrypt function (in Apex):
public static String getCryptedBase64Text(String decryptedText, String encryptionKey)
{
Blob decryptedBlob = Blob.valueOf(decryptedText);
//GENERATE ENCRYPTION KEY
Blob blobKey = Blob.valueOf(encryptionKey);
Blob hashKey = Crypto.generateDigest('MD5', blobKey);
//CRYPT TEXT USING KEY
Blob encryptedBlob1 = Crypto.encryptWithManagedIV('AES128', hashKey, decryptedBlob);
String encryptedString1 = EncodingUtil.base64Encode(encryptedBlob1);
return encryptedString1;
}
Decrypt function (in Apex):
public static String getPlainDecryptedText(String base64encrypted, String decryptionKey)
{
Blob encryptedBlob = EncodingUtil.base64Decode(base64encrypted);
//GENERATE DECRYPTION KEY
Blob blobKey = Blob.valueOf(decryptionKey);
Blob HashKey = Crypto.generateDigest('MD5', blobKey);
//DECRYPT TEXT USING KEY
Blob decryptedBlob = Crypto.decryptWithManagedIV('AES128', HashKey, encryptedBlob);
String decryptedString = decryptedBlob.toString();
return decryptedString;
}
I have the encryptionKey that the vendor gave me, and it is a four-digit string like "abcd".
Knowing both the string "decryptedText" and the key "encryptionKey", how can I decrypt "decryptedText" using C# (or VB.NET)?
Here is my C# code so far:
public String Decrypt2(string encryptedbase64text, byte[] Key){
string plaintext;
byte[] IV = new byte[16];
byte[] phase = Convert.FromBase64String(encryptedbase64Password);
Array.Copy(phase, 0, IV, 0, IV.Length);
byte[] cipherText = new byte[phase.Length - 16];;
Array.Copy(phase, 16, cipherText, 0, cipherText.Length);
using (AesManaged aesAlg = new AesManaged())
{
aesAlg.Key = Key;
aesAlg.IV = IV;
ICryptoTransform decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV);
using (MemoryStream msDecrypt = new MemoryStream(cipherText))
{
using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
{
using (StreamReader srDecrypt = new StreamReader(csDecrypt))
{
plaintext = srDecrypt.ReadToEnd();
}
}
}
}
return plaintext;
}