Android AES算法示例

@SuppressLint("NewApi")

     public static String encryptAES(String seed, String cleartext) throws Exception {      
         byte[] rawKey = getRawKey(seed.getBytes("UTF-8"));      
         byte[] result = encryptAES(rawKey, cleartext.getBytes("UTF-8"));   
         return new String(Base64.encode(result, 0));
         //return toHex_0(result);      
     }      
     
    private static byte[] encryptAES(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 static String decryptAES(String seed, String encrypted) throws Exception {      
         byte[] rawKey = getRawKey(seed.getBytes("UTF-8"));  
         byte[] enc = Base64.decode(encrypted, 0);
         //byte[] enc = toByte_0(encrypted);      
         byte[] result = decryptAES(rawKey, enc);      
         return new String(result, "UTF-8");      
     }        
     
    private static byte[] decryptAES(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;      
    }
      
     private static byte[] getRawKey(byte[] seed) throws Exception {      
         KeyGenerator kgen = KeyGenerator.getInstance("AES");      
         SecureRandom sr = SecureRandom.getInstance("SHA1PRNG", "Crypto");      
         sr.setSeed(seed);      
         kgen.init(128, sr); // 192 and 256 bits may not be available      
         SecretKey skey = kgen.generateKey();      
         byte[] raw = skey.getEncoded();      
         return raw;      

     }      



调用方法:

pw = "密钥xxxx"

String miwen = RegisterActivity.encryptAES(pw,  yuanwen);

String yuanwen = RegisterActivity.decryptAES(pw, miwen);


参考:

http://blog.csdn.net/randyjiawenjie/article/details/6587986

http://my.eoe.cn/elvnxuan/archive/2160.html

http://www.iteye.com/problems/35327


个人理解每次加密后密文不一样是正常的,对称加密算法只要密钥一致就行。

用DES加密的时候,最后一位长度不足64的,它会自动填补到64,那么在我们进行字节数组到字串的转化过程中,

可能把它填补的不可见字符改变了,所以引发系统抛出异常。问题找到,怎么解决呢?

大家还记得邮件传输通常会把一些信息编码保存,对了,就是Base64,那样保证了信息的完整性,所以我们就是利用一下下了。


By tiandyoin:

http://write.blog.csdn.net/postedit/23096187

2014年4月7日

你可能感兴趣的:(Android AES算法示例)