如果您使用 AES 加密,那么在加密明文时生成的二进制字符时,会需要使用 base-64 编码,至少在您希望在 Web 请求(例如,使用 SimpleDB 域)中使用它们时需要使用 base-64 编码。因此,我将编码所有加密的字符串,解码任何已加密的字符串。
用于 AES 的 Cryptographical
实现类(如清单 3 所示)不仅要处理 AES 加密,还要处理 base-64 编码和解码:
清单 3. 我的 Cryptographical 接口的一种 AES 实现
package com.b50.crypto; import sun.misc.BASE64Decoder; import sun.misc.BASE64Encoder; import javax.crypto.Cipher; import javax.crypto.NoSuchPaddingException; import java.security.InvalidKeyException; import java.security.Key; import java.security.NoSuchAlgorithmException; public class AESCryptoImpl implements Cryptographical { private Key key; private Cipher ecipher; private Cipher dcipher; private AESCryptoImpl(Key key) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException { this.key = key; this.ecipher = Cipher.getInstance("AES"); this.dcipher = Cipher.getInstance("AES"); this.ecipher.init(Cipher.ENCRYPT_MODE, key); this.dcipher.init(Cipher.DECRYPT_MODE, key); } public static Cryptographical initialize(CryptoKeyable key) throws CryptoException { try { return new AESCryptoImpl(key.getKey()); } catch (NoSuchAlgorithmException e) { throw new CryptoException(e); } catch (NoSuchPaddingException e) { throw new CryptoException(e); } catch (InvalidKeyException e) { throw new CryptoException(e); } } public String encrypt(String plaintext) { try { return new BASE64Encoder().encode(ecipher.doFinal(plaintext.getBytes("UTF8"))); } catch (Exception e) { throw new RuntimeException(e); } } public String decrypt(String ciphertext) { try { return new String(dcipher.doFinal(new BASE64Decoder().decodeBuffer(ciphertext)), "UTF8"); } catch (Exception e) { throw new RuntimeException(e); } } } |