欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

java数字签名算法之RSA

程序员文章站 2024-03-19 13:36:10
...

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

实例

1.项目结构

java数字签名算法之RSA

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+EChxlnCSS4H8M17fVP7nh5Kk5FP7sTqp3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Fk0rFDK/DJzGVQtUYm5rKDap0zKMxe/P3/6bbs=
===========签名验证结果===========
true

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