一、简介
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);