[英]AES256 JAVA encryption doesn't match C# encryption
在與我的伙伴的JAVA API交談時,我被要求加密一些數據,他向我發送了以下有關加密算法的詳細信息:
我使用下面的代碼,但沒有得到與他匹配的結果:
public byte[] AES_Encrypt(byte[] bytesToBeEncrypted, byte[] passwordBytes)
{
byte[] encryptedBytes = null;
byte[] saltBytes = new byte[16] { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
using (MemoryStream ms = new MemoryStream())
{
using (RijndaelManaged aes = new RijndaelManaged())
{
aes.KeySize = 256;
aes.BlockSize = 128;
var key = new Rfc2898DeriveBytes(passwordBytes, saltBytes, 1000);
aes.Key = key.GetBytes(aes.KeySize / 8);
aes.IV = key.GetBytes(aes.BlockSize / 8);
aes.Padding = PaddingMode.PKCS7;
aes.Mode = CipherMode.CBC;
using (var cs = new CryptoStream(ms, aes.CreateEncryptor(), CryptoStreamMode.Write))
{
cs.Write(bytesToBeEncrypted, 0, bytesToBeEncrypted.Length);
cs.Close();
}
encryptedBytes = ms.ToArray();
}
}
return encryptedBytes;
}
public string EncryptText(string input, string password)
{
byte[] bytesToBeEncrypted = Encoding.UTF8.GetBytes(input);
byte[] passwordBytes = Encoding.UTF8.GetBytes(password);
passwordBytes = SHA256.Create().ComputeHash(passwordBytes);
byte[] bytesEncrypted = AES_Encrypt(bytesToBeEncrypted, passwordBytes);
string result = Convert.ToBase64String(bytesEncrypted);
return result;
}
因此,當我們嘗試加密Hello時,您好嗎? ,我得到了不同的結果,我應該得到與他相同的結果,因為他將解密我發送的數據並對其進行處理。 給定的示例應具有以下結果: TJTojNoVgoqnhCj4uTv1jLBiZU7r+s/0Bm234bHU+S0=
我做了一些測試,現在可以匹配您的預期結果。
2個要完成的更改。
IV
如您所說的IV = 0,IV是最簡單的,因此將IV設置如下:
aes.IV = new byte[16];
在AES中, IV為16個字節 。 上面將創建一個16字節的字節數組,每個值都初始化為零。
鍵
您提供的密碼以“ 0x”開頭-本質上意味着這是密碼字符串的十六進制表示形式。 我使用此密碼將密碼轉換為字節數組
string password = "A8703827AE586460105696504327B7BB0806FEAE96BD664F89E36868FBB48E3D";
請注意,我從上面刪除了開頭的“ 0x”
byte[] passwordBytes = StringToByteArray(password);
上面的代碼將十六進制密碼表示形式轉換為字節數組。
在您的AES_Encrypt
方法中,直接將此byte []作為密鑰分配
aes.Key = passwordBytes;
現在,我的結果是TJTojNoVgoqnhCj4uTv1jLBiZU7r+s/0Bm234bHU+S0=
與您的預期輸出完全匹配。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.