数字签名--DSA实现

xiaoxiao2021-02-28  5

其实DSA的实现和RSA差不多,只是改了改接口名称。

注意,我的代码只是用jdk实现,并没有用BC,想学的人可以自己深究一下。

代码:

package Signature; 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; public class DSA { //jdk只提供了SHA1withDSA,其他的用BC实现 private static String dsa = "CYK"; public static void main(String[] args) { // TODO Auto-generated method stub jdkDSA(); } public static void jdkDSA() { //1.初始化秘钥 KeyPairGenerator keyPairGenerator; try { keyPairGenerator = KeyPairGenerator.getInstance("DSA"); keyPairGenerator.initialize(512); KeyPair keyPair = keyPairGenerator.generateKeyPair(); DSAPublicKey dsaPublicKey = (DSAPublicKey)keyPair.getPublic(); DSAPrivateKey dsaPrivateKey = (DSAPrivateKey)keyPair.getPrivate(); //执行签名 PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(dsaPrivateKey.getEncoded()); KeyFactory keyFactory = KeyFactory.getInstance("DSA"); //这一步注意更改一下catch,让它获取所有错误 PrivateKey privateKey = keyFactory.generatePrivate(pkcs8EncodedKeySpec); //声明签名的对象 Signature signature = Signature.getInstance("SHA1withDSA"); signature.initSign(privateKey); signature.update(dsa.getBytes()); byte[] result = signature.sign(); System.out.println("jdk dsa sign:" + 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(dsa.getBytes()); boolean bool = signature.verify(result); System.out.println("jdk dsa verify:" + bool); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } }

转载请注明原文地址: https://www.6miu.com/read-2400391.html

最新回复(0)