我试图将以下C#代码转换为Java,代码使用的是.NET库(System.Security.Cryptography),我希望能够使用Java获得相同的结果:
internal static class CryptoHelper
{
// keys must be 16 characters long (and ASCII)
public const string DefaultKey = "2$8Kba19z23asd!#";
public const string IV = "0000000000000000";
enum CryptoTransformType
{
Encryptor,
Decryptor
}
public static byte[] Encrypt(bool FIPScompatible, string key, byte[] data)
{
if(key == null) throw new ArgumentNullException("key");
if(data == null) return null;
// Create the crypto
ICryptoTransform transform = CreateCryptoTransform(FIPScompatible,CryptoTransformType.Encryptor, key, IV);
// Encrypt the data
using(MemoryStream ms = new MemoryStream())
{
using(CryptoStream cs = new CryptoStream(ms, transform, CryptoStreamMode.Write))
{
cs.Write(data, 0, data.Length);
cs.FlushFinalBlock();
}
byte[] encryptedData = ms.GetBuffer();
return encryptedData;
}
}
public static byte[] Decrypt(bool FIPScompatible, string key, byte[] data)
{
if(key == null) throw new ArgumentNullException("key");
if(data == null) return null;
// Create the crypto
ICryptoTransform transform = CreateCryptoTransform(FIPScompatible,CryptoTransformType.Decryptor, key, IV);
// Decrypt the data
using(MemoryStream ms = new MemoryStream(data))
{
using(CryptoStream cs = new CryptoStream(ms, transform, CryptoStreamMode.Read))
{
byte[] decryptedData = new byte[data.Length];
cs.Read(decryptedData, 0, decryptedData.Length);
return decryptedData;
}
}
}
private static ICryptoTransform CreateCryptoTransform(bool FIPScompatible,CryptoTransformType transformType, string key, string iv)
{
if (!FIPScompatible)
{
RijndaelManaged rijndael = new RijndaelManaged();
rijndael.Mode = CipherMode.CBC;
rijndael.Padding = PaddingMode.Zeros;
rijndael.BlockSize = 128;
byte[] bykey = Encoding.ASCII.GetBytes(key);
byte[] byiv = Encoding.ASCII.GetBytes(iv);
ICryptoTransform transform = null;
if (transformType == CryptoTransformType.Encryptor)
transform = rijndael.CreateEncryptor(bykey, byiv);
else
transform = rijndael.CreateDecryptor(bykey, byiv);
return transform;
}
else
{
AesCryptoServiceProvider provider = new AesCryptoServiceProvider();
provider.Padding = PaddingMode.Zeros;
provider.BlockSize = 128;
byte[] bykey = Encoding.ASCII.GetBytes(key);
byte[] byiv = Encoding.ASCII.GetBytes(iv);
ICryptoTransform transform = null;
if (transformType == CryptoTransformType.Encryptor)
transform = provider.CreateEncryptor(bykey, byiv);
else
transform = provider.CreateDecryptor(bykey, byiv);
return transform;
}
}
}
我尝试了一种方法,但是我无法从.NET代码中获得相同的结果,我尝试的方法将添加到评论中。