AES加密--适用于RC2、RC4和Blowfish

package test;

import java.security.GeneralSecurityException;
import java.security.Key;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

public class AESCoder {

        public static final String KEY_ALGORITHM= "AES";
       
        public static final String CIPHER_ALGORITHM= "AES/EBC/PKCS5Padding";
       
        //密钥算法
        private static Key toKey(byte[] key){
              SecretKey secretkey = new SecretKeySpec(key,KEY_ALGORITHM);
               return secretkey;
       }
       
        public static byte[] decrypt(byte[] data, byte[] key) throws Exception, GeneralSecurityException{
              Key k= toKey(key);
              Cipher cipher=Cipher. getInstance(CIPHER_ALGORITHM);
              cipher.init(Cipher. DECRYPT_MODE, k);
               return cipher.doFinal(data);
       }
       
        public static byte[] encrytp(byte[] data, byte[] key) throws Exception, GeneralSecurityException{
              
              Key k= toKey(key);
              
              Cipher cipher=Cipher. getInstance(CIPHER_ALGORITHM);
              
              cipher.init(Cipher. ENCRYPT_MODE, k);
               return cipher.doFinal(data);
       }
       
        public static byte[] initKey() throws Exception{
              KeyGenerator kg=KeyGenerator. getInstance(KEY_ALGORITHM);
              kg.init(256);
              SecretKey secretKey=kg.generateKey();
               //获取密钥的二进制编码形式
               return secretKey.getEncoded();
       }
}
对密钥规范的要求降低了,无需实现密钥规范类。
posted @ 2014-08-30 11:21  徐小鱼  阅读(846)  评论(0编辑  收藏  举报