问题描述
我们已经在.Net中进行了加密/解密,但是当迁移到Java时,即使使用相同的密钥对和盐,它也会产生不同的结果。
请帮助我如何修复Java代码?谢谢!
例如:用Java加密字符串时,.Net中的字符串“ Hello world”得到不同的结果。
我的C#代码
namespace Utils
{
public class AES256Crypto
{
const string saltStr = "test";
const string password = "test@1234";
public static string EncryptString(string text)
{
try
{
byte[] baPwd = Encoding.UTF8.GetBytes(password);
// Hash the password with SHA256
byte[] baPwdHash = SHA256Managed.Create().ComputeHash(baPwd);
byte[] baText = Encoding.UTF8.GetBytes(text);
var baEncrypted = AES_Encrypt(baText,baPwdHash);
string result = Convert.ToBase64String(baEncrypted);
return result;
}
catch
{
return string.Empty;
}
}
private static byte[] AES_Encrypt(byte[] bytesToBeEncrypted,byte[] passwordBytes)
{
byte[] encryptedBytes = null;
// Set your salt here,change it to meet your flavor:
// The salt bytes must be at least 8 bytes.
byte[] saltBytes = Encoding.UTF8.GetBytes(saltStr);
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.Mode = CipherMode.CBC;
using (var cs = new CryptoStream(ms,AES.CreateEncryptor(),CryptoStreamMode.Write))
{
cs.Write(bytesToBeEncrypted,bytesToBeEncrypted.Length);
cs.Close();
}
encryptedBytes = ms.ToArray();
}
}
return encryptedBytes;
}
}
}
我的JAVA代码
public static String encrypt(String plainText) {
try {
String salt = "test";
String password = test@1234";
String initializationVector = " ";
int pswdIterations = 1000;
int keySize = 256;
byte[] saltBytes = salt.getBytes("UTF-8");// "UTF-8");
byte[] ivBytes = initializationVector.getBytes("UTF-8");// "UTF-8");
// Derive the key,given password and salt.
SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256");// PBEWithMD5AndDES");
PBEKeySpec spec = new PBEKeySpec(password.tochararray(),pswdIterations,keySize);
SecretKey secretKey = factory.generateSecret(spec);
SecretKeySpec secret = new SecretKeySpec(secretKey.getEncoded(),"AES");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); // Cipher.getInstance("AES/CBC/PKCSPadding"
cipher.init(Cipher.ENCRYPT_MODE,secret,new IvParameterSpec(ivBytes));
byte[] encryptedTextBytes = cipher.doFinal(plainText.getBytes("UTF-8"));// UTF-8"));
String str = new org.apache.commons.codec.binary.Base64().encodeAsstring(encryptedTextBytes);
return str;
} catch (Exception e) {
return e.toString();
}
我们已经在.Net中进行了加密/解密,但是当迁移到Java时,即使使用相同的密钥对和盐,它也会产生不同的结果。
请帮助我如何修复Java代码?谢谢!
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)