我正在尝试创建一个允许我使用AES算法加密和解密字符串的类。我正在使用http://aesencryption.net/#Java-aes-encryption-example中的例外,但修改了代码以满足我的需求。
这是我的Main.java:
public class Main {
public static void main(String[] args) {
AES256 aes = new AES256();
aes.setKey("Secret Key");
String enc = "";
enc = aes.encrypt("qwertyuiopasdfgh");
System.out.println(enc);
System.out.println(aes.decrypt(enc));
}
}
这是我的AES256.java:
import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.util.Base64;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.SecretKeySpec;
public class AES256 {
private SecretKeySpec secretKey;
private byte[] key;
public void setKey(String key) {
MessageDigest sha = null;
try {
this.key = key.getBytes("UTF-8");
sha = MessageDigest.getInstance("SHA-1");
this.key = sha.digest(this.key);
this.key = Arrays.copyOf(this.key, 16);
secretKey = new SecretKeySpec(this.key, "AES");
} catch (UnsupportedEncodingException | NoSuchAlgorithmException e) {
e.printStackTrace();
}
}
public String getSecretKey() {
return secretKey.toString();
}
public String getKey() {
return new String(key);
}
public String encrypt(String string) {
try {
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5PADDING");
cipher.init(Cipher.ENCRYPT_MODE, secretKey);
return Base64.getMimeEncoder().encodeToString(string.getBytes());
} catch (InvalidKeyException | NoSuchAlgorithmException | NoSuchPaddingException e) {
e.printStackTrace();
}
return null;
}
public String decrypt(String string) {
try {
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5PADDING");
cipher.init(Cipher.DECRYPT_MODE, secretKey);
return new String(cipher.doFinal(Base64.getMimeDecoder().decode(string.getBytes())));
} catch (InvalidKeyException | NoSuchAlgorithmException | NoSuchPaddingException | IllegalBlockSizeException | BadPaddingException e) {
e.printStackTrace();
}
return null;
}
}
这是抛出的错误:
javax.crypto.BadPaddingException: Given final block not properly padded
at com.sun.crypto.provider.CipherCore.doFinal(CipherCore.java:966)
at com.sun.crypto.provider.CipherCore.doFinal(CipherCore.java:824)
at com.sun.crypto.provider.AESCipher.engineDoFinal(AESCipher.java:436)
at javax.crypto.Cipher.doFinal(Cipher.java:2121)
at AES256.decrypt(AES256.java:55)
at Main.main(Main.java:13)
有人知道是什么导致了这个错误吗?
答案 0 :(得分:3)
以base64编码的形式返回原始字符串:
return Base64.getMimeEncoder().encodeToString(string.getBytes());
你也想在那里使用密码:
return Base64.getMimeEncoder().encodeToString(cipher.doFinal(string.getBytes()));
独立于此,当请求自己的加密时,请注意密码模式,填充等的影响。例如,您正在使用的ECB模式将从相同的明文产生相同的密文,例如,密文可能会引导有关原始文本的提示,如着名的加密礼服图像:
图片版权:如果原始图片的所有者Larry Ewing要求您提及他的电子邮件地址lewing@isc.tamu.edu和GIMP,则允许使用所有用途。 http://www.isc.tamu.edu/~lewing/linux/
有关详细信息,请参阅Wikipedia's article about block cipher modes。