简介
DSA是Schnorr和ElGamal签名算法的变种,被美国NIST作为DSfS(DigitalSignature Standard)。
DSA是基于整数有限域离散对数难题的,其安全性与RSA相比差不多。DSA的一个重要特点是两个素数公开,这样,当使用别人的p和q时,即使不知道私钥,你也能确认它们是否是随机产生的,还是作了手脚。RSA却做不到。
算法分类信息:
算法 | 密钥长度 | 默认长度 | 签名长度 | 实现的方 |
SHA1withDSA | 512-65536 (64的整数倍) |
1024 | 同密钥 | JDK |
SHA224withDSA | 同上 | 1024 | 同密钥 | BC |
SHA256withDSA | ... | 1024 | 同密钥 | BC |
SHA384withDSA | ... | 1024 | 同密钥 | BC |
SHA512withDSA | ... | 1024 | 同密钥 | BC |
java实现:
package com.zoo.lion.security;
import org.apache.commons.codec.binary.Hex;
import java.security.*;
import java.security.interfaces.DSAPrivateKey;
import java.security.interfaces.DSAPublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
/**
* @Author: xf
* @Date: 2019/6/5 10:05
* @Version 1.0
*/
public class DSA {
private static String src = "dsa security";
public static void main(String[] args) throws Exception {
jdkDSA();
}
public static void jdkDSA() throws Exception {
//1.初始化密钥
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("DSA");
keyPairGenerator.initialize(512);
KeyPair keyPair = keyPairGenerator.generateKeyPair();
DSAPublicKey dsaPublicKey = (DSAPublicKey) keyPair.getPublic();
DSAPrivateKey dsaPrivateKey = (DSAPrivateKey) keyPair.getPrivate();
//2.执行签名
PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(dsaPrivateKey.getEncoded());
KeyFactory keyFactory = KeyFactory.getInstance("DSA");
PrivateKey privateKey = keyFactory.generatePrivate(pkcs8EncodedKeySpec);
Signature signature = Signature.getInstance("SHA1withDSA");
signature.initSign(privateKey);
signature.update(src.getBytes());
byte[] res = signature.sign();
System.out.println("签名:" + Hex.encodeHexString(res));
//3.验证签名
X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(dsaPublicKey.getEncoded());
keyFactory = KeyFactory.getInstance("DSA");
PublicKey publicKey = keyFactory.generatePublic(x509EncodedKeySpec);
signature = Signature.getInstance("SHA1withDSA");
signature.initVerify(publicKey);
signature.update(src.getBytes());
boolean bool = signature.verify(res);
System.out.println("验证:" + bool);
}
}