数字签名编程与实现

package com.alex.security;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.Signature;

public class DigitalSignature {


	public static void main(String[] args) throws Exception{
		//得到keyPairGenerator 的实例对象,并调用其generateKeyPair()方法得到KeyPair对象	
		KeyPair keyPair= KeyPairGenerator.getInstance("RSA").generateKeyPair();
		//调用KeyPair对象的getPrivate和getPublic方法,分别得到PrivateKey对象和PublicKey对象。
		PrivateKey privateKey = keyPair.getPrivate();
		PublicKey publicKey = keyPair.getPublic();
		sign(privateKey);
		verifySign(publicKey);
	}
	
	private static void verifySign(PublicKey publicKey) throws Exception{
		//调用Signature对象的initVerify()方法和指定PublicKey对象,然后调用update方法和verify()方法对原始数据的签名进行验证
		Signature signature = Signature.getInstance("SHA1withRSA");
		signature.initVerify(publicKey);
		signature.update("这是数字签名".getBytes());
		byte[] verifyData = readData("D:/signature.data");
		System.out.println("数字签名检验结果:"+signature.verify(verifyData));
	}

	private static void sign(PrivateKey privateKey) throws Exception {
		//得到Signature的实例对象,调用其initSign()方法和指定PrivateKey对象,然后调用update方法和sign方法产生签名
		Signature signature = Signature.getInstance("SHA1withRSA");
		signature.initSign(privateKey);
		signature.update("这是数字签名".getBytes());
		byte[] signData = signature.sign();
		savaData(signData,"D:/signature.data");
		
	}
	
	private static void savaData(byte[] data,String dataPath) throws Exception{
		FileOutputStream fos = new FileOutputStream(dataPath);
		fos.write(data);
		fos.close();
		
	}
	
	private static byte[] readData(String dataPath) throws Exception{
		FileInputStream fis = new FileInputStream(dataPath); 
		byte[] src = new byte[fis.available()];
		int total=0;
		int len = 0;
		while(total<src.length){
			total = total+len;
			len=fis.read(src, total, src.length-total);
		}
		fis.close();
		return src;
	}

}

运行结果:

数字签名检验结果:true

你可能感兴趣的:(数字签名编程与实现)