廖雪峰Java10加密与安全-5签名算法-2DSA签名算法
DSA
DSA:Digital Signature Algorithm,使用EIGamal数字签名算法,和RSA数字签名相比,DSA更快。
DSA只能配合SHA使用:
- SHA1withDSA
- SHA256withDSA
- SHA512withDSA
代码演示:
package com.testList;
import java.security.*;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;
public class SecDSASignature {
PrivateKey sk;
PublicKey pk;
public SecDSASignature() throws GeneralSecurityException{
//generate key pair
KeyPairGenerator kpGen = KeyPairGenerator.getInstance("DSA");
kpGen.initialize(1024);
KeyPair kp = kpGen.generateKeyPair();
this.sk = kp.getPrivate();
this.pk = kp.getPublic();
}
public SecDSASignature(byte[] pk,byte[] sk) throws GeneralSecurityException{
//create from bytes
KeyFactory kf = KeyFactory.getInstance("DSA");
X509EncodedKeySpec pkSpec = new X509EncodedKeySpec(pk);
this.pk = kf.generatePublic(pkSpec);
PKCS8EncodedKeySpec skSpec = new PKCS8EncodedKeySpec(sk);
this.sk = kf.generatePrivate(skSpec);
}
public byte[] getPrivateKey(){
return this.sk.getEncoded();
}
public byte[] getPublicKey(){
return this.pk.getEncoded();
}
public byte[] sign(byte[] message) throws GeneralSecurityException{
//sign by sk;
Signature signature = Signature.getInstance("SHA1withDSA");
signature.initSign(this.sk);
signature.update(message);
return signature.sign();
}
public boolean verify(byte[] message,byte[] sign) throws GeneralSecurityException{
//verify by pk
Signature signature = Signature.getInstance("SHA1withDSA");
signature.initVerify(this.pk);
signature.update(message);
return signature.verify(sign);
}
public static void main(String[] args) throws Exception{
byte[] message = "Hello,使用SHA1withDSA算法进行数字签名".getBytes("utf-8");
SecDSASignature rasa = new SecDSASignature();
byte[] sign = rasa.sign(message);
System.out.println("sign:"+ Base64.getEncoder().encodeToString(sign));
boolean verified = rasa.verify(message,sign);
System.out.println("verify:"+verified);
message[0] = 100;
boolean verified2 = rasa.verify(message,sign);
System.out.println("verified2:"+verified2);
}
}
总结:
- DSA是另一种签名算法
- 其他数字签名算法
* ECDSA:Elliptic Curve Digital Signature Algorithm(Bouncy Castle)