© 版权声明:本文为博主原创文章,转载请注明出处

实例

1.项目结构

java数字签名算法之RSA-LMLPHP

2.pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>org.security</groupId>
<artifactId>DigitalSignature</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging> <properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties> <dependencies>
<!-- junit -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<!-- commons-codec -->
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
<version>1.10</version>
</dependency>
</dependencies>
</project>

3.RSA.java

package org.security.rsa;

import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.Signature;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.HashMap;
import java.util.Map; import org.apache.commons.codec.binary.Base64; public class RSA { private static final String str = "Digital signature algorithm RSA MD5WithRSA"; private static final String SECURITY = "RSA";// 加密方式
private static final String ALGORITHM = "MD5withRSA";// 加密算法
private static final String PUBLIC_KEY = "RSAPublicKey";// 公钥
private static final String PRIVATE_KEY = "RSAPrivateKey";// 秘钥 public static void main(String[] args) { System.out.println("==========初始化密钥信息==========");
Map<String, Object> map = RSA.init();
System.out.println("=========密钥信息初始化成功=========");
byte[] private_key = RSA.getPrivateKey(map);
System.out.println("=============私钥为=============\n" + Base64.encodeBase64String(private_key));
byte[] public_key = RSA.getPublicKey(map);
System.out.println("=============公钥为=============\n" + Base64.encodeBase64String(public_key));
byte[] bs = RSA.sign(private_key);
System.out.println("=============签名为=============\n" + Base64.encodeBase64String(bs));
boolean result = RSA.verify(public_key, bs);
System.out.println("===========签名验证结果===========\n" + result); } /**
* 初始化密钥
*
* @return
*/
private static Map<String, Object> init() { Map<String, Object> map = null;
try {
// 生成实现指定算法的KeyPairGenerator对象,用于生成密钥对
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(SECURITY);
keyPairGenerator.initialize(1024);// 初始化密钥长度
KeyPair keyPair = keyPairGenerator.generateKeyPair();// 生成密钥对
RSAPublicKey rsaPublicKey = (RSAPublicKey) keyPair.getPublic();// 获取公钥
RSAPrivateKey rsaPrivateKey = (RSAPrivateKey) keyPair.getPrivate();// 获取私钥 // 保存到map中
map = new HashMap<String, Object>();
map.put(PUBLIC_KEY, rsaPublicKey);
map.put(PRIVATE_KEY, rsaPrivateKey);
} catch (Exception e) {
e.printStackTrace();
}
return map; } /**
* 用私钥生成签名
*
* @param privateKey
* 私钥字节数组
* @return
*/
private static byte[] sign(byte[] privateKey) { byte[] signByte = null;
try {
// 根据给定的编码密钥创建一个新的PKCS8EncodedKeySpec对象,指定PKCS#8标准为密钥规范管理的编码格式
PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(privateKey);
// 实例化密钥工厂对象,将密钥转换成密钥规范
KeyFactory keyFactory = KeyFactory.getInstance(SECURITY);
// 根据提供的密钥规范生成私钥对象
PrivateKey key = keyFactory.generatePrivate(pkcs8EncodedKeySpec);
// 实例化实现指定签名算法的Signature对象
Signature signature = Signature.getInstance(ALGORITHM);
// 根据私钥对象初始化签名对象
signature.initSign(key);
// 使用指定的byte数组更新要签名或验证的数据
signature.update(str.getBytes());
// 返回所有已更新数据的签名字节
signByte = signature.sign();
} catch (Exception e) {
e.printStackTrace();
}
return signByte; } /**
* 用公钥验证签名
*
* @param publicKey
* 公钥字节数组
* @param signByte
* 签名字节数组
* @return
*/
public static boolean verify(byte[] publicKey, byte[] signByte) { boolean result = false;
try {
// 根据给定的编码密钥创建一个新的X509EncodedKeySpec对象
X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(publicKey);
// 实例化密钥工厂对象,将密钥转换成密钥规范
KeyFactory keyFactory = KeyFactory.getInstance(SECURITY);
// 根据提供的密钥规范生成公钥对象
PublicKey key = keyFactory.generatePublic(x509EncodedKeySpec);
// 实例化实现指定签名算法的Signature对象
Signature signature = Signature.getInstance(ALGORITHM);
// 根据公钥对象初始化用于验证的对象
signature.initVerify(key);
// 使用指定的byte数组更新要签名或验证的数据
signature.update(str.getBytes());
// 验证传入的签名
result = signature.verify(signByte);
} catch (Exception e) {
e.printStackTrace();
}
return result; } /**
* 获取私钥
*
* @param map
* 密钥map集合
* @return
*/
public static byte[] getPrivateKey(Map<String, Object> map) { RSAPrivateKey key = (RSAPrivateKey) map.get(PRIVATE_KEY);
return key.getEncoded(); } /**
* 获取私钥
*
* @param map
* 密钥map集合
* @return
*/
public static byte[] getPublicKey(Map<String, Object> map) { RSAPublicKey key = (RSAPublicKey) map.get(PUBLIC_KEY);
return key.getEncoded(); } }

4.效果预览

==========初始化密钥信息==========
=========密钥信息初始化成功=========
=============私钥为=============
MIICdQIBADANBgkqhkiG9w0BAQEFAASCAl8wggJbAgEAAoGBAIsbpXWv1jJ/8sLNPC9dWqBmXhyx7MFT3XwyxY9uO1mLJr1biL2hytY+rFeGL+EChxlnCSS4H8M17fVP7nh5Kk5FP7sTqp3hewp9PLpKFsytP5T3urQYbQ5QtKvH4oaUk4Uu8IJ1Bc0cTNvxeSulvMMzxk+wuVEdxfO3tBLUWmjdAgMBAAECgYBQxVO0Ws3PcrVdYNeyVM07V1UL6k+jDXQMGlrV5lZ1rrNmvZBPM3NYJPnitBp21wXkvQv1Eyf2LAkoKCo6L3hdMPXpe19OgFdIHm13kV7rfZNxxGE+3ZFv5EW6O6dC7dK1fUXlAdi1Yvl3nVQx+3e2h+7CTW/fVxb9AH14IjO24QJBAL6b+aGt1v5iH0yAHG2OV30B/0hzW1ImVOu4Kx6lgobVcQkwkUVu00gkI5p7Xs/RYtmVIzR9PoYKrDCE5qGNVGUCQQC61KJnIXZsHfDnaQcq3vsFa7SzDzfKgXxHCBIGhJlLiWFisq4wWhPOO7ADOOz5lyl8TGDGyYTaJJBDGx7hWk8ZAkADUAynnbDV3Pi0SKm10bp9hrJcHP0iUV46donxT2kUVNNRGJH9xe5QG6iuv6QnMnloVKo2+FJE3Byf/z9O4XjtAkBEzColefAGrhvYyxcllUiwXVIEIdV0j6v46CLjHY7pfuRKmOuFyJXEerw844h3/E79g46bhPeT8KTi4SjE6SF5AkBn37pDFVp8mabYzDaEuoUB+WoAfLwPlNA+KQHFHoDzHEjRXvXbfObRViB5/qKkNNQiVXEfcugsA6IDlOGQezED
=============公钥为=============
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCLG6V1r9Yyf/LCzTwvXVqgZl4csezBU918MsWPbjtZiya9W4i9ocrWPqxXhi/hAocZZwkkuB/DNe31T+54eSpORT+7E6qd4XsKfTy6ShbMrT+U97q0GG0OULSrx+KGlJOFLvCCdQXNHEzb8XkrpbzDM8ZPsLlRHcXzt7QS1Fpo3QIDAQAB
=============签名为=============
ODGCnrrBV/1SXfB65SHYWbdgNAuY8QbfAzWGeRscMhGCudfQk9cnLzHVQkhlC9eXruTvjQqQSmBNLmGdegUlAh+bPi/EkqReidD0efsLSy4FQSJIdmFVW6Xl3FuAqzIqidPLPFk0rFDK/DJzGVQtUYm5rKDap0zKMxe/P3/6bbs=
===========签名验证结果===========
true

参考:http://www.imooc.com/video/6154

05-22 04:19