方案1
package ECDSA;
import com.sun.org.apache.xerces.internal.impl.dv.util.HexBin;
import java.security.*;
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 src = "hello berber" ;
public static void main(String []args){
jdkECDSA();
}
public static void jdkECDSA(){
// 1.初始化密鑰
try{
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("EC");
keyPairGenerator.initialize(256);
KeyPair keyPair = keyPairGenerator.generateKeyPair() ;
ECPublicKey ecPublicKey = (ECPublicKey)keyPair.getPublic() ;
ECPrivateKey ecPrivateKey = (ECPrivateKey)keyPair.getPrivate() ;
// 執行簽名
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(src.getBytes());
byte []arr = signature.sign();
System.out.println("jdk ecdsa sign :"+ HexBin.encode(arr));
// 驗證簽名
X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(ecPublicKey.getEncoded());
keyFactory = KeyFactory.getInstance("EC");
PublicKey publicKey = keyFactory.generatePublic(x509EncodedKeySpec);
signature = Signature.getInstance("SHA1withECDSA");
signature.initVerify(publicKey);
signature.update(src.getBytes());
boolean bool = signature.verify(arr);
System.out.println("jdk ecdsa verify:"+bool);
}catch(Exception e){
}
}
}
Java數字簽名——ECDSA算法
方案2
public class MyTest {
/**
* @param args
*/
public static void main(String[] args) {
new MyTest().getSign();
}
void getSign() {
// Get the instance of the Key Generator with "EC" algorithm
try {
KeyPairGenerator g = KeyPairGenerator.getInstance("EC");
ECGenParameterSpec kpgparams = new ECGenParameterSpec("secp256r1");
g.initialize(kpgparams);
KeyPair pair = g.generateKeyPair();
// Instance of signature class with SHA256withECDSA algorithm
Signature ecdsaSign = Signature.getInstance("SHA256withECDSA");
ecdsaSign.initSign(pair.getPrivate());
System.out.println("Private Keys is::" + pair.getPrivate());
System.out.println("Public Keys is::" + pair.getPublic());
String msg = "text ecdsa with sha256";//getSHA256(msg)
ecdsaSign.update((msg + pair.getPrivate().toString())
.getBytes("UTF-8"));
byte[] signature = ecdsaSign.sign();
System.out.println("Signature is::"
+ new BigInteger(1, signature).toString(16));
// Validation
ecdsaSign.initVerify(pair.getPublic());
ecdsaSign.update(signature);
if (ecdsaSign.verify(signature))
System.out.println("valid");
else
System.out.println("invalid!!!!");
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}}
java – 使用secp256r1曲線和SHA256算法生
怎麽驗證生成的Ecdsa簽名是正確的呢,可以看下這篇文章:RSA,ECC,Ecdsa,國密SM2的簽名,驗簽,加密