RSA 加密解密

RSA 加密解密实现代码如下:

package com.barcodecheck;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;

import javax.crypto.Cipher;
import java.security.*;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Arrays;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;

/**
 * @author :zoboy
 * @Description:
 * @ Date: Created in 2019-12-05 09:28
 */
public class RSADemo {
    static String publicKey = "MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAM/bj9+o9pQobuHKRCIuFm2fky8cAvmE1aiAsG/fGLm0zqVGt7M9DAHEVcLd3WVPPVSFLGvp9ysRm565vGrU4HkCAwEAAQ==";
    static String privateKey = "MIIBVQIBADANBgkqhkiG9w0BAQEFAASCAT8wggE7AgEAAkEAz9uP36j2lChu4cpEIi4WbZ+TLxwC+YTVqICwb98YubTOpUa3sz0MAcRVwt3dZU89VIUsa+n3KxGbnrm8atTgeQIDAQABAkEAm62pw21sSSlDaw8wGp2EJNTYyvbi73ljARJpk1B311XPlsrfJJzDEGpHmqoenXnKTtrFK+OOLGWEEwPsJWY+gQIhAO6WrONtzxmc9CF3TgpD8c05XpKdQKHlvHNXcnCzn5bRAiEA3wbFJiQFFOXzeelDOVw+xwdKO4o4eyPx67AX4ElKaSkCIBdw+GWT+WAT2qybEzDRAiXeuBsBlkMR1lUix1ypWUmxAiEAonSSAxhVw0VFN1Zcq1mwONXskrY6Miiave2FVtDMLRECIDWX4aXKHKDpu7HwUYwsa7o/bbG7POMsCoeMkKhUxAN9";

    public static void main(String[] args) {
        initKey();
        Map map = new HashMap();
        map.put("requestId", "1231");
        map.put("companyCode", "10");
        map.put("busNum", "陕A07157D");
        map.put("svrReqTime", "1575422395");
        map.put("classesMD5Code", "");
        map.put("lineNum", "123569");
        String result11 = encrypt(map);
        decrypt(result11);
    }
    public static void rsaPrivateKeyInfo(RSAPrivateKey rsaPrivateKey){
        System.out.println("Private Key : " + privateKey);
        System.out.println("Private Key Mod: " + rsaPrivateKey.getModulus());
        System.out.println("Private Key Mod length: " + rsaPrivateKey.getModulus().bitLength());
        System.out.println("Private Key Exp: " + rsaPrivateKey.getPrivateExponent());
        System.out.println("Private format:" + rsaPrivateKey.getFormat());
        System.out.println("Private Key Algorithm: " +  rsaPrivateKey.getAlgorithm());
    }
    public static void rsaPublicKeyInfo(RSAPublicKey rsaPublicKey){
        System.out.println("Public Key : " + publicKey);
        System.out.println("Public Key Mod: " + rsaPublicKey.getModulus());
        System.out.println("Public Key Mod length: " + rsaPublicKey.getModulus().bitLength());
        System.out.println("Public Key Exp: " + rsaPublicKey.getPublicExponent());
        System.out.println("Public Key Algorithm: " +  rsaPublicKey.getAlgorithm());
        System.out.println("Public format:" + rsaPublicKey.getFormat());
    }

    public static void initKey() {
        // 1、初始化密钥
        KeyPairGenerator keyPairGenerator;
        try {
            keyPairGenerator = KeyPairGenerator.getInstance("RSA");
            keyPairGenerator.initialize(512);// 64的整倍数
            KeyPair keyPair = keyPairGenerator.generateKeyPair();
            RSAPublicKey rsaPublicKey = (RSAPublicKey) keyPair.getPublic();
            RSAPrivateKey rsaPrivateKey = (RSAPrivateKey) keyPair.getPrivate();
            publicKey = Base64.getEncoder().encodeToString(rsaPublicKey.getEncoded());
            privateKey = Base64.getEncoder().encodeToString(rsaPrivateKey.getEncoded());
            rsaPublicKeyInfo(rsaPublicKey);
            rsaPrivateKeyInfo(rsaPrivateKey);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
    }

    public static String encrypt(Object obj) {

        //2 私钥加密,公钥解密   --加密
        try {
            String encryptStr = JSON.toJSONString(obj, SerializerFeature.DisableCircularReferenceDetect);
            byte[] result1 = encryptStr.getBytes("utf-8");
            byte[] buffer = Base64.getDecoder().decode(privateKey);
            PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(buffer);
            KeyFactory instance = KeyFactory.getInstance("RSA");
            RSAPrivateKey key = (RSAPrivateKey) instance.generatePrivate(keySpec);
            rsaPrivateKeyInfo(key);
            Cipher cipher = Cipher.getInstance("RSA");
            cipher.init(Cipher.ENCRYPT_MODE, key);
            int inputLength = result1.length;
            System.out.println("加密字节数:" + inputLength);

            int MAX_ENCRYPT_BLOCK = key.getModulus().bitLength()/8-11;
            // 标识
            int offSet = 0;
            byte[] resultBytes = {};
            byte[] cache = {};
            while (inputLength - offSet > 0) {
                if (inputLength - offSet > MAX_ENCRYPT_BLOCK) {
                    cache = cipher.doFinal(result1, offSet, MAX_ENCRYPT_BLOCK);
                    offSet += MAX_ENCRYPT_BLOCK;
                } else {
                    cache = cipher.doFinal(result1, offSet, inputLength - offSet);
                    offSet = inputLength;
                }
                resultBytes = Arrays.copyOf(resultBytes, resultBytes.length + cache.length);
                System.arraycopy(cache, 0, resultBytes, resultBytes.length - cache.length, cache.length);
            }

            String result11 = Base64.getEncoder().encodeToString(resultBytes);
            System.out.println("私钥加密,公钥解密   --加密: " + result11);
            return result11;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static void decrypt(String ss) {
        //3 私钥加密,公钥解密   --解密
        try {
            byte[] buffer = Base64.getDecoder().decode(publicKey);
            byte[] result1 = Base64.getDecoder().decode(ss);
            X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(buffer);
            KeyFactory keyFactory = KeyFactory.getInstance("RSA");
            RSAPublicKey publicKey = (RSAPublicKey) keyFactory.generatePublic(x509EncodedKeySpec);
            rsaPublicKeyInfo(publicKey);
            Cipher cipher = Cipher.getInstance("RSA");
            cipher.init(Cipher.DECRYPT_MODE, publicKey);
            int inputLength = result1.length;
            int MAX_ENCRYPT_BLOCK =  publicKey.getModulus().bitLength()/8;
            // 标识
            int offSet = 0;
            byte[] resultBytes = {};
            byte[] cache = {};
            while (inputLength - offSet > 0) {
                if (inputLength - offSet > MAX_ENCRYPT_BLOCK) {
                    cache = cipher.doFinal(result1, offSet, MAX_ENCRYPT_BLOCK);
                    offSet += MAX_ENCRYPT_BLOCK;
                } else {
                    cache = cipher.doFinal(result1, offSet, inputLength - offSet);
                    offSet = inputLength;
                }
                resultBytes = Arrays.copyOf(resultBytes, resultBytes.length + cache.length);
                System.arraycopy(cache, 0, resultBytes, resultBytes.length - cache.length, cache.length);
            }

            System.out.println("私钥加密,公钥解密   --解密: " + javax.xml.bind.DatatypeConverter.printHexBinary(resultBytes));
            System.out.println("私钥加密,公钥解密   --解密: " + new String(resultBytes, "utf-8"));
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值