1. 程式人生 > >數字簽名--ECDSA實現

數字簽名--ECDSA實現

和RSA與DSA程式碼基本一樣,ECDSA只是改了幾個小地方,提示一下,DSA只有資料加密功能,而沒有資料通訊功能,但是RSA都有。

程式碼:

package Signature;

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.ECPrivateKey;
import java.security.interfaces.ECPublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;

public class ECDSA {
	
	private static String ecdsa = "CYK";
	
	public static void main(String[] args) {
		jdkECDSA();
	}
	
	public static void jdkECDSA() {
		try {
			//1.初始化祕鑰
			KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("EC");
			keyPairGenerator.initialize(256);
			KeyPair keyPair = keyPairGenerator.generateKeyPair();
			ECPublicKey ecPublicKey = (ECPublicKey)keyPair.getPublic();
			ECPrivateKey ecPrivateKey = (ECPrivateKey)keyPair.getPrivate();
			
			//2.執行簽名
			PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(ecPrivateKey.getEncoded());
			KeyFactory keyFactory = KeyFactory.getInstance("EC");
			PrivateKey privateKey = keyFactory.generatePrivate(pkcs8EncodedKeySpec);
			Signature signature = Signature.getInstance("SHA1withECDSA");
			signature.initSign(privateKey);
			signature.update(ecdsa.getBytes());
			byte[] result = signature.sign();
			System.out.println("jdk ecdsa sign:" + result);
			
			//3.驗證簽名
			X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(ecPublicKey.getEncoded());
			keyFactory = KeyFactory.getInstance("EC");
			PublicKey publicKey = keyFactory.generatePublic(x509EncodedKeySpec);
			signature = Signature.getInstance("SHA1withECDSA");
			signature.initVerify(publicKey);
			signature.update(ecdsa.getBytes());
			boolean bool = signature.verify(result);
			System.out.println("jdk ecdsa verift:" + bool);
			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
}