1. 程式人生 > >整理的AES對稱加密和RSA非對稱加密

整理的AES對稱加密和RSA非對稱加密

專案用到這兩個加密方法,就整理了下做了個demo,這裡也貼出來程式碼供參考

AES加密解密

public class AESUtil {
    /**
     * 生成AES金鑰
     * @param strkey
     * @return
     * @throws Exception
     */
    public static String createKeyPairs(String strkey) 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(strkey.getBytes("UTF-8"));
        kgen.init(128, sr); //256 bits or 128 bits,192bits
        SecretKey skey = kgen.generateKey();
        byte[] raw = skey.getEncoded();
        Log.e("AES----KEY",new String(raw,"UTF-8"));
        return new String(raw);
    }
    /**
     * AES加密,傳入需要加密的明文和key
     * @param key
     * @param src
     * @return
     * @throws Exception
     */
    public static String encrypt(String key, String src) throws Exception {
        byte[] result = encrypt(key.getBytes("UTF-8"), src.getBytes("UTF-8"));
        return Base64.encodeToString(result, Base64.DEFAULT);
    }
    private static byte[] encrypt(byte[] key, byte[] src) throws Exception {
        SecretKeySpec skeySpec = new SecretKeySpec(key, "AES");
        Cipher cipher = Cipher.getInstance("AES");
        cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
        byte[] encrypted = cipher.doFinal(src);
        return encrypted;
    }

    /**
     * AES解密,傳入密文和對應的key
     * @param key
     * @param encrypted
     * @return
     * @throws Exception
     */
    public static String decrypt(String key, String encrypted) throws Exception {
        byte[] result = decrypt(key.getBytes(), Base64.decode(encrypted, Base64.DEFAULT));
        return new String(result,"UTF-8");
    }
    private static byte[] decrypt(byte[] key, byte[] encrypted) throws Exception {
        SecretKeySpec skeySpec = new SecretKeySpec(key, "AES");
        Cipher cipher = Cipher.getInstance("AES");
        cipher.init(Cipher.DECRYPT_MODE, skeySpec);
        byte[] decrypted = cipher.doFinal(encrypted);
        return decrypted;
    }
}
RSA加密解密
public class RSAUtil {
    /**
     * 生成經BASE64編碼後的RSA公鑰和私鑰
     */
    public static void createKeyPairs() {
        try {
            KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA");
            generator.initialize(1024, new SecureRandom());
            KeyPair pair = generator.generateKeyPair();
            PublicKey pubKey = pair.getPublic();
            PrivateKey privKey = pair.getPrivate();
            byte[] pubk = pubKey.getEncoded();
            byte[] privk = privKey.getEncoded();
            // base64編碼,遮蔽特殊字元
            String strpk = new String(Base64.encode(pubk,Base64.DEFAULT));
            String strprivk = new String(Base64.encode(privk,Base64.DEFAULT));
            Log.e("strpk", strpk);
            Log.e("strprivk", strprivk);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    /**
     * RSA公鑰加密
     * @param content	待加密的明文
     * @param pubKey	RSA公鑰
     * @return	經BASE64編碼後的密文
     */
    public static String pubKeyEnc(String content,String pubKey){
        try {
            KeyFactory keyf = KeyFactory.getInstance("RSA","BC");
            //獲取公鑰
            InputStream is = new ByteArrayInputStream(pubKey.getBytes("utf-8"));
            byte[] pubbytes = new byte[new Long(pubKey.length()).intValue()];
            is.read(pubbytes);
            X509EncodedKeySpec pubX509 = new X509EncodedKeySpec(Base64.decode(pubbytes,Base64.DEFAULT));
            PublicKey pkey = keyf.generatePublic(pubX509);

            //公鑰加密
            Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
            cipher.init(Cipher.ENCRYPT_MODE, pkey);
            byte[] cipherText = cipher.doFinal(content.getBytes());
            // 將加密結果轉換為Base64編碼結果;便於internet傳送
            return Base64.encodeToString(cipherText,Base64.DEFAULT);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }


    /**
     * RSA公鑰解密
     * @param ciphertext 經BASE64編碼過的待解密的密文
     * @param pubKey RSA公鑰
     * @return utf-8編碼的明文
     */
    public static String pubKeyDec(String ciphertext ,String pubKey){
        try {
            KeyFactory keyf = KeyFactory.getInstance("RSA","BC");

            //獲取公鑰
            InputStream is = new ByteArrayInputStream(pubKey.getBytes("utf-8"));
            byte[] pubbytes = new byte[new Long(pubKey.length()).intValue()];
            is.read(pubbytes);
            X509EncodedKeySpec pubX509 = new X509EncodedKeySpec(Base64.decode(pubbytes,Base64.DEFAULT));
            PublicKey pkey = keyf.generatePublic(pubX509);

            //公鑰解密
            Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
            cipher.init(Cipher.DECRYPT_MODE, pkey);
            byte[] text = cipher.doFinal(Base64.decode(ciphertext,Base64.DEFAULT));

            return new String(text,"UTF-8");
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }


    /**
     * RSA私鑰加密
     * @param content 待加密的明文
     * @param privKey RSA私鑰
     * @return	經BASE64編碼後的密文
     */
    public static String privKeyEnc(String content,String privKey){
        try {
            KeyFactory keyf = KeyFactory.getInstance("RSA","BC");

            //獲取私鑰
            InputStream key = new ByteArrayInputStream(privKey.getBytes("utf-8"));
            byte[] pribytes = new byte[new Long(privKey.length()).intValue()];
            key.read(pribytes);
            PKCS8EncodedKeySpec priPKCS8 = new PKCS8EncodedKeySpec(Base64.decode(pribytes,Base64.DEFAULT));
            PrivateKey prikey = keyf.generatePrivate(priPKCS8);

            //私鑰加密
            Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
            cipher.init(Cipher.ENCRYPT_MODE, prikey);
            byte[] cipherText = cipher.doFinal(content.getBytes());

            //將加密結果轉換為Base64編碼結果;便於internet傳送
            return Base64.encodeToString(cipherText,Base64.DEFAULT);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }


    /**
     * RSA私鑰解密
     * @param ciphertext	經BASE84編碼過的待解密密文
     * @param privKey	RSA私鑰
     * @return	utf-8編碼的明文
     */
    public static String privKeyDec(String ciphertext ,String privKey){
        try {
            KeyFactory keyf = KeyFactory.getInstance("RSA","BC");
//          獲取私鑰
            InputStream key = new ByteArrayInputStream(privKey.getBytes("utf-8"));
            byte[] pribytes = new byte[new Long(privKey.length()).intValue()];
            key.read(pribytes);
            byte[] buffer = Base64.decode(pribytes,Base64.DEFAULT);
            PKCS8EncodedKeySpec priPKCS8 = new PKCS8EncodedKeySpec(buffer);
            PrivateKey prikey = keyf.generatePrivate(priPKCS8);

            //私鑰解密
            Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
            cipher.init(Cipher.DECRYPT_MODE, prikey);
            byte[] text=Base64.decode(ciphertext,Base64.DEFAULT);
            byte[] content = cipher.doFinal(text);
            return new String(content,"UTF-8");
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }

    /**
     * RSA私鑰數字簽名
     * @param content 待籤內容
     * @param privKey RSA私鑰
     * @return 經BASE64編碼後的簽名串
     */
    public static String sign(String content,String privKey){
        try {
            KeyFactory keyf=KeyFactory.getInstance("RSA","BC");

            //獲取私鑰
            InputStream key = new ByteArrayInputStream(privKey.getBytes("utf-8"));
            byte[] pribytes = new byte[new Long(privKey.length()).intValue()];
            key.read(pribytes);
            PKCS8EncodedKeySpec priPKCS8 = new PKCS8EncodedKeySpec(Base64.decode(new String(pribytes),Base64.DEFAULT));
            PrivateKey priKey=keyf.generatePrivate(priPKCS8);

            //例項化Signature;簽名演算法:MD5withRSA
            Signature signature = Signature.getInstance("MD5withRSA");
            //初始化Signature
            signature.initSign(priKey);
            //更新
            signature.update(content.getBytes());
            return Base64.encodeToString(signature.sign(),Base64.DEFAULT);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }

    /**
     * RSA公鑰校驗數字簽名
     * @param content 待校驗的內容
     * @param pubKey RSA公鑰
     * @param signedStr 簽名字串
     * @return	true:校驗成功;false:校驗失敗
     */
    public static boolean verify(String content,String pubKey,String signedStr){
        try {
            //例項化金鑰工廠
            KeyFactory keyf=KeyFactory.getInstance("RSA","BC");

            //獲取公鑰
            InputStream is = new ByteArrayInputStream(pubKey.getBytes("utf-8"));
            byte[] pubbytes = new byte[new Long(pubKey.length()).intValue()];
            is.read(pubbytes);
            X509EncodedKeySpec pubX509 = new X509EncodedKeySpec(Base64.decode(new String(pubbytes),Base64.DEFAULT));
            PublicKey pkey = keyf.generatePublic(pubX509);

            //例項化Signature;簽名演算法:MD5withRSA
            Signature signature = Signature.getInstance("MD5withRSA");
            signature.initVerify(pkey);
            signature.update(content.getBytes());
            //驗證
            return signature.verify(Base64.decode(signedStr,Base64.DEFAULT));
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }

}

以上就是AES和RSA的實現。可以直接拿來用的

一般都是這兩種配合使用  AES加密先隨機生成一個KEY,然後用RSA對稱加密,將AES的KEY加密,在用AES對需要加密的文明進行加密。

下面將附加上demo

http://download.csdn.net/detail/sinat_23134455/9502953