Android中AES加密解密。解决密文不唯一、解密不出明文问题

AES加密方式是目前来看值得选择的加密方式,但是在Android中使用AES加密时,有些坑看似不大,却让很多人栽了跟头。
Android 4.2之后SHA1PRNG强随意种子算法调用不同,需要区别调用,这个你造吗。
下面贴出部分关键代码,代码与网络上普遍存在的AES加密代码大同小异,不做过多解释。但是解决了那些大部分代码中存在的密文不唯一、解密不出明文的问题。

AESCrypt.java中关键代码

public byte[] getRawKey(byte[] seed) throws Exception {     
        KeyGenerator kgen = KeyGenerator.getInstance("AES");   
        // SHA1PRNG 强随机种子算法, 要区别4.2以上版本的调用方法 
         SecureRandom sr = null;  
       if (android.os.Build.VERSION.SDK_INT >=  17) {  
         sr = SecureRandom.getInstance("SHA1PRNG", "Crypto");  
       } else {  
         sr = SecureRandom.getInstance("SHA1PRNG");  
       }   
        sr.setSeed(seed);     
        kgen.init(AESUtil.ENCRYPT_BITS, sr); //256 bits or 128 bits,192 bits 
        SecretKey skey = kgen.generateKey();     
        byte[] raw = skey.getEncoded();     
        return raw;     
    } 

    public byte[] encrypting(byte[] raw, byte[] clear) throws Exception {
        SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
        Cipher cipher = Cipher.getInstance("AES");
        cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
        byte[] encrypted = cipher.doFinal(clear);
        return encrypted;
    }

    public byte[] decrypting(byte[] raw, byte[] encrypted) throws Exception {
        SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
        Cipher cipher = Cipher.getInstance("AES");
        cipher.init(Cipher.DECRYPT_MODE, skeySpec);
        byte[] decrypted = cipher.doFinal(encrypted);
        return decrypted;
    }

对外封装的AESUtil.java

    /** * 设置编码位数。可选值为:256、192、128 * @param encryptBits */
    public void setEncryptBits(int encryptBits){
        if(encryptBits==256||encryptBits==192||encryptBits==128){
            ENCRYPT_BITS = encryptBits;
        }
    }

    public String encrypt(String seed, String cleartext) throws Exception {
        byte[] rawKey = mAESCrypt.getRawKey(seed.getBytes());
        byte[] result = mAESCrypt.encrypting(rawKey, cleartext.getBytes());
        return mAESCrypt.toHex(result);
    }

    public String decrypt(String seed, String encrypted) throws Exception {
        byte[] rawKey = mAESCrypt.getRawKey(seed.getBytes());
        byte[] encryptedstr = mAESCrypt.toByte(encrypted);
        byte[] result = mAESCrypt.decrypting(rawKey, encryptedstr);
        return new String(result);
    }

完整源码下载 。

更多Android开发技术一起探讨学习,点我 。

更多Android开发资源直接下载,点我 。

你可能感兴趣的:(android,加密,解密,aes,加密解密正确)