Skip to content
体验新版
项目
组织
正在加载...
登录
切换导航
打开侧边栏
一只小余
Java--RSA算法
提交
7733c45a
J
Java--RSA算法
项目概览
一只小余
/
Java--RSA算法
与 Fork 源项目一致
Fork自
inscode / Java
通知
1
Star
1
Fork
0
代码
文件
提交
分支
Tags
贡献者
分支图
Diff
Issue
0
列表
看板
标记
里程碑
合并请求
0
DevOps
流水线
流水线任务
计划
Wiki
0
Wiki
分析
仓库
DevOps
项目成员
Pages
J
Java--RSA算法
项目概览
项目概览
详情
发布
仓库
仓库
文件
提交
分支
标签
贡献者
分支图
比较
Issue
0
Issue
0
列表
看板
标记
里程碑
合并请求
0
合并请求
0
Pages
DevOps
DevOps
流水线
流水线任务
计划
分析
分析
仓库分析
DevOps
Wiki
0
Wiki
成员
成员
收起侧边栏
关闭侧边栏
动态
分支图
创建新Issue
流水线任务
提交
Issue看板
提交
7733c45a
编写于
5月 09, 2023
作者:
6
64586190168b7e02f64e79c2
浏览文件
操作
浏览文件
下载
电子邮件补丁
差异文件
Auto commit
上级
16c07c66
变更
1
隐藏空白更改
内联
并排
Showing
1 changed file
with
75 addition
and
0 deletion
+75
-0
RSA.java
RSA.java
+75
-0
未找到文件。
RSA.java
0 → 100644
浏览文件 @
7733c45a
public
class
RSA
{
private
final
PublicKey
publicKey
;
private
final
PrivateKey
privateKey
;
/**
* 自定义公钥和私钥
* @param n 公钥和私钥的n
* @param e 公钥的e
* @param d 私钥的d
*/
public
RSA
(
BigInteger
n
,
BigInteger
e
,
BigInteger
d
){
RSAPublicKeySpec
publicKeySpec
=
new
RSAPublicKeySpec
(
n
,
e
);
RSAPrivateKeySpec
privateKeySpec
=
new
RSAPrivateKeySpec
(
n
,
d
);
try
{
KeyFactory
rsa
=
KeyFactory
.
getInstance
(
"RSA"
);
publicKey
=
rsa
.
generatePublic
(
publicKeySpec
);
privateKey
=
rsa
.
generatePrivate
(
privateKeySpec
);
}
catch
(
Exception
ex
)
{
throw
new
RuntimeException
(
ex
);
}
}
/**
* 指定密钥大小生成公钥和私钥
* @param keySize 密钥大小
*/
public
RSA
(
int
keySize
){
try
{
KeyPairGenerator
keyGenerator
=
KeyPairGenerator
.
getInstance
(
"RSA"
);
keyGenerator
.
initialize
(
keySize
);
KeyPair
keyPair
=
keyGenerator
.
generateKeyPair
();
publicKey
=
keyPair
.
getPublic
();
privateKey
=
keyPair
.
getPrivate
();
System
.
out
.
println
(
"publicKey = "
+
Base64
.
getEncoder
().
encodeToString
(
publicKey
.
getEncoded
()));
System
.
out
.
println
(
"privateKey = "
+
Base64
.
getEncoder
().
encodeToString
(
privateKey
.
getEncoded
()));
}
catch
(
NoSuchAlgorithmException
ex
)
{
throw
new
RuntimeException
(
ex
);
}
}
/**
* 获取密文
* @param plainText 明文
* @return 密文
*/
public
String
encode
(
String
plainText
){
try
{
Cipher
cipher
=
getInstance
(
"RSA"
);
cipher
.
init
(
Cipher
.
ENCRYPT_MODE
,
publicKey
);
byte
[]
bytes
=
cipher
.
doFinal
(
plainText
.
getBytes
());
return
Base64
.
getEncoder
().
encodeToString
(
bytes
);
}
catch
(
Exception
e
)
{
throw
new
RuntimeException
(
e
);
}
}
/**
* 获取明文
* @param cipherText 密文
* @return 明文
*/
public
String
decode
(
String
cipherText
){
try
{
Cipher
cipher
=
getInstance
(
"RSA"
);
cipher
.
init
(
Cipher
.
DECRYPT_MODE
,
privateKey
);
byte
[]
bytes
=
cipher
.
doFinal
(
Base64
.
getDecoder
().
decode
(
cipherText
));
return
new
String
(
bytes
);
}
catch
(
Exception
ex
)
{
throw
new
RuntimeException
(
ex
);
}
}
}
编辑
预览
Markdown
is supported
0%
请重试
或
添加新附件
.
添加附件
取消
You are about to add
0
people
to the discussion. Proceed with caution.
先完成此消息的编辑!
取消
想要评论请
注册
或
登录