一、非对称简介
与对称加密算法不同,非对称加密算法需要两个密钥:公开密钥(publickey)
和私有密钥(privatekey)
。公开密钥与私有密钥是一对,如果用公开密钥对数据进行加密,只有用对应的私有密钥才能解密;如果用私有密钥对数据进行加密,那么只有用对应的公开密钥才能解密。因为加密和解密使用的是两个不同的密钥,所以这种算法叫作非对称加密算法。
- 常见非对称加密算法
RSA
、DSA
。 - 非对称加密算法私钥由数据接收方持有,不会在网络上传递,保证了密钥的安全。
- 非对称加密算法通常比对称加密算法计算复杂,性能消耗高。
- 非对称加密算法可用于数字签名。
注意:
- 使用时都是使用公钥加密使用私钥解密,公钥可以公开,私钥自己保留。
- 算法强度复杂、安全性依赖于算法与密钥但是由于其算法复杂,而使加密解密速度慢于对称加密
二、RSA
RSA
的私钥、公钥、明文、密文长度有一定对应关系:
私钥长度 | 公钥长度 | 明文长度 | 密文长度 |
---|---|---|---|
428 | 128 | 1~53 | 88 |
812 | 216 | 1~117 | 172 |
1588 | 392 | 1~245 | 344 |
1.JavaScript 实现
// npm install node-rsa --save
// 引用 node-rsa 加密模块
var NodeRSA = require('node-rsa');
function rsaEncrypt() {
pubKey = new NodeRSA(publicKey,'pkcs8-public');
var encryptedData = pubKey.encrypt(text, 'base64');
return encryptedData
}
function rsaDecrypt() {
priKey = new NodeRSA(privatekey,'pkcs8-private');
var decryptedData = priKey.decrypt(encryptedData, 'utf8');
return decryptedData
}
var key = new NodeRSA({b: 512}); //生成512位秘钥
var publicKey = key.exportKey('pkcs8-public'); //导出公钥
var privatekey = key.exportKey('pkcs8-private'); //导出私钥
var text = "I love Python!"
var encryptedData = rsaEncrypt()
var decryptedData = rsaDecrypt()
console.log("公钥:\n", publicKey)
console.log("私钥:\n", privatekey)
console.log("加密字符串: ", encryptedData)
console.log("解密字符串: ", decryptedData)
常见JavaScript调试算法
- 搜索关键词 `
- new JSEncrypt()
,
JSEncrypt等,一般会使用
JSEncrypt `库,会有 new 一个实例对象的操作; - 搜索关键词
setPublicKey
、setKey
、setPrivateKey
、getPublicKey
等,一般实现的代码里都含有设置密钥的过程。
1.python实现
模块:rsa
# -*- coding: utf-8 -*-
import rsa
import base64
def rsa_encrypt(pu_key, t):
# 公钥加密
rsas = rsa.encrypt(t.encode("utf-8"), pu_key)
return base64.b64encode(rsas)
def rsa_decrypt(pr_key, t):
# 私钥解密
rsas = rsa.decrypt(base64.b64decode(t), pr_key).decode("utf-8")
return rsas
if __name__ == "__main__":
public_key, private_key = rsa.newkeys(512) # 生成公钥、私钥
print('公钥:', public_key)
print('私钥:', private_key)
text = 'I love Python!' # 加密对象
encrypted_str = rsa_encrypt(public_key, text)
print('加密字符串:', encrypted_str)
decrypted_str = rsa_decrypt(private_key, encrypted_str)
print('解密字符串:', decrypted_str)