RSA加密解密

一、简介

RSA加密算法是一种非对称加密算法,基于公钥加密私钥解密和私钥加密公钥解密两种使用方式。
RSA算法基于一个十分简单的数论事实:将两个大质数相乘十分容易,但是想要对其乘积进行因式分解却极其困难,因此可以将乘积公开作为加密密钥。
在这里插入图片描述
其中:E(Encryption), D(Decryption), N(Number)都是整数

二、安全性

RSA是目前最有影响力和最常用的公钥加密算法,它能够抵抗到目前为止已知的绝大多数密码攻击,已被ISO推荐为公钥数据加密标准。
对极大整数做因数分解的难度决定了RSA算法的可靠性。换言之,对一极大整数做因数分解愈困难,RSA算法愈可靠。

三、缺点:运算速度慢

四、常用解决方案

1、结合Base64来解决密文太长的问题
2、结合数字签名sign,来解决中间人窃取信息的攻击行为

五、Demo

import java.nio.charset.Charset;
import java.security.Key;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.SecureRandom;
import java.security.Signature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.crypto.Cipher;
import java.io.ByteArrayOutputStream;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;

/**
 * RSA 工具类
 **/
public class RsaUtil {
    private static Logger logger = LoggerFactory.getLogger(RsaUtil.class);

    /**
     * 加密
     */
    public static byte[] encrypt(byte[] data, Key key) {
        if (data == null || data.length == 0 || key == null) {
            return null;
        }

        // 1024 位密钥最多支持 117 字节明文加密,超过则分段加密
        if (data.length > 117) {
            return segmentEncrypt(data, key);
        }

        try {
            Cipher cipher = Cipher.getInstance("RSA");
            cipher.init(Cipher.ENCRYPT_MODE, key);
            return cipher.doFinal(data);
        } catch (Exception e) {
            logger.error("encrypt error", e);
            return null;
        }
    }

    /**
     * 分段加密
     */
    private static byte[] segmentEncrypt(byte[] data, Key key) {
        if (data == null || data.length == 0 || key == null) {
            return null;
        }

        try {
            Cipher cipher = Cipher.getInstance("RSA");
            cipher.init(Cipher.ENCRYPT_MODE, key);

            ByteArrayOutputStream output = new ByteArrayOutputStream();
            int length = data.length;
            int offset = 0;
            byte[] cache;

            while (length > offset) {
                if (length - offset > 117) {
                    cache = cipher.doFinal(data, offset, 117);
                } else {
                    cache = cipher.doFinal(data, offset, length - offset);
                }
                output.write(cache, 0, cache.length);

                offset += 117;
            }

            return output.toByteArray();
        } catch (Exception e) {
            logger.error("encrypt error", e);
            
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值