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() != '-') {
            str += s + "\r";
            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() != '-') {
            str += s + "\r";
            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();   
    }
}
java 使用pem密钥进行RSA加解密的更多相关文章
- java与IOS之间的RSA加解密
		
很简单的一个需求,ipad端给密码RSA加密,传到java后台,解密.RSA加密算法是基于一个密钥对的,分为公钥和私钥,一般情况公钥加密,私钥解密,但也可私钥加密,公钥解密.还可以验签,就是先用私钥对 ...
 - openssl pem密钥文件rsa加密解密例子
		
准备工作 命令行加密解密,用与比对代码中的算法和命令行的算法是否一致 C:\openssl_test>openssl rsautl -encrypt -in data.txt -inkey pu ...
 - 前后端java+vue 实现rsa 加解密与摘要签名算法
		
RSA 加密.解密.签名.验签.摘要,前后端java+vue联调测试通过 直接上代码 // 注意:加密密文与签名都是唯一的,不会变化.// 注意:vue 端密钥都要带pem格式.java 不要带pem ...
 - rsa加解密的内容超长的问题解决
		
一. 现象: 有一段老代码用来加密的,但是在使用key A的时候,抛出了异常:javax.crypto.IllegalBlockSizeException: Data must not be ...
 - 全面解决.Net与Java互通时的RSA加解密问题,使用PEM格式的密钥文件
		
作者: zyl910 一.缘由 RSA是一种常用的非对称加密算法.所以有时需要在不用编程语言中分别使用RSA的加密.解密.例如用Java做后台服务端,用C#开发桌面的客户端软件时. 由于 .Net.J ...
 - Rsa加解密Java、C#、php通用代码  密钥转换工具
		
之前发了一篇"TripleDes的加解密Java.C#.php通用代码",后面又有项目用到了Rsa加解密,还是在不同系统之间进行交互,Rsa在不同语言的密钥格式不一样,所以过程中主 ...
 - 与非java语言使用RSA加解密遇到的问题:algid parse error, not a sequence
		
遇到的问题 在一个与Ruby语言对接的项目中,决定使用RSA算法来作为数据传输的加密与签名算法.但是,在使用Ruby生成后给我的私钥时,却发生了异常:IOException: algid parse ...
 - java RSA加解密以及用途
		
在公司当前版本的中间件通信框架中,为了防止非授权第三方和到期客户端的连接,我们通过AES和RSA两种方式的加解密策略进行认证.对于非对称RSA加解密,因为其性能耗费较大,一般仅用于认证连接,不会用于每 ...
 - RSA加解密算法以及密钥格式
		
RSA算法: 有个文章关于RSA原理讲的不错: https://blog.csdn.net/dbs1215/article/details/48953589 http://www.ruanyifeng ...
 
随机推荐
- php对数组中指定键值排序
			
function array_sort($arr,$keys,$type='asc'){ $keysvalue = $new_array = array(); foreach ($arr as $k= ...
 - MAC OS中使用ll,la命令
			
在linux下习惯了使用ll.la等ls别名 用mac os发现没有这样的命令,很不方便. 其实只要在用户目录下建立一个脚本“.bash_profile”,并输入以下内容即可:alias ll='ls ...
 - ajax创建对象
			
<script> function createAjax(){ var request=false; //window对象中有X ...
 - HTML5 JavaScript 文件上传
			
function fileUpload(targetUrl) { // 隐藏表单名称 var inputName = '_fileselect'; // 文件尺寸 this.fileSize = 0; ...
 - Python之路第十三天,高级(7)-详述数据库一对多,多对多表关系的设计以及如何查询
			
一对多表设计和查询方法 #!/usr/bin/env python3 # Author: Zhangxunan from sqlalchemy import create_engine from sq ...
 - python连接postgresql数据库
			
python可以通过第三方模块连接postgresql. 比较有名的有psycopg2 和python3-postgresql (一)psycopg2 ubuntu下安装 sudo apt-get ...
 - 利用Azure Automation实现云端自动化运维(1)
			
Azure Automation是Azure上的一个自动化工作流引擎,基于Powershell,来帮助用户简化,集成和自动化Azure上的运维工作,例如: 实现定时开关虚拟机,节约成本 实现定时创建删 ...
 - OSA-MAC: A MAC Protocol for Opportunistic Spectrum Access in Cognitive Radio Networks
			
This full text paper was peer reviewed at the direction of IEEE Communications Society subject matte ...
 - POP3、SMTP、IMAP和Exchange都是个什么玩意?
			
很多时候一直对POP3.SMTP.IMAP和Exchange等迷迷糊糊的.下面就整理说明一下: 当前常用的电子邮件协议有SMTP.POP3.IMAP4,它们都隶属于TCP/IP协议簇,默认状态下,分别 ...
 - 关于WPF中承载 ArcGIS控件。
			
原文 http://www.cnblogs.com/zoe-j/archive/2011/05/18/2050208.html 之前就做过WPF的应用,之前承载的MapGIS的二次开发控件,今天写一下 ...