公众号:架构师与哈苏
关注公众号进入it交流群! 公众号:架构师与哈苏 不定时都会推送一些实用的干货。。。

RsaUtil

package com.fintechervision.das.facility.utils;

import com.sun.org.apache.xerces.internal.impl.dv.util.HexBin;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.security.*;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.InvalidKeySpecException;
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;

/**
 * Rsa工具类
 * @author : GoslingWu
 */
public class RsaUtil {

    private String publicKey = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAgXnV6Kbi1JQ2lHhWeCC8VO8CyZPhDAAqApMAOtbMY9VQackH7QDYLLsYjHUXwwBXYhWNLQkYKZ8G7NCwJ7cRGF5UcN4gWE5g8f/hccl9E7f29TUsDFFmaw3zaxwadffiflY59EArwHZk/wj9osXYBZlIXctKFS49PQKZYJFMYd0nIbrmJIZq+ARHGE4tOas3Q7yv5Cjh37Fvdlvb6fkrggBPANjGcmcHcZovolEp9hxNlO+aQiUV0fxXgSpPgaJAS5I25nUVIKWnW9/BMqEAou8XS0dHombdhpBkRrT9vlvZIFGkvvqAEjuJuLyZ2VO1wyDBMdBfAjKP6re3y4RuIwIDAQAB";

    private String privateKey = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAgXnV6Kbi1JQ2lHhWeCC8VO8CyZPhDAAqApMAOtbMY9VQackH7QDYLLsYjHUXwwBXYhWNLQkYKZ8G7NCwJ7cRGF5UcN4gWE5g8f/hccl9E7f29TUsDFFmaw3zaxwadffiflY59EArwHZk/wj9osXYBZlIXctKFS49PQKZYJFMYd0nIbrmJI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CISN86Dy+IVo/zPWn5EQKBgQCGfts+zUA/UJsb+bXYM9MOunHHmZ1SXZ4Ho25qEz9yFqocUDWn8WTcvkV756fhs43MdjQBGiIMu90III7Yw8NIHD1EzpY2EqbJVNy1Z244EqGZMa/qbgdCWPoVs9XPUeUrOA2+qx/tSE/uo25lAUMvDBnl7focBEAihK57DWTT8wKBgQDIzjuIxnx0/M1YOGjVNhRX1fpYZ7mYLXhFONjWgtLazZmvvuOiqLc/y903cOdrrCrWV1C4VEpTU5l32dNrKQUl7BEZXlhD7Itihm3KCp9MQBFaS0wUGVq+NYOEjq0d42HbWh3k1uAWHJVppXesG2u+ZQkvAvGgxS7d0GqKr8fhgQKBgD6dapcHWYTgkwXoMHeyUO1Hcdc6Nhr1iLAHr0zlHyGPWa0KzqAcaxe14YV46RjTzg1Fbpqgvv9sqs+w0LAsG4tD0mZpQ1dzQYDz6DjwKUkjq2Y10q9ygCCsaemWqtD1UJrZYtTEuH1wr/3qymdtugh6OshoDYvjkrQ/TzfsmWdvAoGADv0GzSc5xfl4Q53v5COtnV49VrTee4O0t6NJ0wCZ352BL9vNf+L6INS9hUmmAju7j2h6X4pZxOMQkkM1iAPnfiyEcle4z5y3op9jYhHWGYR4gM5cOhfnNpHyGIIBzyCZ0vwhRvuKFiSB3uwxBh2Ik1mWlVe3/2CGCeIN9WE+d9o=";

    /**加密算法RSA*/
    public static final String KEY_ALGORITHM = "RSA";

    /** 填充方式*/
    public static final String KEY_ALGORITHM_PADDING = "RSA/ECB/PKCS1Padding";

    /**密钥位数 1024 2048*/
    public static final int RAS_KEY_SIZE = 2048;

    /**请求算法的标准名称**/
    private static final String SIGNATURE_ALGORITHM ="SHA256withRSA";

    public static final String ENCODE_ALGORITHM = "SHA-256";

    /**生成没有加过密的公私钥*/
    public static Map<String, String> createKey(String algorithm, int keysize) throws Exception {
        KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance(algorithm);
        keyPairGen.initialize(keysize);
        KeyPair keyPair = keyPairGen.generateKeyPair();

        //通过对象 KeyPair 获取RSA公私钥对象RSAPublicKey RSAPrivateKey
        RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
        RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();

        //公私钥对象存入map中
        Map<String, String> keyMap = new HashMap<String, String>(2);

        String publicKeyStr = 	new String(Base64.getEncoder().encode(publicKey.getEncoded()));
        String privateKeyStr = new String(Base64.getEncoder().encode(privateKey.getEncoded()));

        keyMap.put("publicKey", publicKeyStr);
        keyMap.put("privateKey", privateKeyStr);
        return keyMap;
    }


    public static PublicKey getPublicKey(String publicKey){
        try {
            X509EncodedKeySpec spec=new X509EncodedKeySpec(Base64.getDecoder().decode(publicKey));
            KeyFactory keyFactory= KeyFactory.getInstance(KEY_ALGORITHM);
            return keyFactory.generatePublic(spec);

        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }catch (InvalidKeySpecException e) {
            e.printStackTrace();
        }

        return null;
    }

    public static PrivateKey getPrivateKey(String privateKey){
        try {
            PKCS8EncodedKeySpec spec=new PKCS8EncodedKeySpec(Base64.getDecoder().decode(privateKey));
            KeyFactory keyFactory=KeyFactory.getInstance(KEY_ALGORITHM);
            return keyFactory.generatePrivate(spec);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (InvalidKeySpecException e) {
            e.printStackTrace();
        }
        return null;
    }

    //公钥加密
    public static String encrypt(String plainText,String publicKeyStr){
        try {
            Cipher cipher = Cipher.getInstance(KEY_ALGORITHM);//根据需要选择分组模式、填充。比如:RSA/ECB/NoPadding
            PublicKey publickKey=getPublicKey(publicKeyStr);
            if(publickKey!=null){
                cipher.init(Cipher.ENCRYPT_MODE,publickKey);
                byte[] bytes=cipher.doFinal(plainText.getBytes(StandardCharsets.UTF_8));
                return Base64.getEncoder().encodeToString(bytes);//base64编码
            }
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (NoSuchPaddingException e) {
            e.printStackTrace();
        } catch (InvalidKeyException e) {
            e.printStackTrace();
        } catch (IllegalBlockSizeException e) {
            e.printStackTrace();
        } catch (BadPaddingException e) {
            e.printStackTrace();
        }
        return null;
    }

    //私钥解密
    public static String decrypt(String encryptText,String privateKeyStr){
        try {
            Cipher cipher = Cipher.getInstance(KEY_ALGORITHM);//根据需要选择分组模式、填充。比如:RSA/ECB/NoPadding
            PrivateKey privateKey=getPrivateKey(privateKeyStr);
            if(privateKey!=null){
                cipher.init(Cipher.DECRYPT_MODE,privateKey);
                byte[] bytes=cipher.doFinal(Base64.getDecoder().decode(encryptText));//encryptText之前用base64编码过,要解码成bytes
                return new String(bytes);//得到明文
            }
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (NoSuchPaddingException e) {
            e.printStackTrace();
        } catch (InvalidKeyException e) {
            e.printStackTrace();
        } catch (IllegalBlockSizeException e) {
            e.printStackTrace();
        } catch (BadPaddingException e) {
            e.printStackTrace();
        }

        return null;
    }

    /**
     * 签名
     * @param privateKeyStr  私钥
     * @param plainText 明文
     * @return base64后的sign
     */
    public static String sign(String privateKeyStr, String plainText) {
        PrivateKey privateKey = getPrivateKey(privateKeyStr);
        MessageDigest messageDigest;
        byte[] signed = null;
        try {
            messageDigest = MessageDigest.getInstance(ENCODE_ALGORITHM);
            messageDigest.update(plainText.getBytes());
            byte[] outputDigest_sign = messageDigest.digest();
            System.out.println("SHA-256编码后-----》"
                    + bytesToHexString(outputDigest_sign));
            Signature Sign = Signature.getInstance(SIGNATURE_ALGORITHM);
            Sign.initSign(privateKey);
            Sign.update(outputDigest_sign);
            signed = Sign.sign();
            System.out.println("SHA256withRSA签名后-----》"
                    + bytesToHexString(signed));
            return Base64.getEncoder().encodeToString(signed);
        } catch (NoSuchAlgorithmException | InvalidKeyException | SignatureException e) {
            e.printStackTrace();
        }
        return null;
    }


    /**
     * 验签
     * @param publicKeyStr 公钥
     * @param plain_text 明文
     * @param signed 签名
     */
    public static boolean verifySign(String publicKeyStr, String plain_text, String signed) {
        PublicKey publicKey = getPublicKey(publicKeyStr);
        MessageDigest messageDigest;
        boolean SignedSuccess=false;
        try {
            //signed base64 解密
            byte[] signedArr = Base64.getDecoder().decode(signed);
            messageDigest = MessageDigest.getInstance(ENCODE_ALGORITHM);
            messageDigest.update(plain_text.getBytes());
            byte[] outputDigest_verify = messageDigest.digest();
            //System.out.println("SHA-256加密后-----》" +bytesToHexString(outputDigest_verify));
            Signature verifySign = Signature.getInstance(SIGNATURE_ALGORITHM);
            verifySign.initVerify(publicKey);
            verifySign.update(outputDigest_verify);
            SignedSuccess = verifySign.verify(signedArr);
            System.out.println("验证成功?---" + SignedSuccess);

        } catch (NoSuchAlgorithmException | InvalidKeyException | SignatureException e) {
            e.printStackTrace();
        }
        return SignedSuccess;
    }


    /**
     * bytes[]换成16进制字符串
     *
     * @param src
     * @return
     */
    public static String bytesToHexString(byte[] src) {
        StringBuilder stringBuilder = new StringBuilder("");
        if (src == null || src.length <= 0) {
            return null;
        }
        for (int i = 0; i < src.length; i++) {
            int v = src[i] & 0xFF;
            String hv = Integer.toHexString(v);
            if (hv.length() < 2) {
                stringBuilder.append(0);
            }
            stringBuilder.append(hv);
        }
        return stringBuilder.toString();
    }

    public static void main(String[] args) throws Exception {

        Map<String, String> key = createKey(RsaUtil.KEY_ALGORITHM, RAS_KEY_SIZE);
        String publicKey = key.get("publicKey");
        String privateKey = key.get("privateKey");
        System.out.println(key.get("publicKey"));
        System.out.println(key.get("privateKey"));

        String text = "你好 GoslingWu!";

        String encryptStr = encrypt(text, publicKey);
        System.out.println("加密后的字符串:" + encryptStr);

        String decryptStr = decrypt(encryptStr, privateKey);
        System.out.println("解密后的字符串:" + decryptStr);

        String sign = sign(privateKey, text);
//        System.out.println("sign的字符串:" + sign);

        boolean b = verifySign(publicKey, "你好 GoslingWu!", sign);
        System.out.println("verifySign:" + b);
    }

}

posted on 2021-09-01 10:59  公众号/架构师与哈苏  阅读(124)  评论(0编辑  收藏  举报