Java数字签名——RSA算法

Java基础

浏览数:64

2019-10-7

AD:资源代下载服务

  数字签名:带有密钥(公钥,私钥)的消息摘要算法。

       验证数据的完整性,认证数据的来源,抗否性

  OSI参考模型

  私钥签名,公钥验证

  签名算法:RSA,DSA,ECDSA

  

  算法1 :RSA

      MD,SHA两类

————————————————————————————————————

      密钥长度均是 512~65536(64的整数倍)

————————————————————————————————————  

      实现方:JDK     默认长度:1024

        MD2withRSA

        MD5withRSA

        SHA1withRSA

————————————————————————————————————

      实现方:BC     默认长度:2048

        SHA224withRSA

        SHA256withRSA

        SHA384withRSA

        SHA512withRSA

        RIPEMD128withRSA

        RIPEMD160withRSA

————————————————————————————————————

 1 package RSA;
 2 
 3 import com.sun.org.apache.xerces.internal.impl.dv.util.HexBin;
 4 
 5 import java.security.*;
 6 import java.security.interfaces.RSAPrivateKey;
 7 import java.security.interfaces.RSAPublicKey;
 8 import java.security.spec.PKCS8EncodedKeySpec;
 9 import java.security.spec.X509EncodedKeySpec;
10 
11 public class Rsa {
12     public static String src = "hello human";
13     public static void main(String[] args) {
14         jdkRSA();
15     }
16     public static void jdkRSA(){
17         try{
18             // 密钥初始化
19             KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
20             keyPairGenerator.initialize(512);
21             KeyPair keyPair = keyPairGenerator.generateKeyPair();
22             RSAPublicKey rsaPublicKey = (RSAPublicKey)keyPair.getPublic() ;
23             RSAPrivateKey rsaPrivateKey = (RSAPrivateKey)keyPair.getPrivate() ;
24             // 签名
25             PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(rsaPrivateKey.getEncoded());
26             KeyFactory keyFactory = KeyFactory.getInstance("RSA");
27             PrivateKey privateKey = keyFactory.generatePrivate(pkcs8EncodedKeySpec);
28             Signature signature = Signature.getInstance("MD5withRSA");
29             signature.initSign(privateKey);
30             signature.update(src.getBytes());
31             byte []arr = signature.sign();
32             System.out.println("jdk rsa sign:"+ HexBin.encode(arr));
33             // 验证签名
34             X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(rsaPublicKey.getEncoded()) ;
35             keyFactory = KeyFactory.getInstance("RSA");
36             PublicKey publicKey = keyFactory.generatePublic(x509EncodedKeySpec);
37             signature = Signature.getInstance("MD5withRSA");
38             signature.initVerify(publicKey);
39             signature.update(src.getBytes());
40             boolean bool = signature.verify(arr);
41             System.out.println("jdk rsa verify:"+bool);
42         }catch (Exception e){
43 
44         }
45     }
46 }

  执行过程:

    构建密钥对:

      发送方 :1.构建密钥对

           2.公布密钥

    发送数据   :

      发送方 :1.使用私钥对数据签名

           2.发送签名,数据

      接收放 :3.使用公钥,签名验证数据

作者:AntzUhl