加密結果直接轉字符串
public class Client {
// 加密算法
private static final String BLOWFISH = "Blowfish";
// 加密秘鑰
private static final String SECRET = "test";
public static void main(String[] args) throws Exception {
String source = "hello";
byte[] encrypt = encrypt(source);
byte[] decrypt = decrypt(new String(encrypt));
System.out.println(new String(decrypt));
}
// 加密
private static byte[] encrypt(String data) throws Exception {
Cipher cipher = Cipher.getInstance(BLOWFISH);
SecretKeySpec myskeys = new SecretKeySpec(SECRET.getBytes(), BLOWFISH);
cipher.init(Cipher.ENCRYPT_MODE, myskeys);
return cipher.doFinal(data.getBytes());
}
// 解密
private static byte[] decrypt(String data) throws Exception {
Cipher cipher = Cipher.getInstance(BLOWFISH);
SecretKeySpec myskeys = new SecretKeySpec(SECRET.getBytes(), BLOWFISH);
cipher.init(Cipher.DECRYPT_MODE, myskeys);
return cipher.doFinal(data.getBytes());
}
}
運行結果為
Exception in thread "main" javax.crypto.IllegalBlockSizeException: Input length must be multiple of 8 when decrypting with padded cipher
at com.sun.crypto.provider.CipherCore.doFinal(CipherCore.java:936)
at com.sun.crypto.provider.CipherCore.doFinal(CipherCore.java:847)
at com.sun.crypto.provider.BlowfishCipher.engineDoFinal(BlowfishCipher.java:319)
at javax.crypto.Cipher.doFinal(Cipher.java:2164)
at com.imooc.sourcecode.java.base.java8.base64.test2.Client.decrypt(Client.java:28)
at com.imooc.sourcecode.java.base.java8.base64.test2.Client.main(Client.java:13)
這是因為解密之后得到的字節數組是不符合UTF8,GBK等編碼規則的,轉成字符串再轉成字節數組,數據已經改變了,所以解密會出錯。
將加密結果轉為Base64再轉為字符串
public class Client {
private static final String BLOWFISH = "Blowfish";
private static final String SECRET = "test";
public static void main(String[] args) throws Exception {
String source = "hello";
byte[] encrypt = encrypt(source);
String encodeToString = Base64.getEncoder().encodeToString(encrypt);
byte[] decode = Base64.getDecoder().decode(encodeToString);
byte[] decrypt = decrypt(decode);
System.out.println(new String(decrypt));
}
private static byte[] encrypt(String data) throws Exception {
Cipher cipher = Cipher.getInstance(BLOWFISH);
SecretKeySpec myskeys = new SecretKeySpec(SECRET.getBytes(), BLOWFISH);
cipher.init(Cipher.ENCRYPT_MODE, myskeys);
return cipher.doFinal(data.getBytes());
}
private static byte[] decrypt(byte[] data) throws Exception {
Cipher cipher = Cipher.getInstance(BLOWFISH);
SecretKeySpec myskeys = new SecretKeySpec(SECRET.getBytes(), BLOWFISH);
cipher.init(Cipher.DECRYPT_MODE, myskeys);
return cipher.doFinal(data);
}
}
結果為hello,符合預期。