当前位置:   article > 正文

Java实现RSA加解密_java rsa加密解密

java rsa加密解密

Java实现RSA加解密

需要引入的依赖

<dependency>
            <groupId>cn.hutool</groupId>
            <artifactId>hutool-all</artifactId>
            <version>5.7.8</version>
        </dependency>

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

RSA密钥对生成工具类

package cn.demo.rsa;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.io.FileUtil;

import java.io.File;
import java.io.FileOutputStream;
import java.nio.file.Files;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.util.ArrayList;
import java.util.Base64;
import java.util.HashMap;
import java.util.List;

public class RSAKeyGenUtil {

    /**
     * 密钥大小,单位bit
     */
    private static final int KEY_SIZE = 1024;

    private static HashMap<String, String> createBase64RSAKey() throws NoSuchAlgorithmException {

        HashMap<String, String> ssMap = new HashMap<>();

        KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
        keyPairGenerator.initialize(KEY_SIZE);

        //生成密钥对
        KeyPair keyPair = keyPairGenerator.generateKeyPair();
        RSAPublicKey pubKey = (RSAPublicKey) keyPair.getPublic();
        RSAPrivateKey priKey = (RSAPrivateKey) keyPair.getPrivate();

        String pub = new String(Base64.getEncoder().encode(pubKey.getEncoded()));
        String pri = new String(Base64.getEncoder().encode(priKey.getEncoded()));
        System.out.println("公钥:" + pub);
        System.out.println("私钥:" + pri);

        ssMap.put("publicKey",pub);
        ssMap.put("privateKey",pri);
        return ssMap;
    }

    /**
     * 生成的公钥和私钥文件,最好放到项目的classpath下,以便app读取
     */
    private static void  genRSAKeyFile(){
        HashMap<String, String> ssMap = new HashMap<>();
        try {
            ssMap = createBase64RSAKey();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        if (CollUtil.isNotEmpty(ssMap)){
            File pubKeyFile = FileUtil.writeBytes(ssMap.get("publicKey").getBytes(),
                    "D:/rsa2/rsa_public.key");
            System.out.println(pubKeyFile.getAbsolutePath());

            File priKeyFile = FileUtil.writeBytes(ssMap.get("privateKey").getBytes(),
                    "D:/rsa2/rsa_private.key");
            System.out.println(priKeyFile.getAbsolutePath());

        }

    }

    public static void main(String[] args) {
        genRSAKeyFile();
    }



}

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78

RSA加解密工具类

package cn.demo.rsa;

import cn.hutool.core.io.FileUtil;

import javax.crypto.Cipher;
import java.io.File;
import java.nio.charset.StandardCharsets;
import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;

public class RSAjjmUtils {

    /**
     * rsa加密
     * @param yw  原文
     * @param rsaPublicKeyFilePath  rsa公钥文件路径
     * @return 密文
     * @throws Exception
     */
    public static String encrypt(String yw,String rsaPublicKeyFilePath) throws Exception {
        String utf8StringPubk = FileUtil.readUtf8String(rsaPublicKeyFilePath);
        byte[] publicKeyBytes = utf8StringPubk.getBytes();
        X509EncodedKeySpec x =
                new X509EncodedKeySpec(Base64.getDecoder().decode(publicKeyBytes));
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        PublicKey pubKey = keyFactory.generatePublic(x);
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.ENCRYPT_MODE, pubKey);

        byte[] result = cipher.doFinal(yw.getBytes(StandardCharsets.UTF_8));
        return Base64.getEncoder().encodeToString(result);
    }


    /**
     * rsa解密
     * @param mw  密文
     * @param rsaPrivateKeyFilePath rsa私钥文件路径
     * @return 原文
     * @throws Exception
     */
    public static String decrypt(String mw,String rsaPrivateKeyFilePath) throws Exception{
        String utf8StringPrik = FileUtil.readUtf8String(rsaPrivateKeyFilePath);
        byte[] privateKeyBytes = utf8StringPrik.getBytes();
        PKCS8EncodedKeySpec pkcs8EncodedKeySpec =
                new PKCS8EncodedKeySpec(Base64.getDecoder().decode(privateKeyBytes));
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        PrivateKey priKey = keyFactory.generatePrivate(pkcs8EncodedKeySpec);

        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.DECRYPT_MODE, priKey);

        byte[] result = cipher.doFinal(Base64.getDecoder().decode(mw));
        return new String(result);

    }


    public static void main(String[] args) throws Exception {
//        File pubKeyFile = FileUtil.file("D:/rsa2/rsa_public.key");
        File pubKeyFile = FileUtil.file("classpath:rsa_public.key");
        String encryptStr = encrypt("20230609", pubKeyFile.getPath());
        System.err.println(encryptStr); //密文每次都不一样

//        File filePrk = FileUtil.file("D:/rsa2/rsa_private.key");
        File filePrk = FileUtil.file("classpath:rsa_private.key");
        String decryptStr = decrypt(encryptStr, filePrk.getPath());
        System.err.println(decryptStr); //解出的明文都是 20230609
    }



}


  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/知新_RL/article/detail/601118
推荐阅读
相关标签
  

闽ICP备14008679号