Java数字签名——ECDSA算法

Java基础

浏览数:54

2019-10-7

AD:资源代下载服务

  ECDSA

  例如微软产品的序列号的验证算法。

  Elliptic Curve Digital Signature Algorithm,椭圆曲线数字签名算法。

  速度快,强度高,签名短

——————————————————————————————————

  密钥长度   112~571           默认  256  

——————————————————————————————————
  NONEwithECDSA     签名长度:128  实现方:JDK/BC
  RIPEMD160withECDSA   签名长度:160  实现方:BC
  SHA1withECDSA        签名长度:160  实现方:JDK/BC
  SHA224withECDSA    签名长度:224  实现方:BC
  SHA384withECDSA    签名长度:384  实现方:JDK/BC
  SHA512withECDSA    签名长度:512  实现方:JDK/BC 

——————————————————————————————————

  代码:

 1 package ECDSA;
 2 
 3 import com.sun.org.apache.xerces.internal.impl.dv.util.HexBin;
 4 
 5 import java.security.*;
 6 import java.security.interfaces.ECPrivateKey;
 7 import java.security.interfaces.ECPublicKey;
 8 import java.security.spec.PKCS8EncodedKeySpec;
 9 import java.security.spec.X509EncodedKeySpec;
10 
11 public class Ecdsa {
12     private static String src = "hello berber" ;
13     public static void main(String []args){
14         jdkECDSA();
15     }
16     public static void jdkECDSA(){
17         // 1.初始化密钥
18         try{
19             KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("EC");
20             keyPairGenerator.initialize(256);
21             KeyPair keyPair = keyPairGenerator.generateKeyPair() ;
22             ECPublicKey ecPublicKey = (ECPublicKey)keyPair.getPublic() ;
23             ECPrivateKey ecPrivateKey = (ECPrivateKey)keyPair.getPrivate() ;
24             // 执行签名
25             PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(ecPrivateKey.getEncoded());
26             KeyFactory keyFactory = KeyFactory.getInstance("EC") ;
27             PrivateKey privateKey = keyFactory.generatePrivate(pkcs8EncodedKeySpec) ;
28             Signature signature = Signature.getInstance("SHA1withECDSA");
29             signature.initSign(privateKey);
30             signature.update(src.getBytes());
31             byte []arr = signature.sign();
32             System.out.println("jdk ecdsa sign :"+ HexBin.encode(arr));
33             // 验证签名
34             X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(ecPublicKey.getEncoded());
35             keyFactory = KeyFactory.getInstance("EC");
36             PublicKey publicKey = keyFactory.generatePublic(x509EncodedKeySpec);
37             signature = Signature.getInstance("SHA1withECDSA");
38             signature.initVerify(publicKey);
39             signature.update(src.getBytes());
40             boolean bool = signature.verify(arr);
41             System.out.println("jdk ecdsa verify:"+bool);
42         }catch(Exception e){
43 
44         }
45     }
46 }

 

作者:AntzUhl