首页 > 编程 > Java > 正文

java 加密之数字签名算法

2019-11-06 07:11:54
字体:
来源:转载
供稿:网友

简介

数字签名算法是带有公钥和私钥的消息摘要算法,私钥签名,公钥验证,用来验证数据完整性,验证数据来源,抗否认。

数字签名必须具备 5 个特性: (1)签名是可信的。 (2)签名是不可伪造的。 (3)签名是不可重用的。 (4)签名的文件是不可改变的。 (5)签名是不可抵赖的。

流行的有RSA、DSA、ECDSA算法。


RSA算法

包括MD和SHA两类。其中 md5withRSA 的java实现:

public class MyRSA { PRivate static String str = "guo feng"; public static void main(String[] args) { try { //初始化密钥 KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA"); keyPairGenerator.initialize(512); KeyPair keyPair = keyPairGenerator.generateKeyPair(); RSAPrivateKey rsaPrivateKey = (RSAPrivateKey) keyPair.getPrivate(); RSAPublicKey rsaPublicKey = (RSAPublicKey) keyPair.getPublic(); //私钥签名 PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(rsaPrivateKey.getEncoded()); KeyFactory keyFactory = KeyFactory.getInstance("RSA"); PrivateKey privateKey = keyFactory.generatePrivate(pkcs8EncodedKeySpec); Signature signature = Signature.getInstance("MD5withRSA"); signature.initSign(privateKey); signature.update(str.getBytes()); byte[] result = signature.sign(); System.out.println(new BigInteger(result)); //公钥验证 X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(rsaPublicKey.getEncoded()); keyFactory = KeyFactory.getInstance("RSA"); PublicKey publicKey = keyFactory.generatePublic(x509EncodedKeySpec); signature = Signature.getInstance("MD5withRSA"); signature.initVerify(publicKey); signature.update(str.getBytes()); boolean b = signature.verify(result); System.out.println(b); } catch (Exception e) { e.printStackTrace(); } }}

输出:

2982312259358826061447321482940705327790349142998412535792313942953590618626400322298375288237244307356609052905381328226612007870641624392779916247258746true

场景时序图:

首先: 这里写图片描述 然后: 这里写图片描述


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表