RAS 加密与解密

1.代码

package com.peak.common.utils;

import org.apache.tomcat.util.codec.binary.Base64;
import javax.crypto.Cipher;
import java.io.ByteArrayOutputStream;
import java.security.*;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;

/**
 * @ClassName RSAUtils
 * @Description: RSA 加密解密工具类
 * @Author jql
 * @Date 2020/7/17 13:29
 * @Version V1.0
 **/
public class RSAUtils {
    
    

    /**
     * RSA最大加密明文大小
     **/
    private static final int MAX_ENCRYPT_BLOCK = 117;

    /**
     * RSA最大解密密文大小
     **/
    private static final int MAX_DECRYPT_BLOCK = 128;


    public static final String KEY_ALGORITHM = "RSA";
    public static final String SIGNATURE_ALGORITHM = "MD5withRSA";

    /**
     * @Title: getKeyPair
     * @Description: 获取密钥对
     * @Date: 2020/7/17 14:44
     * @return: java.security.KeyPair
     **/
    public static KeyPair getKeyPair() throws Exception {
    
    
        KeyPairGenerator generator = KeyPairGenerator.getInstance(KEY_ALGORITHM);
        generator.initialize(1024);
        return generator.generateKeyPair();
    }

    /**
     * @Title: getPrivateKey
     * @Description: 获取私钥
     * @param privateKey 私钥字符串
     * @Date: 2020/7/17 14:45
     * @return: java.security.PrivateKey
     **/
    public static PrivateKey getPrivateKey(String privateKey) throws Exception {
    
    
        KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
        byte[] decodedKey = Base64.decodeBase64(privateKey.getBytes());
        PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(decodedKey);
        return keyFactory.generatePrivate(keySpec);
    }

    /**
     * @Title: getPublicKey
     * @Description: 获取公钥
     * @param publicKey 公钥字符串
     * @Date: 2020/7/17 14:47
     * @return: java.security.PublicKey
     **/
    public static PublicKey getPublicKey(String publicKey) throws Exception {
    
    
        KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
        byte[] decodedKey = Base64.decodeBase64(publicKey.getBytes());
        X509EncodedKeySpec keySpec = new X509EncodedKeySpec(decodedKey);
        return keyFactory.generatePublic(keySpec);
    }

    /**
     * @Title: encrypt
     * @Description: RSA 加密
     * @param data 待加密数据
     * @param publicKey 公钥
     * @Date: 2020/7/17 14:47
     * @return: java.lang.String
     **/
    public static String encrypt(String data, PublicKey publicKey) throws Exception {
    
    
        Cipher cipher = Cipher.getInstance(KEY_ALGORITHM);
        cipher.init(Cipher.ENCRYPT_MODE, publicKey);
        int inputLen = data.getBytes().length;
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        int offset = 0;
        byte[] cache;
        int i = 0;
        // 对数据分段加密
        while (inputLen - offset > 0) {
    
    
            if (inputLen - offset > MAX_ENCRYPT_BLOCK) {
    
    
                cache = cipher.doFinal(data.getBytes(), offset, MAX_ENCRYPT_BLOCK);
            } else {
    
    
                cache = cipher.doFinal(data.getBytes(), offset, inputLen - offset);
            }
            out.write(cache, 0, cache.length);
            i++;
            offset = i * MAX_ENCRYPT_BLOCK;
        }
        byte[] encryptedData = out.toByteArray();
        out.close();
        // 获取加密内容使用base64进行编码,并以UTF-8为标准转化成字符串
        // 加密后的字符串
        return new String(Base64.encodeBase64String(encryptedData));
    }

    /**
     * @Title: decrypt
     * @Description: RSA 解密
     * @param data 待解密数据
     * @param privateKey 私钥
     * @Date: 2020/7/17 14:48
     * @return: java.lang.String
     **/
    public static String decrypt(String data, PrivateKey privateKey) throws Exception {
    
    
        Cipher cipher = Cipher.getInstance(KEY_ALGORITHM);
        cipher.init(Cipher.DECRYPT_MODE, privateKey);
        byte[] dataBytes = Base64.decodeBase64(data);
        int inputLen = dataBytes.length;
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        int offset = 0;
        byte[] cache;
        int i = 0;
        // 对数据分段解密
        while (inputLen - offset > 0) {
    
    
            if (inputLen - offset > MAX_DECRYPT_BLOCK) {
    
    
                cache = cipher.doFinal(dataBytes, offset, MAX_DECRYPT_BLOCK);
            } else {
    
    
                cache = cipher.doFinal(dataBytes, offset, inputLen - offset);
            }
            out.write(cache, 0, cache.length);
            i++;
            offset = i * MAX_DECRYPT_BLOCK;
        }
        byte[] decryptedData = out.toByteArray();
        out.close();
        // 解密后的内容
        return new String(decryptedData, "UTF-8");
    }

    /**
     * @Title: sign
     * @Description: 签名
     * @param data 待签名数据
     * @param privateKey 私钥
     * @Date: 2020/7/17 14:49
     * @return: java.lang.String
     **/
    public static String sign(String data, PrivateKey privateKey) throws Exception {
    
    
        byte[] keyBytes = privateKey.getEncoded();
        PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
        PrivateKey key = keyFactory.generatePrivate(keySpec);
        Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);
        signature.initSign(key);
        signature.update(data.getBytes());
        return new String(Base64.encodeBase64(signature.sign()));
    }

    /**
     * @Title: verify
     * @Description: 验签
     * @param srcData 原始字符串
     * @param publicKey 公钥
     * @param sign 签名
     * @Date: 2020/7/17 14:50
     * @return: boolean
     **/
    public static boolean verify(String srcData, PublicKey publicKey, String sign) throws Exception {
    
    
        byte[] keyBytes = publicKey.getEncoded();
        X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
        PublicKey key = keyFactory.generatePublic(keySpec);
        Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);
        signature.initVerify(key);
        signature.update(srcData.getBytes());
        return signature.verify(Base64.decodeBase64(sign.getBytes()));
    }
}

2.测试

public static void main(String[] args) {
    
    
        try {
    
    
            // 生成密钥对
            KeyPair keyPair = getKeyPair();
            String privateKey = new String(Base64.encodeBase64(keyPair.getPrivate().getEncoded()));
            String publicKey = new String(Base64.encodeBase64(keyPair.getPublic().getEncoded()));
            System.out.println("私钥:" + privateKey);
            System.out.println("公钥:" + publicKey);
            // RSA加密
            String data = "待加密的文字内容";
            String encryptData = encrypt(data, getPublicKey(publicKey));
            System.out.println("加密后内容:" + encryptData);
            // RSA解密
            String decryptData = decrypt(encryptData, getPrivateKey(privateKey));
            System.out.println("解密后内容:" + decryptData);

            // RSA签名
            String sign = sign(data, getPrivateKey(privateKey));
            // RSA验签
            boolean result = verify(data, getPublicKey(publicKey), sign);
            System.out.print("验签结果:" + result);
        } catch (Exception e) {
    
    
            e.printStackTrace();
            System.out.print("加解密异常");
        }
    }

参考:https://blog.csdn.net/qy20115549/article/details/83105736

猜你喜欢

转载自blog.csdn.net/weixin_43727535/article/details/107470938
RAS