我尝试使用java和cryptoJS加密和解密AES,如果我以任何一种方式加密和解密短文本,一切都很好。但是,如果我放一个长文本,当cryptoJS尝试解密时结果是错误的,其他方式工作正常。请帮我解答一下我的问题。这是我的代码。
java代码
public void setKey(String myKey){
secretKey = new SecretKeySpec(Base64.decodeBase64(myKey), "AES");
}
public String generateKey(int len) {
final String AB = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
Random rnd = new Random();
StringBuilder sb = new StringBuilder(len);
for (int i = 0; i < len; i++) {
sb.append(AB.charAt(rnd.nextInt(AB.length())));
}
return sb.toString();
}
public void encrypt(String strToEncrypt)
{
try
{
Cipher cipher = Cipher.getInstance("AES/ECB/Iso10126Padding");
cipher.init(Cipher.ENCRYPT_MODE, secretKey);
setEncryptedString(Base64.encodeBase64String(cipher.doFinal(strToEncrypt.getBytes("UTF-8"))));
}
catch (Exception e)
{
System.out.println("Error while encrypting: "+e.toString());
}
}
public void decrypt(String strToDecrypt)
{
try
{
Cipher cipher = Cipher.getInstance("AES/ECB/Iso10126PADDING");
cipher.init(Cipher.DECRYPT_MODE, secretKey);
setDecryptedString(new String(cipher.doFinal(Base64.decodeBase64(strToDecrypt))));
}
catch (Exception e)
{
System.out.println("Error while decrypting: "+e.toString());
}
}
Javascript代码
function encrypt(string,key){
var keyInside = CryptoJS.enc.Base64.parse(key);
var encrypted = CryptoJS.AES.encrypt(string, keyInside, {mode: CryptoJS.mode.ECB, padding: CryptoJS.pad.Iso10126});
return encrypted;
}
function decrypt(string,key){
var keyInside = CryptoJS.enc.Base64.parse(key);
var decrypted = CryptoJS.AES.decrypt(string, keyInside, {mode: CryptoJS.mode.ECB, padding: CryptoJS.pad.Iso10126});
return decrypted.toString(CryptoJS.enc.Utf8);
}
function generateKey(length)
{
var text = "";
var possible = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
for( var i=0; i < length; i++ )
text += possible.charAt(Math.floor(Math.random() * possible.length));
return text;
}
感谢您帮助我:)