zoukankan      html  css  js  c++  java
  • java 使用pem密钥进行RSA加解密

    1.使用openssl生成私钥和公钥

       openssl下载地址:http://www.openssl.org/source

       openssl生成私钥命令:  genrsa -out rsa_private_key.pem 1024

       openssl生成公钥命令:  rsa -in rsa_private_key.pem -pubout -out rsa_public_key.pem

    2.此时在openssl安装目录下的bin文件夹可以看到 rsa_private_key.pem 和 rsa_public_key.pem 两个文件。这时候的私钥是不能直接使用的,需要进行 pkcs8 编码

       openssl的pkcs8编码命令:pkcs8 -topk8 -in rsa_private_key.pem -out pkcs8_rsa_private_key.pem -nocrypt

       那么在bin文件夹可以看到 pkcs8_rsa_private_key.pem 文件。至此,可用的密钥对已经生成好了,私钥使用pkcs8_rsa_private_key.pem,公钥采用rsa_public_key.pem。

    3.使用密钥对进行签名、加解密

    public class RSAPemCoder {
        public static final String KEY_SHA = "SHA";   
        public static final String KEY_MD5 = "MD5";
        public static final String KEY_ALGORITHM = "RSA";
        public static final String SIGNATURE_ALGORITHM = "MD5withRSA";
    
        /**
         * 用私钥对信息生成数字签名
         *
         * @param data 加密数据
         * @param privateKey 私钥
         * @return
         * @throws Exception
         */
        public static String sign(byte[] data, PrivateKey privateKey) throws Exception {  
            Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);
            signature.initSign(privateKey);
            signature.update(data);
            return encryptBASE64(signature.sign());
        }
    
        /**
         * 校验数字签名
         *
         * @param data 加密数据
         * @param publicKey 公钥
         * @param sign 数字签名
         * @return 校验成功返回true 失败返回false
         * @throws Exception
         */
        public static boolean verify(byte[] data, PublicKey publicKey, String sign) throws Exception {
            Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);
            signature.initVerify(publicKey);
            signature.update(data);
            return signature.verify(decryptBASE64(sign));
        }
    
        /**
         * 私钥解密
         *
         * @param data 密文
         * @param PrivateKey 私钥
         * @return
         * @throws Exception
         */
        public static byte[] decryptByPrivateKey(byte[] data, PrivateKey privateKey) throws Exception {
            KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
            Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
            cipher.init(Cipher.DECRYPT_MODE, privateKey);
            return cipher.doFinal(data);
        }
    
        /**
         * 用公钥解密
         *
         * @param data 密文
         * @param publicKey 公钥 
         * @return
         * @throws Exception
         */
        public static byte[] decryptByPublicKey(byte[] data, PublicKey publicKey) throws Exception {
            KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
            Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
            cipher.init(Cipher.DECRYPT_MODE, publicKey);
            return cipher.doFinal(data);
        }
    
        /**
         * 用公钥加密
         *
         * @param data 明文
         * @param PublicKey 公钥
         * @return
         * @throws Exception
         */
        public static byte[] encryptByPublicKey(byte[] data, PublicKey publicKey) throws Exception {
            KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
            Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
            cipher.init(Cipher.ENCRYPT_MODE, publicKey);
            return cipher.doFinal(data);
        }
    
        /**
         * 用私钥加密
         *
         * @param data 明文
         * @param privateKey 私钥
         * @return
         * @throws Exception
         */
        public static byte[] encryptByPrivateKey(byte[] data, PrivateKey privateKey) throws Exception {
            KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
            Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
            cipher.init(Cipher.ENCRYPT_MODE, privateKey);
            return cipher.doFinal(data);
        }
    
        public static PrivateKey getPrivateKeyFromPem() throws Exception {
            BufferedReader br = new BufferedReader(new FileReader("e:/pkcs8_privatekey.pem"));
            String s = br.readLine();
            String str = "";
            s = br.readLine();
            while (s.charAt(0) != '-') {
                str += s + "
    ";
                s = br.readLine();
            }
            BASE64Decoder base64decoder = new BASE64Decoder();
            byte[] b = base64decoder.decodeBuffer(str);
    
            // 生成私匙  
            KeyFactory kf = KeyFactory.getInstance("RSA");
            PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(b);
            PrivateKey privateKey = kf.generatePrivate(keySpec);
            return privateKey;
        }
    
        public static PublicKey getPublicKeyFromPem() throws Exception {
            BufferedReader br = new BufferedReader(new FileReader("e:/publickey.pem"));
            String s = br.readLine();
            String str = "";
            s = br.readLine();
            while (s.charAt(0) != '-') {
                str += s + "
    ";
                s = br.readLine();
            }
            BASE64Decoder base64decoder = new BASE64Decoder();
            byte[] b = base64decoder.decodeBuffer(str);
            KeyFactory kf = KeyFactory.getInstance("RSA");
            X509EncodedKeySpec keySpec = new X509EncodedKeySpec(b);
            PublicKey pubKey = kf.generatePublic(keySpec);
            return pubKey;
        }
        
        public static byte[] decryptBASE64(String key) throws Exception {   
            return (new BASE64Decoder()).decodeBuffer(key);   
        }   
      
        public static String encryptBASE64(byte[] key) throws Exception {   
            return (new BASE64Encoder()).encodeBuffer(key);   
        }   
    
        public static byte[] encryptMD5(byte[] data) throws Exception {   
      
            MessageDigest md5 = MessageDigest.getInstance(KEY_MD5);   
            md5.update(data);   
      
            return md5.digest();   
      
        }   
      
        public static byte[] encryptSHA(byte[] data) throws Exception {   
      
            MessageDigest sha = MessageDigest.getInstance(KEY_SHA);   
            sha.update(data);   
      
            return sha.digest();   
      
        }   
    }
  • 相关阅读:
    【刷题】面筋-mysql-如何对数据库进行备份
    【刷题】面筋-数据库-mysql的优化
    【刷题】面筋-MySQL中char、varchar和text三者的区别
    【刷题】面筋-sql-学生成绩单里两门成绩>80的学生名字
    【刷题】面筋-网络-无效链接,死链接,错误链接
    【刷题】面筋-算法-在海量IP中找出访问次数最多的100个IP
    【刷题】面筋-shell:统计一个文件中重复的行和重复次数
    【刷题】面筋-linux-如何查找出现频率最高的100个ip地址
    【刷题】面筋-linux 如何将文件从一台服务器转移到另一台服务器
    【刷题】面筋-Linux-vi显示或关闭行号:set number
  • 原文地址:https://www.cnblogs.com/vicent/p/3805722.html
Copyright © 2011-2022 走看看