rsa加解密+

public class RSAUtils {

private static final Logger log = LoggerFactory.getLogger(RSAUtils.class);

    private static final String TYPE = "RSA";

    private static final String SIGN_ALGORITHM = "MD5withRSA";

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

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

    /**
     * 密钥长度
     */
    private static final int KEY_SIZE = 2048;

    public static final String PUBLIC_KEY = "PUBLIC_KEY";
    public static final String PRIVATE_KEY = "PRIVATE_KEY";

    /**
     * 生成密钥对
     *
     * @return 密钥对
     */
    public static Map<String,String> getKeyPair() throws Exception {
        Map<String,String> map = new HashMap<String,String>(2);
        KeyPairGenerator generator = KeyPairGenerator.getInstance(TYPE);
        generator.initialize(KEY_SIZE);
        KeyPair keyPair = generator.generateKeyPair();
        map.put(PRIVATE_KEY, Base64Utils.encodeToString(keyPair.getPrivate().getEncoded()));
        map.put(PUBLIC_KEY,Base64Utils.encodeToString(keyPair.getPublic().getEncoded()));
        return map;
    }

    /**
     * 获取私钥
     *
     * @param privateKey 私钥字符串
     * @return
     */
    private static PrivateKey getPrivateKey(String privateKey) throws Exception {
        KeyFactory keyFactory = KeyFactory.getInstance(TYPE);
        byte[] decodedKey = Base64Utils.decodeFromString(privateKey);
        PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(decodedKey);
        return keyFactory.generatePrivate(keySpec);
    }

    /**
     * 获取公钥
     *
     * @param publicKey 公钥字符串
     * @return
     */
    private static PublicKey getPublicKey(String publicKey) throws Exception {
        KeyFactory keyFactory = KeyFactory.getInstance(TYPE);
        byte[] decodedKey = Base64Utils.decodeFromString(publicKey);
        X509EncodedKeySpec keySpec = new X509EncodedKeySpec(decodedKey);
        return keyFactory.generatePublic(keySpec);
    }

    /**
     * RSA加密
     *
     * @param data 待加密数据
     * @param pubKey 公钥
     * @return
     */
    public static String encrypt(String data, String pubKey) throws Exception {
        try {
            PublicKey publicKey = getPublicKey(pubKey);
            Cipher cipher = Cipher.getInstance(TYPE);
            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进行编码
            // 加密后的字符串
            return Base64Utils.encodeToString(encryptedData);
        }catch(Exception e){
            log.info("加密异常");
            throw new Exception(e.getMessage());
        }
    }

    /**
     * RSA解密
     *
     * @param data 待解密数据
     * @param priKey 私钥
     * @return
     */
    public static String decrypt(String data, String priKey) throws Exception {
        try {
            PrivateKey privateKey = getPrivateKey(priKey);
            Cipher cipher = Cipher.getInstance(TYPE);
            cipher.init(Cipher.DECRYPT_MODE, privateKey);
            byte[] dataBytes = Base64Utils.decodeFromString(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, StandardCharsets.UTF_8);
        }catch (Exception e){
            log.info("解密异常");
            throw new Exception(e.getMessage());
        }
    }

    /**
     * 签名
     *
     * @param data 待签名数据
     * @param priKey 私钥
     * @return 签名
     */
    public static String sign(String data, String priKey) throws Exception {
        try {
            Security.addProvider(
                    new org.bouncycastle.jce.provider.BouncyCastleProvider()
            );
            PrivateKey privateKey = getPrivateKey(priKey);
            byte[] keyBytes = privateKey.getEncoded();
            PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyBytes);
            KeyFactory keyFactory = KeyFactory.getInstance(TYPE);
            PrivateKey key = keyFactory.generatePrivate(keySpec);
            Signature signature = Signature.getInstance(SIGN_ALGORITHM);
            signature.initSign(key);
            signature.update(data.getBytes());
            return Base64Utils.encodeToString(signature.sign());
        }catch (Exception e){
            log.info("签名异常");
            e.printStackTrace();
            throw new Exception(e.getMessage());
        }
    }

    /**
     * 验签
     *
     * @param srcData 原始字符串
     * @param pubKey 公钥
     * @param sign 签名
     * @return 是否验签通过
     */
    public static boolean verify(String srcData, String pubKey, String sign) throws Exception {
        try {
            PublicKey publicKey = getPublicKey(pubKey);
            byte[] keyBytes = publicKey.getEncoded();
            X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);
            KeyFactory keyFactory = KeyFactory.getInstance("RSA");
            PublicKey key = keyFactory.generatePublic(keySpec);
            Signature signature = Signature.getInstance(SIGN_ALGORITHM);
            signature.initVerify(key);
            signature.update(srcData.getBytes());
            return signature.verify(Base64Utils.decode(sign.getBytes()));
        }catch (Exception e){
            log.info("验签异常");
            e.printStackTrace();
            throw new Exception(e.getMessage());
        }
    }


    public static void main(String[] args) {

        try {

            // 生成密钥对
            Map map = getKeyPair();
            String privateKey = (String) map.get(RSAUtils.PRIVATE_KEY);
            String publicKey = (String) map.get(RSAUtils.PUBLIC_KEY);

            String aa = sign("ssss",privateKey);


            // RSA加密
            String data = "123";
            String encryptData = encrypt(data, publicKey);


            // RSA解密
            String decryptData = decrypt(encryptData, privateKey);


            // RSA签名
            String sign = sign(data, privateKey);


            // RSA验签
            boolean result = verify(data, publicKey, sign);

        } catch (Exception e) {
            e.printStackTrace();

        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值