Skip to content

Commit 4f24f76

Browse files
committed
master 优化数字签名的readme
1 parent 84ea658 commit 4f24f76

2 files changed

Lines changed: 57 additions & 4 deletions

File tree

.idea/workspace.xml

Lines changed: 1 addition & 1 deletion
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

README.md

Lines changed: 56 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -236,13 +236,66 @@ public class MacDemo {
236236
> 总结:
237237
>
238238
> 1. 数据通信
239-
>
240-
> ```
241239
> - 公钥加密, 私钥解密
242240
> 2. 数字签名:
243241
> - 私钥加密, 公钥解密
244-
> ```
242+
>
245243
246244
### 数字签名的方法
247245

248246
![Logo](imgs/3.png)
247+
248+
- 数字签名示例代码
249+
```$xslt
250+
public class SignatureDemo {
251+
public static void main(String[] args) throws Exception {
252+
String algorithm = "RSA";
253+
String priPath = "test.pri";
254+
String pubPath = "test.pub";
255+
String input = "frank";
256+
// RSAUtil.generateKeys(algorithm,priPath,pubPath);
257+
258+
PrivateKey privateKey = RSAUtil.getPrivateKey(priPath, algorithm);
259+
PublicKey publicKey = RSAUtil.getPublicKey(pubPath, algorithm);
260+
261+
String signatureAlgorithm = "SHA256withRSA";
262+
String signatured = getSignature(input, privateKey, signatureAlgorithm);
263+
264+
boolean verify = verifySignature(input, publicKey, signatureAlgorithm, signatured);
265+
System.out.println(verify);
266+
}
267+
268+
/**
269+
* 生成签名字符串
270+
* @param input 原文
271+
* @param privateKey 私钥
272+
* @param signatureAlgorithm 签名算法
273+
* @return
274+
* @throws Exception
275+
*/
276+
public static String getSignature(String input, PrivateKey privateKey, String signatureAlgorithm) throws Exception {
277+
Signature signature = Signature.getInstance(signatureAlgorithm);
278+
signature.initSign(privateKey);
279+
signature.update(input.getBytes());
280+
byte[] sign = signature.sign();
281+
return Base64.encode(sign);
282+
}
283+
284+
/**
285+
* 校验签名
286+
* @param input 原文
287+
* @param publicKey 公钥
288+
* @param signatureAlgorithm 签名算法
289+
* @param signatured 发送过来的签名
290+
* @return
291+
* @throws Exception
292+
*/
293+
public static boolean verifySignature(String input, PublicKey publicKey, String signatureAlgorithm, String signatured) throws Exception {
294+
Signature signature = Signature.getInstance(signatureAlgorithm);
295+
signature.initVerify(publicKey);
296+
signature.update(input.getBytes());
297+
return signature.verify(Base64.decode(signatured));
298+
299+
}
300+
}
301+
```

0 commit comments

Comments
 (0)