java RSA生成公钥和私钥
1.随机生成密钥对

/**
* 随机生成密钥对
* @throws NoSuchAlgorithmException
*/
public static void genKeyPair() throws NoSuchAlgorithmException {
// KeyPairGenerator类用于生成公钥和私钥对,基于RSA算法生成对象
KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("RSA");
// 初始化密钥对生成器,密钥大小为96-1024位
keyPairGen.initialize(1024,new SecureRandom());
// 生成一个密钥对,保存在keyPair中
KeyPair keyPair = keyPairGen.generateKeyPair();
// 得到私钥
RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
// 得到公钥
RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
String publicKeyString = new String(Base64.encodeBase64(publicKey.getEncoded()));
// 得到私钥字符串
String privateKeyString = new String(Base64.encodeBase64((privateKey.getEncoded())));
// 将公钥和私钥保存到Map
//0表示公钥
keyMap.put(0,publicKeyString);
//1表示私钥
keyMap.put(1,privateKeyString);
}
2.RSA公钥加密

/**
* RSA公钥加密
* @param str 加密字符串
* @param publicKey 公钥
* @return 密文
* @throws Exception 加密过程中的异常信息
*
*/
public static String encrypt( String str, String publicKey ) throws Exception{
try {
//base64编码的公钥
byte[] decoded = Base64.decodeBase64(publicKey);
RSAPublicKey pubKey = (RSAPublicKey) KeyFactory.getInstance("RSA").generatePublic(new X509EncodedKeySpec(decoded));
//RSA加密
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.ENCRYPT_MODE, pubKey);
byte[] strBytes = str.getBytes("UTF-8");
int inputLength = strBytes.length;
System.out.println("加密字节数:" + inputLength);
// 最大加密字节数,超出最大字节数需要分组加密
// 标识
int offSet = 0;
byte[] resultBytes = {};
byte[] cache;
while (inputLength - offSet > 0) {
if (inputLength - offSet > MAX_ENCRYPT_BLOCK) {
cache = cipher.doFinal(strBytes, offSet, MAX_ENCRYPT_BLOCK);
offSet += MAX_ENCRYPT_BLOCK;
} else {
cache = cipher.doFinal(strBytes, offSet, inputLength - offSet);
offSet = inputLength;
}
resultBytes = Arrays.copyOf(resultBytes, resultBytes.length + cache.length);
System.arraycopy(cache, 0, resultBytes, resultBytes.length - cache.length, cache.length);
}
String outStr = Base64.encodeBase64String(resultBytes);
return outStr;
}catch (Exception e){
System.out.println("rsaEncrypt error:" + e.getMessage());
}
return "";
}
3.RSA私钥解密

/**
* RSA私钥解密
* @param str 加密字符串
* @param privateKey 私钥
* @return 铭文
* @throws Exception 解密过程中的异常信息
*/
public static String decrypt(String str, String privateKey) throws Exception{
//64位解码加密后的字符串
byte[] inputByte = Base64.decodeBase64(str.getBytes("UTF-8"));
//base64编码的私钥
byte[] decoded = Base64.decodeBase64(privateKey);
RSAPrivateKey priKey = (RSAPrivateKey) KeyFactory.getInstance("RSA").generatePrivate(new PKCS8EncodedKeySpec(decoded));
//RSA解密
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.DECRYPT_MODE, priKey);
ByteArrayOutputStream out = new ByteArrayOutputStream();
int inputLen = inputByte.length;
System.out.println("解密字节数:" + inputLen);
int offset = 0;
byte[] cache;
int i = 0;
// 对数据分段解密
while (inputLen - offset > 0) {
if (inputLen - offset > MAX_DECRYPT_BLOCK) {
cache = cipher.doFinal(inputByte, offset, MAX_DECRYPT_BLOCK);
} else {
cache = cipher.doFinal(inputByte, offset, inputLen - offset);
}
out.write(cache, 0, cache.length);
i++;
offset = i * MAX_DECRYPT_BLOCK;
}
byte[] decryptedData = out.toByteArray();
out.close();
// 解密后的内容
String outStr = new String(decryptedData);
return outStr;
}
4.使用
private static final Map<Integer,String> keyMap=new HashMap<>();
/**
* RSA最大加密明文大小
*/
private static final int MAX_ENCRYPT_BLOCK = 117;
/**
* RSA最大解密密文大小
*/
private static final int MAX_DECRYPT_BLOCK = 128;
/**
* @param args
* @throws Exception
*/
public static void main(String[] args) throws Exception {
//生成公钥和私钥
genKeyPair();
//加密字符串
String message = "sdaw";
System.out.println("随机生成的公钥为:" + keyMap.get(0));
System.out.println("随机生成的私钥为:" + keyMap.get(1));
String messageEn = encrypt(message,keyMap.get(0));
System.out.println(message + "\t加密后的字符串为:" + messageEn);
String messageDe = decrypt(messageEn,keyMap.get(1));
System.out.println("还原后的字符串为:" + messageDe);
}
java RSA生成公钥和私钥的更多相关文章
- Java RSA 生成公钥 私钥
目前为止,RSA是应用最多的公钥加密算法,能够抵抗已知的绝大多数密码攻击,已被ISO推荐为公钥数据加密标准. RSA算法中,每个通信主体都有两个钥匙,一个公钥(Public Key)用来对数据进行加密 ...
- java RSA 生成公钥私钥
/** * 引进的包都是Java自带的jar包 * 秘钥相关包 * base64 编解码 * 这里只用到了编码 */ import java.security.Key; import java.sec ...
- git 生成公钥、私钥方法与clone使用方法
我的配置流程 Git配置 Git安装完之后,需做git配置.打开git bash,分别执行以下两句命令 git config --global user.name "用户名" gi ...
- RSA的公钥、私钥
一.举个例子 1.发消息 用对方的公钥给对方发消息 2.发公告 发公告的时候,用自己的私钥形成签名! 二.加密和签名 RSA的公钥.私钥是互相对应的,RSA会生成两个密钥,你可以把任何一个用于公钥,然 ...
- Git简单生成生成公钥和私钥方法
Git简单生成生成公钥和私钥方法 Git配置 Git安装完之后,需做最后一步配置.打开git bash,分别执行以下两句命令 git config --global user.name “用户名” g ...
- GIT生成公钥和私钥
转载至:https://blog.csdn.net/gwz1196281550/article/details/80268200 打开 git bash! git config --global us ...
- Git安装与使用(windows环境)(一)----Git安装、生成公钥和私钥、添加SSH
安装 1.从官网下载git:http://git-scm.com/downloads 2.安装git,选择git组件安装,如下图 3.一直next,直到出现下面的窗口.这里是选择命令行形式.(可以理解 ...
- 使用keytool生成公钥、私钥、证书并且读取出来,使用私钥签名jar并验证(转)
参考链接:http://happyqing.iteye.com/blog/2139504 :https://blog.csdn.net/arjelarxfc/article/details/52461 ...
- openssl pem 生成公钥和私钥及文件
openssl pem.h 中提供了关于pem格式密钥对的操作接口 通常使用.pem的格式文件来保存openssl 生成的密钥对: 在终端下 cat xxx.pem 可以看到 p.p1 { margi ...
- MAC下用OPENSSL生成公钥和私钥
MAC OS自带了OpenSSL,所以不用去编译那一坨跟SHIT一样的源码.直接在命令行里使用OPENSSL就可以. 打开命令行工具,然后输入 openssl打开openssl,接着只要三句命令就可以 ...
随机推荐
- EXT GridPanel button 按钮 事件 方法 DirectMethod
C# 代码 //首页 Ext.Net.Button btnFirst = new Ext.Net.Button(); btnFirst.Icon = Icon.ControlStartBlue; bt ...
- Delphi之不可思议
1.--------不可思议的函数调用--开始- 开发环境D7 1 function TForm1.GetssA: string; 2 begin 3 Result:=Result+'AA'; 4 e ...
- jjencode|JS混淆手工解析编码过程以及自定义混淆变体改装
此前发布过关于aaencode的混淆编码,此篇文章继续说同作者的jjencode混淆编码的具体过程. 介绍 首先是jjencode的作者提供的编码测试页:http://utf-8.jp/public/ ...
- 8-WebShell总结
WebShell 1.webshell介绍 在计算机科学中,Shell 俗称壳(用来区别"核"),是指"为使用者提供操作界面"的软件(命令解释器).类似于win ...
- 转载:谷歌浏览器一些https打不开点击高级不行的解决办法
转载:https://blog.51cto.com/u_15275035/2925642 关于谷歌浏览器一些https网站打不开点击高级不行的解决办法有些url,在谷歌浏览器上打不开,点击高级也没有继 ...
- 事与愿违( backfire effect ) 的故事
例如:我作为一个需求者,我想要买世界上最便宜的苹果手机,但是当我进入市场去寻找世界上最便宜苹果手机的时候,这一行为本身就使得苹果手机的价格上升. 作为供应者,我本来要去卖最贵的房子,但是当我作为开发商 ...
- warning: the `gets' function is dangerous and should not be used.
LINUX下编译C程序时,出现了:warning: the `gets' function is dangerous and should not be used. 原因:Linux 下gcc编译器不 ...
- nios verify failed 问题解决。
nios 调试时碰到上图所示问题.根据下载地址可以判断下载flash.sdram都成功,这里说明电路设计和焊接都没有问题. 但是在flash地址verify failed between adress ...
- grpc - 使用
grpc 工具 BloomRPC GRPC - 使用 protobuf 定义protobuf,并将protobuf文件,通过java的plugin打包生成java-grpc相关文件.参照:grpc-p ...
- 【转载】Python:logging详细版
转载自:https://www.cnblogs.com/Nicholas0707/p/9021672.html 一.logging模块 (一).日志相关概念 日志是一种可以追踪某些软件运行时所发生事件 ...