加密後位元組陣列和字串相互轉換
阿新 • • 發佈:2020-07-26
加密結果直接轉字串
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,符合預期。