我们帮大家精选了Java相关的编程文章,网友钭晴波根据主题投稿了本篇教程内容,涉及到Java、数字签名、算法、DSA、Java数字签名算法DSA实例详解相关内容,已被446网友关注,相关难点技巧可以阅读下方的电子资料。
Java数字签名算法DSA实例详解
本文实例讲述了Java数字签名算法DSA。分享给大家供大家参考,具体如下:
一、介绍
DSS:Digital Signature Standard 数字签名标准
DSA:Digital Signature Algorithm 数字签名算法
DSA仅包含数字签名
二、参数说明
三、代码实现
package com.imooc.security.dsa; import java.security.KeyFactory; import java.security.KeyPair; import java.security.KeyPairGenerator; import java.security.PrivateKey; import java.security.PublicKey; import java.security.Signature; import java.security.interfaces.DSAPrivateKey; import java.security.interfaces.DSAPublicKey; import java.security.spec.PKCS8EncodedKeySpec; import java.security.spec.X509EncodedKeySpec; import org.apache.commons.codec.binary.Hex; public class ImoocDSA { private static String src = "cakin24 security dsa"; public static void main(String[] args) { jdkDSA(); } public static void jdkDSA() { try { //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[] result = signature.sign(); System.out.println("jdk dsa sign : " + Hex.encodeHexString(result)); //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(result); System.out.println("jdk dsa verify : " + bool); } catch (Exception e) { e.printStackTrace(); } } }
四、实现效果
jdk dsa sign : 302c0214310539f9e19ec98167a687eb4e8f91e7f47326bf021428080b7f0ad2ccffc71466998d8d364ba516e840
jdk dsa verify : true
五、应用场景
希望本文所述对大家java程序设计有所帮助。