ToB企服应用市场:ToB评测及商务社交产业平台

标题: 从加密到签名:如何利用Java实现高效、安全的RSA加解密算法? [打印本页]

作者: 嚴華    时间: 2024-8-16 07:16
标题: 从加密到签名:如何利用Java实现高效、安全的RSA加解密算法?
目次
1. 接下来让小编给您们编写实当代码!请躺好 ☺
1.1 设置application.yml文件
1.2 RSA算法签名工具类
1.3 RSA算法生成签名以及效验签名测试
1.4 RSA算法生成公钥私钥、加密、解密工具类
1.5 RSA算法加解密测试

   
    RSA 加密算法是一种非对称加密算法,也是目前广泛利用的加密技术之一。RSA
算法的安全性基于大素数分解的困难性问题,其重要特点是安全性高、密钥管理简单等。
  RSA 算法采用非对称加密的方式,即加密和解密利用不同的密钥举行操作。算法的安全性基于两个大素数相乘难以分解的数学问题,包管了密钥的安全性和秘密性。在
RSA 算法中,公钥用于加密,私钥用于解密。
  RSA 算法重要优点如下:
      RSA 算法重要用于数字签名、加密解密等方面。在数字签名方面,RSA
算法可以用于生成和验证签名,包管数据的秘密性、完备性和认证性,防止篡改和伪造;在加密解密方面,RSA 算法可以用于实现各种安全协媾和应用程序,例如
SSL/TLS、IPSec、PGP 等,包管数据的秘密性和隐私性。值得注意的是,由于 RSA
算法的加密和解密速度较慢,因此在加密大量数据时,大概会影响体系的性能。
  
    RSA签名机制好坏对称加密技术的一种重要应用,用于数字签名和认证,在计算机网络通信安全、电子商务、数字版权等领域广泛应用。RSA签名可以包管信息传输过程中不被篡改,同时也能够验证消息发送者的身份和数据完备性。
  详细来说,利用RSA签名可以实现以下目标:
      因此,利用RSA签名是保障信息安全和传输可靠性的重要本领,它可以有效防范数据被篡改、伪造和窃取等风险。
  1. 接下来让小编给您们编写实当代码!请躺好 ☺


1.1 设置application.yml文件

  1. crypto:
  2.   #AES消息秘钥
  3.   ASE_SIGN_KEY: MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCFeSnQmMwPfwnvrozctUM8YmkvieWgsxvh2aAl71GVeGcsxCvIO1K9uAPF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k75EDxbHSIlCUSCxX7Gb1kHwcolDa5Ra0hWqUJ7g6nIlUBG209V89bJ70KuW84OYQ7QH0VIdJPJ70zbqlOt7+VTKT/DT41iHe2ULXxM9nPKWEt6Ga/iKsEY4zsJxPYcCgYEAoGW8YlcLiMpaTOyOnS5uH6at71sUc2wLR+ovLqqpQxLtOn597fB96X41fg07x0yh9RJ4MbSjamVOpcWsXJaTL5hf98ppw/ffeoWtRc2IiVVGZFNDYm5xXj+mMke8mFNCeKEo2Igf8jGXUTz6473cdljd4GB0T/JWGFX2HNzvEcs=
  12.   #签名公钥
  13.   SIGNATURE_PUBLIC_KEY: MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAvRr+SjbZOHIRwcd99rS8YDp6Cfc6Q4jEOmHGbiztxgvyDS1jO9SPy78j6VNKcAtTcAhtBjIDT2sezupIjZKf9H/t3+4zxUH9Kj+ybBrJNW3ZhSMunDp5K7x9RcmCRnU8QcCcYsEwa90FDd54f3YzuUD3kX35/mIfWZCLD3mY6d7txzGHlWlV84UyQDK1cqAYlUvMyHg7Ff0q1NrVwXU0fVC8PBtxnqzukny42oDEN0r7jIvrK0sKmZSVHfoHVjWPhVL9RWuN/GP2RV0k0nb856A9cxedlV236lSBpPNYgWiglPGWxTmrwOI66GE1PZ/DMJBp+RaPveh52NA0mA4JoQIDAQAB
复制代码
1.2 RSA算法签名工具类

  1. package com.jmh.service.base.util;
  2. import org.apache.tomcat.util.codec.binary.Base64;
  3. import java.security.KeyFactory;
  4. import java.security.PrivateKey;
  5. import java.security.PublicKey;
  6. import java.security.Signature;
  7. import java.security.spec.InvalidKeySpecException;
  8. import java.security.spec.PKCS8EncodedKeySpec;
  9. import java.security.spec.X509EncodedKeySpec;
  10. /**
  11. * 签名工具类
  12. */
  13. public class DigitalSignatureUtil {
  14.     /**
  15.      * 参数分别代表
  16.      */
  17.     private static final String ALGORITHMS = "RSA";
  18.     private static final String ALGORITHM = "SHA256withRSA";
  19.     /**
  20.      *
  21.      * @param signatureContent 签名内容
  22.      * @param privateKeyEncoded 私钥
  23.      * @return
  24.      * @throws Exception
  25.      */
  26.     public static String generationSignature(String signatureContent, byte[] privateKeyEncoded) throws Exception {
  27.         // 创建key的工厂
  28.         KeyFactory keyFactory=KeyFactory.getInstance(ALGORITHMS);
  29.         // 创建 已编码的私钥规格
  30.         PKCS8EncodedKeySpec encPriKeySpec = new PKCS8EncodedKeySpec(privateKeyEncoded);
  31.         // 获取指定算法的密钥工厂, 根据 已编码的私钥规格, 生成私钥对象
  32.         PrivateKey privateKey = keyFactory.generatePrivate(encPriKeySpec);
  33.         Signature signature = Signature.getInstance(ALGORITHM);
  34.         signature.initSign(privateKey);
  35.         signature.update(signatureContent.getBytes());
  36.         byte[] sign = signature.sign();
  37.         // 采用base64算法进行转码,避免出现中文乱码
  38.         return  Base64.encodeBase64String(sign);
  39.     }
  40.     /**
  41.      *  校验签名
  42.      * @param signatureContent 签名内容
  43.      * @param signature 签名
  44.      * @param publicKeyEncoded 公钥
  45.      * @return
  46.      * @throws Exception
  47.      */
  48.     public static boolean verifySignature(String signatureContent,String signature, byte[] publicKeyEncoded) throws Exception {
  49.         // 创建key的工厂
  50.         KeyFactory keyFactory=KeyFactory.getInstance(ALGORITHMS);
  51.         // 创建 已编码的公钥规格
  52.         X509EncodedKeySpec encPubKeySpec = new X509EncodedKeySpec(publicKeyEncoded);
  53.         // 获取指定算法的密钥工厂, 根据 已编码的公钥规格, 生成公钥对象
  54.         PublicKey publicKey = keyFactory.generatePublic(encPubKeySpec);
  55.         Signature verifySignature = Signature.getInstance(ALGORITHM);
  56.         verifySignature.initVerify(publicKey);
  57.         verifySignature.update(signatureContent.getBytes());
  58.         boolean verify = verifySignature.verify(Base64.decodeBase64(signature));
  59.         return verify;
  60.     }
  61. }
复制代码
1.3 RSA算法生成签名以及效验签名测试


  1. package com.jmh.service.service.jmhDemo;
  2. import com.fesion.service.base.util.AESEncryptUtil;
  3. import com.fesion.service.base.util.DigitalSignatureUtil;
  4. import com.fesion.service.base.util.MessageDigestUtil;
  5. import com.fesion.service.base.util.RSAEncryptUtil;
  6. import lombok.SneakyThrows;
  7. import lombok.extern.slf4j.Slf4j;
  8. import org.apache.tomcat.util.codec.binary.Base64;
  9. import org.junit.Test;
  10. import org.junit.runner.RunWith;
  11. import org.springframework.beans.factory.annotation.Value;
  12. import org.springframework.boot.test.context.SpringBootTest;
  13. import org.springframework.test.context.junit4.SpringRunner;
  14. /**
  15. * @author 蒋明辉
  16. * @data 2023/6/18 23:25
  17. */
  18. @SpringBootTest
  19. @RunWith(SpringRunner.class)
  20. @Slf4j
  21. public class Demo02 {
  22.     /**
  23.      * RSA算法私钥
  24.      */
  25.     @Value("${crypto.RSA_PRIVATE_KEY}")
  26.     private String RSA_PRIVATE_KEY;
  27.     /**
  28.      * RSA算法公钥
  29.      */
  30.     @Value("${crypto.RSA_PUBLIC_KEY}")
  31.     private String RSA_PUBLIC_KEY;
  32.     }
  33.     /**
  34.      * 采用RSA算法生成签名、效验签名
  35.      */
  36.     @Test
  37.     @SneakyThrows
  38.     public void demo02(){
  39.         //---------------------------------生成签名
  40.         //要签名的内容
  41.         String conent="蒋明辉是个大帅逼!我好爱。";
  42.         String signature = DigitalSignatureUtil.generationSignature(conent, Base64.decodeBase64(SIGNATURE_PRIVATE_KEY));
  43.         //---------------------------------效验签名
  44.         boolean verifySignature = DigitalSignatureUtil.verifySignature(conent, signature, Base64.decodeBase64(SIGNATURE_PUBLIC_KEY));
  45.         System.out.println("--------------------------生成的签名-----------------");
  46.         System.out.println(signature);
  47.         System.out.println("--------------------------效验签名、正确true、错误false-----------------");
  48.         System.out.println(verifySignature);
  49.     }
  50. }
复制代码


1.4 RSA算法生成公钥私钥、加密、解密工具类


1.5 RSA算法加解密测试


  1. package com.jmh.service.service.jmhDemo;
  2. import cn.hutool.crypto.asymmetric.RSA;
  3. import com.fesion.service.base.util.AESEncryptUtil;
  4. import com.fesion.service.base.util.DigitalSignatureUtil;
  5. import com.fesion.service.base.util.MessageDigestUtil;
  6. import com.fesion.service.base.util.RSAEncryptUtil;
  7. import lombok.SneakyThrows;
  8. import lombok.extern.slf4j.Slf4j;
  9. import org.apache.tomcat.util.codec.binary.Base64;
  10. import org.junit.Test;
  11. import org.junit.runner.RunWith;
  12. import org.springframework.beans.factory.annotation.Value;
  13. import org.springframework.boot.test.context.SpringBootTest;
  14. import org.springframework.test.context.junit4.SpringRunner;
  15. /**
  16. * @author 蒋明辉
  17. * @data 2023/6/18 23:25
  18. */
  19. @SpringBootTest
  20. @RunWith(SpringRunner.class)
  21. @Slf4j
  22. public class Demo02 {
  23.     /**
  24.      * RSA签名私钥
  25.      */
  26.     @Value("${crypto.SIGNATURE_PRIVATE_KEY}")
  27.     private String SIGNATURE_PRIVATE_KEY;
  28.     /**
  29.      * RSA签名公钥
  30.      */
  31.     @Value("${crypto.SIGNATURE_PUBLIC_KEY}")
  32.     private String SIGNATURE_PUBLIC_KEY;
  33.     /**
  34.      * 采用RSA算法加解密
  35.      */
  36.     @Test
  37.     @SneakyThrows
  38.     public void demo03(){
  39.         //------------------------RSA算法加密
  40.         //要加密的内容
  41.         String conent="蒋明辉好帅!我好爱。";
  42.         String encrypt = RSAEncryptUtil.encrypt(conent, Base64.decodeBase64(RSA_PUBLIC_KEY));
  43.         //------------------------RSA算法解密
  44.         String decrypt = RSAEncryptUtil.decrypt(encrypt, Base64.decodeBase64(RSA_PRIVATE_KEY));
  45.         System.out.println("-----------------加密------------------");
  46.         System.out.println(encrypt);
  47.         System.out.println("-----------------解密------------------");
  48.         System.out.println(decrypt);
  49.     }
  50. }
复制代码



黑客学习资源保举
最后给各人分享一份全套的网络安全学习资料,给那些想学习 网络安全的小同伴们一点帮助!
对于从来没有打仗过网络安全的同学,我们帮你准备了详细的学习成长门路图。可以说是最科学最体系的学习门路,各人跟着这个大的方向学习准没问题。





欢迎光临 ToB企服应用市场:ToB评测及商务社交产业平台 (https://dis.qidao123.com/) Powered by Discuz! X3.4