数字签名算法_DSA

DSS:数字签名标准

DSA:数字签名算法

DSA和RSA区别:

  1. DSA:仅包含数字签名
  2. RSA:既包含数字签名也包含数字加密

DSA签名和RSA签名Java jdk提供的实现代码基本一样,BC提供的没学学习过不知道啥情况。

直接上代码吧:

public class DemoDsa {
public static void jdkDSA(String data) {
    // 初始化密钥
    try {
        KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("DSA");
        keyPairGenerator.initialize(512);

        KeyPair keyPair = keyPairGenerator.generateKeyPair();
        //0. 获取公钥和密钥
        DSAPublicKey dsaPublicKey = (DSAPublicKey) keyPair.getPublic();
        DSAPrivateKey dsaPrivateKey = (DSAPrivateKey) keyPair.getPrivate();

        //1.执行签名
        PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(dsaPrivateKey.getEncoded());
        KeyFactory keyFactory = KeyFactory.getInstance("DSA");
        PrivateKey privateKey = keyFactory.generatePrivate(pkcs8EncodedKeySpec);
        Signature signature = Signature.getInstance("SHAwithDSA");
        signature.initSign(privateKey);
        signature.update(data.getBytes());
        //加密后的结果
        byte[] result = signature.sign();
        //打印数据
        StringBuilder hexString = new StringBuilder();
        for (int i = 0; i < result.length; i++) {
            if ((result[i] & 0xff) < 0x10)
                hexString.append("0");
            hexString.append(Integer.toHexString(0xFF & result[i]));
        }
        System.out.println("加密后的数据:" + hexString.toString().toLowerCase());

        //3.验证签名
        X509EncodedKeySpec x509EncodedKeySpec=new X509EncodedKeySpec(dsaPublicKey.getEncoded());
        keyFactory=KeyFactory.getInstance("DSA");
        PublicKey publicKey=keyFactory.generatePublic(x509EncodedKeySpec);
        signature=Signature.getInstance("SHAwithDSA");
        signature.initVerify(publicKey);
        signature.update(data.getBytes());
        //验证后的结果
        boolean isOk=signature.verify(result);
        System.out.println("验证结果:"+isOk);
    } catch (Exception e) {
        e.printStackTrace();
    }

}
}

调用这个签名:

jdkDSA("i love you");

你可能感兴趣的:(数字签名算法_DSA)