Java
import org.apache.commons.codec.binary.Base64;
import javax.crypto.Cipher;
import java.io.ByteArrayOutputStream;
import java.security.*;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
public class RSAUtil {
private static final int MAX_ENCRYPT_BLOCK = 117;
private static final int MAX_DECRYPT_BLOCK = 128;
public static KeyPair getKeyPair() throws Exception {
KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA");
generator.initialize(1024);
return generator.generateKeyPair();
}
public static PrivateKey getPrivateKey(String privateKey) throws Exception {
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
byte[] decodedKey = Base64.decodeBase64(privateKey.getBytes());
PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(decodedKey);
return keyFactory.generatePrivate(keySpec);
}
public static PublicKey getPublicKey(String publicKey) throws Exception {
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
byte[] decodedKey = Base64.decodeBase64(publicKey.getBytes());
X509EncodedKeySpec keySpec = new X509EncodedKeySpec(decodedKey);
return keyFactory.generatePublic(keySpec);
}
public static String encrypt(String data, PublicKey publicKey) throws Exception {
Cipher cipher = Cipher.getInstance("RSA");
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();
return new String(Base64.encodeBase64String(encryptedData));
}
public static String decrypt(String data, PrivateKey privateKey) throws Exception {
Cipher cipher = Cipher.getInstance("RSA");
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");
}
public static String sign(String data, PrivateKey privateKey) throws Exception {
byte[] keyBytes = privateKey.getEncoded();
PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyBytes);
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
PrivateKey key = keyFactory.generatePrivate(keySpec);
Signature signature = Signature.getInstance("MD5withRSA");
signature.initSign(key);
signature.update(data.getBytes());
return new String(Base64.encodeBase64(signature.sign()));
}
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("RSA");
PublicKey key = keyFactory.generatePublic(keySpec);
Signature signature = Signature.getInstance("MD5withRSA");
signature.initVerify(key);
signature.update(srcData.getBytes());
return signature.verify(Base64.decodeBase64(sign.getBytes()));
}
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);
String data = "张三123456";
String encryptData = encrypt(data, getPublicKey(publicKey));
System.out.println("加密后内容:" + encryptData);
String decryptData = decrypt(encryptData, getPrivateKey(privateKey));
System.out.println("解密后内容:" + decryptData);
String sign = sign(data, getPrivateKey(privateKey));
boolean result = verify(data, getPublicKey(publicKey), sign);
System.out.print("验签结果:" + result);
} catch (Exception e) {
e.printStackTrace();
System.out.print("加解密异常");
}
}
}
Html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>使用jsencrypt的RSA加密,解密</title>
</head>
<script src="../static/js/jsencrypt.js"></script>
<script type="text/javascript">
var PUBLIC_KEY = 'MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCkFFoi5kycZssTvGRRjQVTmJJ+qAKrQbX6MxL+edILUv9F0MQt24Rd2tpdkvpcHygL7/b8LvV/meazq5EtcwDwlR7330AIP877Mqp85hVE8w9Kxfb47yS8+wpmimkuum52u/cMBbuBCS/sshnPs5ox0bwT7FNWFMrM76jKAafVowIDAQAB';
var PRIVATE_KEY ='MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBAKQUWiLmTJxmyxO8ZFGNBVOYkn6oAqtBtfozEv550gtS/0XQxC3bhF3a2l2S+lwfKAvv9vwu9X+Z5rOrkS1zAPCVHvffQAg/zvsyqnzmFUTzD0rF9vjvJLz7CmaKaS66bna79wwFu4EJL+yyGc+zmjHRvBPsU1YUyszvqMoBp9WjAgMBAAECgYEAo+oNDfZiLJDoaUP4OBwYaSXvm4Y+fFW99UCWxhBvDI8So+1mPqWg+54KLhcJ84PQnvRQGijTanEWLwHDm9La6OCHKchpnLl+epMHKdrwx42GyjlfLjKDWHT7Iaj+f/bpI6njEYi0HlUjr3xPooRGUH9OV8B0L9ZhCj+U5JMqfGECQQDnyo1aFfeBbl/p+J7/i8wLY2gX7MuXODISffA0fZZrrF3R2FqYKH4CWpsTdm3NgCpe/pfiPZtKXfEpcbk41upRAkEAtTdg1iE6XNajLzGndpxrOOQqOArP74N9Q8IIS9rhGtTPF1lx7K2hv+BIx2WcYwrr1xwhAy0JatK1AcAKaCNPswJBAIGpoDr1sNfZm5PxvVfspv7z48YGc7kq+W+4vYdPfbbL3EvIAJ2/gQXmE3vmsvPTL2CmgOZRWi5WsNJjSJ7QMpECQD1QNWV97J9IyAHJzR1moyimmlpH3j7twE5SsjfoIM3RPxhpXRB1Vwryue0tRhKEuXMYw1qtvEf2buPetCaz+90CQFqeY2QH7/q5Qsp6hQD5x+yZWTCjMH4gARHp2ye5/uSA48I0zHmLtEolERnbUDeZbz8tQo8cRLFjaVgHxmEOHBM=';
var encrypt = new JSEncrypt();
encrypt.setPublicKey('-----BEGIN PUBLIC KEY-----' + PUBLIC_KEY + '-----END PUBLIC KEY-----');
var str = {
"name":"张三",
"password":"123456"
}
var encrypted = encrypt.encrypt(JSON.stringify(str));
console.log('加密前数据:%o', str);
console.log('加密后数据:%o', encrypted);
var decrypt = new JSEncrypt();
decrypt.setPrivateKey('-----BEGIN RSA PRIVATE KEY-----'+PRIVATE_KEY+'-----END RSA PRIVATE KEY-----');
var uncrypted = decrypt.decrypt(encrypted);
console.log('解密后数据:%o', uncrypted);
</script>
</html>
JS
jsencrypt.js
React & Vue
- 安装包:npm install jsencrypt
- 页面使用
import { JSEncrypt } from ‘jsencrypt’;
const PUBLIC_KEY = ‘公钥’
var encrypt=new JSEncrypt();
encrypt.setPublicKey(PUBLIC_KEY);
// 加密数据
var res = encrypt.encrypt(‘要加密的字符串’);
console.log(res); // 打印加密后的数据