整理的AES对称加密和RSA非对称加密

4 篇文章 0 订阅
1 篇文章 0 订阅

项目用到这两个加密方法,就整理了下做了个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

  • 3
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
双向 RSA + AES 加密是一种常见的加密方式,其中使用 RSA 算法加密 AES 密钥,然后使用 AES 算法加密数据。在 C# 中,可以使用 `RSACryptoServiceProvider` 类和 `AesCryptoServiceProvider` 类来实现此加密方式。以下是一个简单的示例: ```csharp using System; using System.IO; using System.Security.Cryptography; using System.Text; class Program { static void Main(string[] args) { string plainText = "Hello, world!"; byte[] encryptedData = Encrypt(plainText); string decryptedText = Decrypt(encryptedData); Console.WriteLine("Original text: {0}", plainText); Console.WriteLine("Encrypted data: {0}", Convert.ToBase64String(encryptedData)); Console.WriteLine("Decrypted text: {0}", decryptedText); } static byte[] Encrypt(string plainText) { byte[] aesKey = GenerateAesKey(); using (var rsa = new RSACryptoServiceProvider()) { rsa.PersistKeyInCsp = false; byte[] encryptedAesKey = rsa.Encrypt(aesKey, true); // 使用 RSA 加密 AES 密钥 using (var aes = new AesCryptoServiceProvider()) { aes.Key = aesKey; aes.GenerateIV(); using (var memoryStream = new MemoryStream()) { memoryStream.Write(aes.IV, 0, aes.IV.Length); using (var cryptoStream = new CryptoStream(memoryStream, aes.CreateEncryptor(), CryptoStreamMode.Write)) { byte[] plainData = Encoding.UTF8.GetBytes(plainText); cryptoStream.Write(plainData, 0, plainData.Length); cryptoStream.FlushFinalBlock(); } byte[] encryptedData = memoryStream.ToArray(); byte[] result = new byte[encryptedAesKey.Length + encryptedData.Length]; Buffer.BlockCopy(encryptedAesKey, 0, result, 0, encryptedAesKey.Length); Buffer.BlockCopy(encryptedData, 0, result, encryptedAesKey.Length, encryptedData.Length); return result; } } } } static string Decrypt(byte[] encryptedData) { byte[] encryptedAesKey = new byte[128]; // RSA 加密 AES 密钥得到的密文长度为 128 字节 byte[] encryptedDataOnly = new byte[encryptedData.Length - encryptedAesKey.Length]; Buffer.BlockCopy(encryptedData, 0, encryptedAesKey, 0, encryptedAesKey.Length); Buffer.BlockCopy(encryptedData, encryptedAesKey.Length, encryptedDataOnly, 0, encryptedDataOnly.Length); using (var rsa = new RSACryptoServiceProvider()) { rsa.PersistKeyInCsp = false; byte[] aesKey = rsa.Decrypt(encryptedAesKey, true); // 使用 RSA 解密 AES 密钥 using (var aes = new AesCryptoServiceProvider()) { aes.Key = aesKey; aes.IV = encryptedDataOnly.Take(aes.IV.Length).ToArray(); using (var memoryStream = new MemoryStream()) { using (var cryptoStream = new CryptoStream(memoryStream, aes.CreateDecryptor(), CryptoStreamMode.Write)) { cryptoStream.Write(encryptedDataOnly, aes.IV.Length, encryptedDataOnly.Length - aes.IV.Length); cryptoStream.FlushFinalBlock(); } byte[] decryptedData = memoryStream.ToArray(); return Encoding.UTF8.GetString(decryptedData); } } } } static byte[] GenerateAesKey() { using (var aes = new AesCryptoServiceProvider()) { aes.GenerateKey(); return aes.Key; } } } ``` 上面的代码中,首先调用 `GenerateAesKey` 方法生成 AES 密钥,然后使用 RSA 算法加密 AES 密钥。加密时,先将 AES 密钥使用 RSA 加密,然后使用 AES 算法加密数据。具体来说,将 AES 密钥和 IV 都写入 `MemoryStream` 对象中,然后使用 `CryptoStream` 对象将数据写入 `MemoryStream` 对象中。最后将密文和 RSA 加密的 AES 密钥一起返回。 解密时,先从密文中取出 RSA 加密的 AES 密钥,然后使用 RSA 算法解密 AES 密钥。解密时,先从密文中取出 AES 的 IV 值,然后使用 `CryptoStream` 对象将数据解密。最后将解密后的文本返回。 注意,上面的示例仅用于演示 RSA + AES 加密的基本原理,实际使用中还需要考虑安全性等因素。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值