-2
private static string Encrypt(string plainText)
{
byte[] keyBytes = Encoding.UTF8.GetBytes(_secretKey);
byte[] hashedKeyBytes = new SHA256CryptoServiceProvider().ComputeHash(keyBytes);
var secretKeyHashString = string.Concat(hashedKeyBytes.Select(hb => hb.ToString("x2")));
byte[] cryptoKeyHash = new SHA256CryptoServiceProvider().ComputeHash(Encoding.UTF8.GetBytes(secretKeyHashString));
byte[] cryptoKey = cryptoKeyHash.Take(16).ToArray();
var aes = new AesCryptoServiceProvider()
{
Padding = PaddingMode.PKCS7,
Key = cryptoKey,
Mode = CipherMode.CBC,
IV = _initialisationVector
};
RijndaelManaged aesEnc = new RijndaelManaged();
byte[] plainTextBytes = Encoding.UTF8.GetBytes(plainText);
var encryptor = aes.CreateEncryptor();
byte[] encryptedBytes = encryptor.TransformFinalBlock(plainTextBytes, 0, plainTextBytes.Length);
var encryptedString = Convert.ToBase64String(encryptedBytes);
return encryptedString;
}
private static string Decrypt(string encryptedText)
{
byte[] keyBytes = Encoding.UTF8.GetBytes(_secretKey);
byte[] hashedKeyBytes = new SHA256CryptoServiceProvider().ComputeHash(keyBytes);
var secretKeyHashString = string.Concat(hashedKeyBytes.Select(hb => hb.ToString("x2")));
byte[] cryptoKeyHash = new SHA256CryptoServiceProvider().ComputeHash(Encoding.UTF8.GetBytes(secretKeyHashString));
byte[] cryptoKey = cryptoKeyHash.Take(16).ToArray();
byte[] initialisationVector = { 0, 133, 36, 86, 84, 150, 188, 164, 28, 210, 112, 158, 141, 87, 11, 227 };
var aes = new AesCryptoServiceProvider()
{
Padding = PaddingMode.PKCS7,
Key = cryptoKey,
Mode = CipherMode.CBC,
IV = _initialisationVector
};
var decryptor = aes.CreateDecryptor();
var encryptedBytes = Convert.FromBase64String(encryptedText);
var decryptedBytes = decryptor.TransformFinalBlock(encryptedBytes, 0, encryptedBytes.Length);
var decryptedString = Encoding.UTF8.GetString(decryptedBytes);
return decryptedString;
}
Dhaval嗨,感謝您的回答! – user3932597
由於這些方法是由客戶端提供的,所以我們必須在JAVA中使用相同的方法。代碼中還有一些初始化矢量,我沒有得到。 – user3932597