java RSA非对称加密算法工具类

java | 2022-07-24 10:08:40

RAS非对称加密算法工具类实现的功能:

1.生成密钥对

2.私钥签名 公钥 验签

3.私钥加密数据 公钥解密数据

4.公钥加密数据 私钥解密数据

 

package com.stackcloud.system.utils;

/**
 * @author houyong
 * @date 2022/3/14 16:50
 */

import org.apache.commons.codec.binary.Base64;

import javax.crypto.Cipher;
import java.security.*;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.HashMap;
import java.util.Map;

public class RSAUtil {
    private static final String KEY_ALGORITHM = "RSA";
    private static final String SIGNATURE_ALGORITHM = "MD5withRSA";

    private static final String PUBLIC_KEY = "RSAPublicKey";
    private static final String PRIVATE_KEY = "RSAPrivateKey";

    /**
     * 初始化密钥对
     *
     * @return
     * @throws Exception
     */
    public static Map<String, Key> initKeyPair() throws Exception {
        KeyPairGenerator keyPairGen = KeyPairGenerator
                .getInstance(KEY_ALGORITHM);
        keyPairGen.initialize(1024);
        KeyPair keyPair = keyPairGen.generateKeyPair();
        Map<String, Key> keyMap = new HashMap(2);
        keyMap.put(PUBLIC_KEY, keyPair.getPublic());// 公钥
        keyMap.put(PRIVATE_KEY, keyPair.getPrivate());// 私钥
        return keyMap;
    }

    /**
     * base64code转privatekey
     * @param privateKeyStr
     * @return
     * @throws NoSuchAlgorithmException
     * @throws InvalidKeySpecException
     */
    public static PrivateKey getPrivateKeyByBase64Code(String privateKeyStr) throws NoSuchAlgorithmException, InvalidKeySpecException {
        // 对密钥解密
        byte[] keyBytes = Base64.decodeBase64(privateKeyStr);
        // 取得私钥
        PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
        return keyFactory.generatePrivate(pkcs8KeySpec);
    }

    /**
     * 取得私钥 转为base64
     *
     * @param keyMap
     * @return
     * @throws Exception
     */
    public static String getPrivateKeyBase64Code(Map<String, Key> keyMap)
            throws Exception {
        Key key = (Key) keyMap.get(PRIVATE_KEY);
        return Base64.encodeBase64String(key.getEncoded());
    }

    /**
     * base64转publickey
     * @param publicKeyStr
     * @return
     * @throws NoSuchAlgorithmException
     * @throws InvalidKeySpecException
     */
    public static PublicKey getPublicKeyByBase64Code(String publicKeyStr) throws NoSuchAlgorithmException, InvalidKeySpecException {
        // 对公钥解密
        byte[] keyBytes = Base64.decodeBase64(publicKeyStr);
        // 取得公钥
        X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
        return  keyFactory.generatePublic(x509KeySpec);
    }


    /**
     * 取得公钥 转为base64
     *
     * @param keyMap
     * @return
     * @throws Exception
     */
    public static String getPublicKeyBase64Code(Map<String, Key> keyMap)
            throws Exception {
        Key key = keyMap.get(PUBLIC_KEY);
        return Base64.encodeBase64String(key.getEncoded());
    }



    /**
     * 用私钥对信息生成数字签名
     *
     * @param data       加密数据
     * @param privateKeyStr 私钥
     * @return
     * @throws Exception
     */
    public static String sign(String data, String privateKeyStr) throws Exception {
        // 取私钥匙对象
        PrivateKey priKey = getPrivateKeyByBase64Code(privateKeyStr);
        // 用私钥对信息生成数字签名
        Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);
        signature.initSign(priKey);
        signature.update(data.getBytes("utf-8"));
        return Base64.encodeBase64String(signature.sign());
    }

    /**
     * 校验数字签名
     *
     * @param data      加密数据
     * @param publicKeyStr 公钥
     * @param sign      数字签名
     * @return 校验成功返回true 失败返回false
     * @throws Exception
     */
    public static boolean verify(String data, String publicKeyStr, String sign)
            throws Exception {
        // 取公钥匙对象
        PublicKey pubKey = getPublicKeyByBase64Code(publicKeyStr);
        Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);
        signature.initVerify(pubKey);
        signature.update(data.getBytes("utf-8"));
        // 验证签名是否正常
        return signature.verify(Base64.decodeBase64(sign));
    }


    /**
     * 用私钥解密
     *
     * @param data
     * @param privateKeyStr
     * @return
     * @throws Exception
     */
    public static String decryptByPrivateKey(String data, String privateKeyStr) throws Exception {
        KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
        Key privateKey = getPrivateKeyByBase64Code(privateKeyStr);
        // 对数据解密
        Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
        cipher.init(Cipher.DECRYPT_MODE, privateKey);
        return new String(cipher.doFinal(Base64.decodeBase64(data)), "utf-8");
    }


    /**
     * 解密<br>
     * 用公钥解密
     *
     * @param data
     * @param publicKeyStr
     * @return
     * @throws Exception
     */
    public static String decryptByPublicKey(String data, String publicKeyStr)
            throws Exception {
        KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
        Key publicKey = getPublicKeyByBase64Code(publicKeyStr);
        // 对数据解密
        Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
        cipher.init(Cipher.DECRYPT_MODE, publicKey);
        return new String(cipher.doFinal(Base64.decodeBase64(data)));
    }

    /**
     * 加密<br>
     * 用公钥加密
     *
     * @param data
     * @param publicKeyStr
     * @return
     * @throws Exception
     */
    public static String encryptByPublicKey(String data, String publicKeyStr)
            throws Exception {
        KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
        Key publicKey = getPublicKeyByBase64Code(publicKeyStr);
        // 对数据加密
        Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
        cipher.init(Cipher.ENCRYPT_MODE, publicKey);
        return Base64.encodeBase64String(cipher.doFinal(data.getBytes("utf-8")));
    }

    /**
     * 加密<br>
     * 用私钥加密
     *
     * @param data
     * @param privateKeyStr
     * @return
     * @throws Exception
     */
    public static String encryptByPrivateKey(String data, String privateKeyStr)
            throws Exception {
        KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
        Key privateKey =getPrivateKeyByBase64Code(privateKeyStr);
        // 对数据加密
        Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
        cipher.init(Cipher.ENCRYPT_MODE, privateKey);
        return Base64.encodeBase64String(cipher.doFinal(data.getBytes("utf-8")));
    }


    /**
     * 测试
     * @param args
     * @throws Exception
     */
    public static void main(String[] args) throws Exception {
        //密钥对
        Map<String, Key> keyMap = initKeyPair();
        String publicKeyStr = getPublicKeyBase64Code(keyMap);
        System.out.println("publicKeyStr:"+publicKeyStr);
        String privateKeyStr = getPrivateKeyBase64Code(keyMap);
        System.out.println("privateKeyStr:"+privateKeyStr);

        //签名
        String signStr=sign("str",privateKeyStr);
        boolean verify=verify("str",publicKeyStr,signStr);
        System.out.println(verify);

        //私钥加密公钥解密
        String encrystrByPrivateKey=encryptByPrivateKey("data",privateKeyStr);
        System.out.println(encrystrByPrivateKey);
        String dataStrByPublicKey=decryptByPublicKey(encrystrByPrivateKey,publicKeyStr);
        System.out.println(dataStrByPublicKey);

        //公钥加密私钥解密
        String encryByPublicKey=encryptByPublicKey("data",publicKeyStr);
        System.out.println(encryByPublicKey);
        String dataStryByPrivateKey=decryptByPrivateKey(encryByPublicKey,privateKeyStr);
        System.out.println(dataStryByPrivateKey);



    }
}

 

登录后即可回复 登录 | 注册
    
关注编程学问公众号