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加解密的更多相关文章

  1. java与IOS之间的RSA加解密

    很简单的一个需求,ipad端给密码RSA加密,传到java后台,解密.RSA加密算法是基于一个密钥对的,分为公钥和私钥,一般情况公钥加密,私钥解密,但也可私钥加密,公钥解密.还可以验签,就是先用私钥对 ...

  2. openssl pem密钥文件rsa加密解密例子

    准备工作 命令行加密解密,用与比对代码中的算法和命令行的算法是否一致 C:\openssl_test>openssl rsautl -encrypt -in data.txt -inkey pu ...

  3. 前后端java+vue 实现rsa 加解密与摘要签名算法

    RSA 加密.解密.签名.验签.摘要,前后端java+vue联调测试通过 直接上代码 // 注意:加密密文与签名都是唯一的,不会变化.// 注意:vue 端密钥都要带pem格式.java 不要带pem ...

  4. rsa加解密的内容超长的问题解决

    一. 现象:      有一段老代码用来加密的,但是在使用key A的时候,抛出了异常:javax.crypto.IllegalBlockSizeException: Data must not be ...

  5. 全面解决.Net与Java互通时的RSA加解密问题,使用PEM格式的密钥文件

    作者: zyl910 一.缘由 RSA是一种常用的非对称加密算法.所以有时需要在不用编程语言中分别使用RSA的加密.解密.例如用Java做后台服务端,用C#开发桌面的客户端软件时. 由于 .Net.J ...

  6. Rsa加解密Java、C#、php通用代码 密钥转换工具

    之前发了一篇"TripleDes的加解密Java.C#.php通用代码",后面又有项目用到了Rsa加解密,还是在不同系统之间进行交互,Rsa在不同语言的密钥格式不一样,所以过程中主 ...

  7. 与非java语言使用RSA加解密遇到的问题:algid parse error, not a sequence

    遇到的问题 在一个与Ruby语言对接的项目中,决定使用RSA算法来作为数据传输的加密与签名算法.但是,在使用Ruby生成后给我的私钥时,却发生了异常:IOException: algid parse ...

  8. java RSA加解密以及用途

    在公司当前版本的中间件通信框架中,为了防止非授权第三方和到期客户端的连接,我们通过AES和RSA两种方式的加解密策略进行认证.对于非对称RSA加解密,因为其性能耗费较大,一般仅用于认证连接,不会用于每 ...

  9. RSA加解密算法以及密钥格式

    RSA算法: 有个文章关于RSA原理讲的不错: https://blog.csdn.net/dbs1215/article/details/48953589 http://www.ruanyifeng ...

随机推荐

  1. PHP __autoload函数知识点

    __autoload函数主要是用来包含不存在的类文件,当初始化的类不存在的时候 存在一个文件名为footer.php的文件,里面有个footer类 class footer{ public funct ...

  2. chmod 命令——chmod 755与chmod 4755区别(转)

    755和4755的区别 chmod是Linux下设置文件权限的命令,后面的数字表示不同用户或用户组的权限. 一般是三个数字:第一个数字表示文件所有者的权限第二个数字表示与文件所有者同属一个用户组的其他 ...

  3. php的一些小笔记--字符串

    字符串: 转换ASCII函数: ord($tring) 返回ASCII,chr($ASCII)返回相应的字符 把字符串切割成数据的函数: chunk_split($string,$len) chunk ...

  4. linux vim 常用命令

    一. VIM高亮 进入vim后,在普通模式下输入如下命令,开启php代码高亮显示 :syntax enable :source $VIMRUNTIME/syntax/php.vim二. VI常用命令_ ...

  5. UESTC_Frozen Rose-Heads CDOJ 791

    The winter is coming and all the experts are warning that it will be the coldest one in the last hun ...

  6. C#代码控制 zip rar 解压缩

    首先 解压ZIP的方法: #region 解压ZIP /// <summary> /// 解压ZIP /// </summary> /// <param name=&qu ...

  7. python2 和3的区别

    __future__ 模块 Python 3.x引入一些Python2不兼容的关键字和函数,可以通过在 Python2 内置的模块 __future__ 导入.建议如果你想在代码中支持 Python3 ...

  8. IOS添加多个按钮在导航栏

    UIView *customView = [[UIView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, 75.0f, 30.0f)]; UIButton * ...

  9. 使用lock_sga和pre_page_sga参数保证SGA常驻物理内存 .

    Lock_sga LOCK_SGA locks the entire SGA into physical memory. It is usually advisable to lock the SGA ...

  10. 那么温暖http合约,入门。

    简介 年提出.经过几年的使用与发展,得到不断地完好和扩展.眼下在WWW中使用的是HTTP/1.0的第六版,HTTP/1.1的规范化工作正在进行之中,并且HTTP-NG(Next Generation ...