AES加密避免踩坑的方法

jopen 8年前

 

本人是半路出家,从事Android开发的,在新的项目中,需要用到AES加密,由于对加密一窍不通,颇为折腾,专门针对那些对加密不熟悉的人,避免跟我踩到同样的坑。

之所以被踩坑,很大一部分原因是因为,网上很多AES加密的方法,很多,很多……

当加密的字段上传到服务端后,发现后端无法解密,于是以为是自己找的方法错误,继续找新的方法,很容易有找到新的方法,重新试,不行,再换,运气好,就成了,运气不好,就是无止境的循环,我这次在项目中,就是属于运气不好的

心酸历程就不说了,以下说重点:

加密失败的解决思路:

1、当你拿到一套加密的方法的时候,一般都有解密的方法,先试着自己加解密,如果你的方法自己都无法加解密,肯定你在网上找的方法有问题。

2、跟后端确认加密key的字符串,再次确认,这个不用说了

3、跟后端确认加密的位数,一般加密有128、256两种位数,位数错误怎么也加密不成功,如果你不知道自己的位数是多少,搜索128跟256,搜到了哪个,就说明是哪个位数了

4、如果还不行,确认加密的iv是否一致,我就是因为后端是用动态的iv,被整死的,后来改成固定的iv,调试通过了。

最后,附上一个AES加密的方法类,可以动态设置加密的位数和iv,有了此方法,可以不用管什么php,ios通用型,因为那些参数都是可以设置的,这个方法是被人写的,我只是copy过来, 原文查看这里

public class AES {  //-----類別常數-----  /**   * 預設的Initialization Vector,為16 Bits的0   */  private static final IvParameterSpec DEFAULT_IV = new IvParameterSpec(new byte[]{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0});  /**   * 加密演算法使用AES   */  private static final String ALGORITHM = "AES";  /**   * AES使用CBC模式與PKCS5Padding   */  private static final String TRANSFORMATION = "AES/CBC/PKCS5Padding";    //-----物件變數-----  /**   * 取得AES加解密的密鑰   */  private Key key;  /**   * AES CBC模式使用的Initialization Vector   */  private IvParameterSpec iv;  /**   * Cipher 物件   */  private Cipher cipher;    //-----建構子-----  /**   * 建構子,使用128 Bits的AES密鑰(計算任意長度密鑰的MD5)和預設IV   *   * @param key 傳入任意長度的AES密鑰   */  public AES(final String key) {      this(key, 128);  }    /**   * 建構子,使用128 Bits或是256 Bits的AES密鑰(計算任意長度密鑰的MD5或是SHA256)和預設IV   *   * @param key 傳入任意長度的AES密鑰   * @param bit 傳入AES密鑰長度,數值可以是128、256 (Bits)   */  public AES(final String key, final int bit) {      this(key, bit, null);  }    /**   * 建構子,使用128 Bits或是256 Bits的AES密鑰(計算任意長度密鑰的MD5或是SHA256),用MD5計算IV值   *   * @param key 傳入任意長度的AES密鑰   * @param bit 傳入AES密鑰長度,數值可以是128、256 (Bits)   * @param iv 傳入任意長度的IV字串   */  public AES(final String key, final int bit, final String iv) {      if (bit == 256) {          this.key = new SecretKeySpec(getHash("SHA-256", key), ALGORITHM);      } else {          this.key = new SecretKeySpec(getHash("MD5", key), ALGORITHM);      }      if (iv != null) {          this.iv = new IvParameterSpec(getHash("MD5", iv));      } else {          this.iv = DEFAULT_IV;      }        init();  }    //-----物件方法-----  /**   * 取得字串的雜湊值   *   * @param algorithm 傳入雜驟演算法   * @param text 傳入要雜湊的字串   * @return 傳回雜湊後資料內容   */  private static byte[] getHash(final String algorithm, final String text) {      try {          return getHash(algorithm, text.getBytes("UTF-8"));      } catch (final Exception ex) {          throw new RuntimeException(ex.getMessage());      }  }    /**   * 取得資料的雜湊值   *   * @param algorithm 傳入雜驟演算法   * @param data 傳入要雜湊的資料   * @return 傳回雜湊後資料內容   */  private static byte[] getHash(final String algorithm, final byte[] data) {      try {          final MessageDigest digest = MessageDigest.getInstance(algorithm);          digest.update(data);          return digest.digest();      } catch (final Exception ex) {          throw new RuntimeException(ex.getMessage());      }  }    /**   * 初始化   */  private void init() {      try {          cipher = Cipher.getInstance(TRANSFORMATION);      } catch (final Exception ex) {          throw new RuntimeException(ex.getMessage());      }  }    /**   * 加密文字   *   * @param str 傳入要加密的文字   * @return 傳回加密後的文字   */  public String encrypt(final String str) {      try {          return encrypt(str.getBytes("UTF-8"));      } catch (final Exception ex) {          throw new RuntimeException(ex.getMessage());      }  }    /**   * 加密資料   *   * @param data 傳入要加密的資料   * @return 傳回加密後的資料   */  public String encrypt(final byte[] data) {      try {          cipher.init(Cipher.ENCRYPT_MODE, key, iv);          final byte[] encryptData = cipher.doFinal(data);          return Base64.encodeToString(encryptData, Base64.DEFAULT);      } catch (final Exception ex) {          throw new RuntimeException(ex.getMessage());      }  }    /**   * 解密文字   *   * @param str 傳入要解密的文字   * @return 傳回解密後的文字   */  public String decrypt(final String str) {      try {          return decrypt(Base64.decode(str, Base64.DEFAULT));      } catch (final Exception ex) {          throw new RuntimeException(ex.getMessage());      }  }    /**   * 解密文字   *   * @param data 傳入要解密的資料   * @return 傳回解密後的文字   */  public String decrypt(final byte[] data) {      try {          cipher.init(Cipher.DECRYPT_MODE, key, iv);          final byte[] decryptData = cipher.doFinal(data);          return new String(decryptData, "UTF-8");      } catch (final Exception ex) {          throw new RuntimeException(ex.getMessage());      }  }}

使用方法就很简单了,这样:
AES aes = new AES(galleryUrls.ASE_ENCODE_KEY, 256, galleryUrls.ASE_IV);      String result = aes.encrypt(object.toString());

于是大功告成了,我被AES耽搁了整整两天,希望这篇文章对那些不熟悉AES加密的人员有所帮助。