使用jsencrypt.js实现RSA加密和解密(短消息版)

<!doctype html>
<html lang="zh">
<head>
<meta charset="utf-8">
<title>使用jsencrypt.js实现RSA加密和解密</title>
</head>
<body>
<script type="text/javascript" src="./jsencrypt.min.js"></script>
<script type="text/javascript">
//========== 公钥 ==========//
var publicKey = `-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAzjGQT86U567mS2j3dzuf
Q6sDJJDGfnO9J8ESaiwvMChZ30zD/USypRlKSnX1d+bqTLFMoNEOK/bQmqZiiSk5
Fzek2IA78n4NsvorKfsc5Gje2RQGqG5kKMt1TfLg2cF8dOZ+8Q6FoJ6EB3Dd1KPU
f0duLcEXs+Am70CVeBs7aGYVUY2dtVlAVSK1mlUmYWNxRlk5V5oSdUaHN9vAzgiJ
Y844bbpP3XOCgT/Fc0sN+AVoGIrgAyGt1qWHTiXIbJQ0ocyFoaT/CCdP7ueqesJp
LCxupSqoS0SdNh3JpbLz4ZnHGug7uP1mqwkGQACAJfYE6X7fNRO+BIaVJRGCMBcm
jwIDAQAB
-----END PUBLIC KEY-----`;

//========== 私钥 ==========//
var privateKey = `-----BEGIN PRIVATE KEY-----
MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQDOMZBPzpTnruZL
aPd3O59DqwMkkMZ+c70nwRJqLC8wKFnfTMP9RLKlGUpKdfV35upMsUyg0Q4r9tCa
pmKJKTkXN6TYgDvyfg2y+isp+xzkaN7ZFAaobmQoy3VN8uDZwXx05n7xDoWgnoQH
cN3Uo9R/R24twRez4CbvQJV4GztoZhVRjZ21WUBVIrWaVSZhY3FGWTlXmhJ1Roc3
28DOCIljzjhtuk/dc4KBP8VzSw34BWgYiuADIa3WpYdOJchslDShzIWhpP8IJ0/u
56p6wmksLG6lKqhLRJ02HcmlsvPhmcca6Du4/WarCQZAAIAl9gTpft81E74EhpUl
EYIwFyaPAgMBAAECggEAR5X7lUmSdvFI8QtrRx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lREsXbqfpa6WU50BLXFxknP+91QYwOHafZpdjm7LL8GJ7H5vmyK
CLhxY5fZejlze0eMa8A07JWBH9F4cBamI9NbmatfmhlvLjPaRcNaoyuk1W8LuL9Z
im+u/8E9Zm1atbpr7lP33YQ=
-----END PRIVATE KEY-----`;

var jse = new JSEncrypt();

//========== 使用公钥加密 ==========//
jse.setPublicKey(publicKey); // 设置公钥
var ciphertext = jse.encrypt('PHP是世界上最好の语言'); // 注:每次加密得到的密文都是不同的
console.log('密文:' + ciphertext); // 密文:y1LcbtL8ej64zoHbbMHXbrHrAWVhj0qm6s7UGzWHe……

//========== 使用私钥解密 ==========//
jse.setPrivateKey(privateKey); // 设置私钥
var plaintext = jse.decrypt(ciphertext);
console.log('明文:' + plaintext); // 明文:PHP是世界上最好の语言
</script>
</body>
</html>

Copyright © 2024 码农人生. All Rights Reserved