参考资料:
在一些对称和非对称加密算法中,经常会用到以下三个参数:初始向量 iv、加密模式 mode、填充方式 padding,先介绍一下这三个参数的含义和作用:
Base64 维基百科:https://en.wikipedia.org/wiki/Base64
// 引用 crypto-js 加密模块
var CryptoJS = require('crypto-js')
function base64Encode() {
var srcs = CryptoJS.enc.Utf8.parse(text);
var encodeData = CryptoJS.enc.Base64.stringify(srcs);
return encodeData
}
function base64Decode() {
var srcs = CryptoJS.enc.Base64.parse(encodeData);
var decodeData = srcs.toString(CryptoJS.enc.Utf8);
return decodeData
}
var text = "I love Python!"
var encodeData = base64Encode()
var decodeData = base64Decode()
console.log("Base64 编码: ", encodeData)
console.log("Base64 解码: ", decodeData)
// Base64 编码: SSBsb3ZlIFB5dGhvbiE=
// Base64 解码: I love Python!
import base64
def base64_encode(text):
encode_data = base64.b64encode(text.encode())
return encode_data
def base64_decode(encode_data):
decode_data = base64.b64decode(encode_data)
return decode_data
if __name__ == '__main__':
text = 'I love Python!'
encode_data = base64_encode(text)
decode_data = base64_decode(encode_data)
print('Base64 编码:', encode_data)
print('Base64 解码:', decode_data)
# Base64 编码:b'SSBsb3ZlIFB5dGhvbiE='
# Base64 解码:b'I love Python!'
// 引用 crypto-js 加密模块
var CryptoJS = require('crypto-js')
function MD5Test() {
var text = "I love python!"
return CryptoJS.MD5(text).toString()
}
console.log(MD5Test()) // 21169ee3acd4a24e1fcb4322cfd9a2b8
import hashlib
def md5_test1():
md5 = hashlib.new('md5', 'I love python!'.encode('utf-8'))
print(md5.hexdigest())
def md5_test2():
md5 = hashlib.md5()
md5.update('I love '.encode('utf-8'))
md5.update('python!'.encode('utf-8'))
print(md5.hexdigest())
if __name__ == '__main__':
md5_test1() # 21169ee3acd4a24e1fcb4322cfd9a2b8
md5_test2() # 21169ee3acd4a24e1fcb4322cfd9a2b8
// 引用 crypto-js 加密模块
var CryptoJS = require('crypto-js')
function pbkdf2Encrypt() {
var text = "I love Python!"
var salt = "43215678"
// key 长度 128,10 次重复运算
var encryptedData = CryptoJS.PBKDF2(text, salt, {keySize: 128/32,iterations: 10});
return encryptedData.toString()
}
console.log(pbkdf2Encrypt()) // 7fee6e8350cfe96314c76aaa6e853a50
import binascii
from Cryptodome.Hash import SHA1
from Cryptodome.Protocol.KDF import PBKDF2
text = 'I love Python!'
salt = b'43215678'
result = PBKDF2(text, salt, count=10, hmac_hash_module=SHA1)
result = binascii.hexlify(result)
print(result)
# b'7fee6e8350cfe96314c76aaa6e853a50'
// 引用 crypto-js 加密模块
var CryptoJS = require('crypto-js')
function SHA1Encrypt() {
var text = "I love python!"
return CryptoJS.SHA1(text).toString();
}
console.log(SHA1Encrypt()) // 23c02b203bd2e2ca19da911f1d270a06d86719fb
import hashlib
def sha1_test1():
sha1 = hashlib.new('sha1', 'I love python!'.encode('utf-8'))
print(sha1.hexdigest())
def sha1_test2():
sha1 = hashlib.sha1()
sha1.update('I love python!'.encode('utf-8'))
print(sha1.hexdigest())
if __name__ == '__main__':
sha1_test1() # 23c02b203bd2e2ca19da911f1d270a06d86719fb
sha1_test2() # 23c02b203bd2e2ca19da911f1d270a06d86719fb
// 引用 crypto-js 加密模块
var CryptoJS = require('crypto-js')
function HMACEncrypt() {
var text = "I love python!"
var key = "secret"
return CryptoJS.HmacMD5(text, key).toString();
// return CryptoJS.HmacSHA1(text, key).toString();
// return CryptoJS.HmacSHA256(text, key).toString();
}
console.log(HMACEncrypt())
import hmac
def hmac_test1():
message = b'I love python!'
key = b'secret'
md5 = hmac.new(key, message, digestmod='MD5')
print(md5.hexdigest())
def hmac_test2():
key = 'secret'.encode('utf8')
sha1 = hmac.new(key, digestmod='sha1')
sha1.update('I love '.encode('utf8'))
sha1.update('Python!'.encode('utf8'))
print(sha1.hexdigest())
if __name__ == '__main__':
hmac_test1() # 9c503a1f852edcc3526ea56976c38edf
hmac_test2() # 2d8449a4292d4bbeed99ce9ea570880d6e19b61a
// 引用 crypto-js 加密模块
var CryptoJS = require('crypto-js')
function desEncrypt() {
var key = CryptoJS.enc.Utf8.parse(desKey),
iv = CryptoJS.enc.Utf8.parse(desIv),
srcs = CryptoJS.enc.Utf8.parse(text),
// CBC 加密模式,Pkcs7 填充方式
encrypted = CryptoJS.DES.encrypt(srcs, key, {
iv: iv,
mode: CryptoJS.mode.CBC,
padding: CryptoJS.pad.Pkcs7
});
return encrypted.toString();
}
function desDecrypt() {
var key = CryptoJS.enc.Utf8.parse(desKey),
iv = CryptoJS.enc.Utf8.parse(desIv),
srcs = encryptedData,
// CBC 加密模式,Pkcs7 填充方式
decrypted = CryptoJS.DES.decrypt(srcs, key, {
iv: iv,
mode: CryptoJS.mode.CBC,
padding: CryptoJS.pad.Pkcs7
});
return decrypted.toString(CryptoJS.enc.Utf8);
}
var text = "I love Python!" // 待加密对象
var desKey = "6f726c64f2c2057" // 密钥
var desIv = "0123456789ABCDEF" // 初始向量
var encryptedData = desEncrypt()
var decryptedData = desDecrypt()
console.log("加密字符串: ", encryptedData)
console.log("解密字符串: ", decryptedData)
// 加密字符串: +ndbEkWNw2QAfIYQtwC14w==
// 解密字符串: I love Python!
import binascii
# 加密模式 CBC,填充方式 PAD_PKCS5
from pyDes import des, CBC, PAD_PKCS5
def des_encrypt(key, text, iv):
k = des(key, CBC, iv, pad=None, padmode=PAD_PKCS5)
en = k.encrypt(text, padmode=PAD_PKCS5)
return binascii.b2a_hex(en)
def des_decrypt(key, text, iv):
k = des(key, CBC, iv, pad=None, padmode=PAD_PKCS5)
de = k.decrypt(binascii.a2b_hex(text), padmode=PAD_PKCS5)
return de
if __name__ == '__main__':
secret_key = '12345678' # 密钥
text = 'I love Python!' # 加密对象
iv = secret_key # 偏移量
secret_str = des_encrypt(secret_key, text, iv)
print('加密字符串:', secret_str)
clear_str = des_decrypt(secret_key, secret_str, iv)
print('解密字符串:', clear_str)
# 加密字符串:b'302d3abf2421169239f829b38a9545f1'
# 解密字符串:b'I love Python!'
// 引用 crypto-js 加密模块
var CryptoJS = require('crypto-js')
function tripleDesEncrypt() {
var key = CryptoJS.enc.Utf8.parse(desKey),
iv = CryptoJS.enc.Utf8.parse(desIv),
srcs = CryptoJS.enc.Utf8.parse(text),
// ECB 加密方式,Iso10126 填充方式
encrypted = CryptoJS.TripleDES.encrypt(srcs, key, {
iv: iv,
mode: CryptoJS.mode.ECB,
padding: CryptoJS.pad.Iso10126
});
return encrypted.toString();
}
function tripleDesDecrypt() {
var key = CryptoJS.enc.Utf8.parse(desKey),
iv = CryptoJS.enc.Utf8.parse(desIv),
srcs = encryptedData,
// ECB 加密方式,Iso10126 填充方式
decrypted = CryptoJS.TripleDES.decrypt(srcs, key, {
iv: iv,
mode: CryptoJS.mode.ECB,
padding: CryptoJS.pad.Iso10126
});
return decrypted.toString(CryptoJS.enc.Utf8);
}
var text = "I love Python!" // 待加密对象
var desKey = "6f726c64f2c2057c" // 密钥
var desIv = "0123456789ABCDEF" // 偏移量
var encryptedData = tripleDesEncrypt()
var decryptedData = tripleDesDecrypt()
console.log("加密字符串: ", encryptedData)
console.log("解密字符串: ", decryptedData)
// 加密字符串: 3J0NX7x6GbewjjhoW2HKqg==
// 解密字符串: I love Python!
from Cryptodome.Cipher import DES3
from Cryptodome import Random
# 需要补位,str不是16的倍数那就补足为16的倍数
def add_to_16(value):
while len(value) % 16 != 0:
value += '\0'
return str.encode(value)
def des_encrypt(key, text, iv):
# 加密模式 OFB
cipher_encrypt = DES3.new(add_to_16(key), DES3.MODE_OFB, iv)
encrypted_text = cipher_encrypt.encrypt(text.encode("utf-8"))
return encrypted_text
def des_decrypt(key, text, iv):
# 加密模式 OFB
cipher_decrypt = DES3.new(add_to_16(key), DES3.MODE_OFB, iv)
decrypted_text = cipher_decrypt.decrypt(text)
return decrypted_text
if __name__ == '__main__':
key = '12345678' # 密钥,16 位
text = 'I love Python!' # 加密对象
iv = Random.new().read(DES3.block_size) # DES3.block_size == 8
secret_str = des_encrypt(key, text, iv)
print('加密字符串:', secret_str)
clear_str = des_decrypt(key, secret_str, iv)
print('解密字符串:', clear_str)
# 加密字符串:b'\xa5\x8a\xd4R\x99\x16j\xba?vg\xf2\xb6\xa9'
# 解密字符串:b'I love Python!'
// 引用 crypto-js 加密模块
var CryptoJS = require('crypto-js')
function tripleAesEncrypt() {
var key = CryptoJS.enc.Utf8.parse(aesKey),
iv = CryptoJS.enc.Utf8.parse(aesIv),
srcs = CryptoJS.enc.Utf8.parse(text),
// CBC 加密方式,Pkcs7 填充方式
encrypted = CryptoJS.AES.encrypt(srcs, key, {
iv: iv,
mode: CryptoJS.mode.CBC,
padding: CryptoJS.pad.Pkcs7
});
return encrypted.toString();
}
function tripleAesDecrypt() {
var key = CryptoJS.enc.Utf8.parse(aesKey),
iv = CryptoJS.enc.Utf8.parse(aesIv),
srcs = encryptedData,
// CBC 加密方式,Pkcs7 填充方式
decrypted = CryptoJS.AES.decrypt(srcs, key, {
iv: iv,
mode: CryptoJS.mode.CBC,
padding: CryptoJS.pad.Pkcs7
});
return decrypted.toString(CryptoJS.enc.Utf8);
}
var text = "I love Python!" // 待加密对象
var aesKey = "6f726c64f2c2057c" // 密钥,16 倍数
var aesIv = "0123456789ABCDEF" // 偏移量,16 倍数
var encryptedData = tripleAesEncrypt()
var decryptedData = tripleAesDecrypt()
console.log("加密字符串: ", encryptedData)
console.log("解密字符串: ", decryptedData)
// 加密字符串: dZL7TLJR786VGvuUvqYGoQ==
// 解密字符串: I love Python!
import base64
from Cryptodome.Cipher import AES
# 需要补位,str不是16的倍数那就补足为16的倍数
def add_to_16(value):
while len(value) % 16 != 0:
value += '\0'
return str.encode(value)
# 加密方法
def aes_encrypt(key, t, iv):
aes = AES.new(add_to_16(key), AES.MODE_CBC, add_to_16(iv)) # 初始化加密器
encrypt_aes = aes.encrypt(add_to_16(t)) # 先进行 aes 加密
encrypted_text = str(base64.encodebytes(encrypt_aes), encoding='utf-8') # 执行加密并转码返回 bytes
return encrypted_text
# 解密方法
def aes_decrypt(key, t, iv):
aes = AES.new(add_to_16(key), AES.MODE_CBC, add_to_16(iv)) # 初始化加密器
base64_decrypted = base64.decodebytes(t.encode(encoding='utf-8')) # 优先逆向解密 base64 成 bytes
decrypted_text = str(aes.decrypt(base64_decrypted), encoding='utf-8').replace('\0', '') # 执行解密密并转码返回str
return decrypted_text
if __name__ == '__main__':
secret_key = '12345678' # 密钥
text = 'I love Python!' # 加密对象
iv = secret_key # 初始向量
encrypted_str = aes_encrypt(secret_key, text, iv)
print('加密字符串:', encrypted_str)
decrypted_str = aes_decrypt(secret_key, encrypted_str, iv)
print('解密字符串:', decrypted_str)
# 加密字符串:lAVKvkQh+GtdNpoKf4/mHA==
# 解密字符串:I love Python!
// 引用 crypto-js 加密模块
var CryptoJS = require('crypto-js')
function RC4Encrypt() {
return CryptoJS.RC4.encrypt(text, key).toString();
}
function RC4Decrypt(){
return CryptoJS.RC4.decrypt(encryptedData, key).toString(CryptoJS.enc.Utf8);
}
var text = "I love Python!"
var key = "6f726c64f2c2057c"
var encryptedData = RC4Encrypt()
var decryptedData = RC4Decrypt()
console.log("加密字符串: ", encryptedData)
console.log("解密字符串: ", decryptedData)
// 加密字符串: U2FsdGVkX18hMm9WWdoEQGPolnXzlg9ryArdGNwv
// 解密字符串: I love Python!
import base64
from Cryptodome.Cipher import ARC4
def rc4_encrypt(key, t):
enc = ARC4.new(key.encode('utf8'))
res = enc.encrypt(t.encode('utf-8'))
res = base64.b64encode(res)
return res
def rc4_decrypt(key, t):
data = base64.b64decode(t)
enc = ARC4.new(key.encode('utf8'))
res = enc.decrypt(data)
return res
if __name__ == "__main__":
secret_key = '12345678' # 密钥
text = 'I love Python!' # 加密对象
encrypted_str = rc4_encrypt(secret_key, text)
print('加密字符串:', encrypted_str)
decrypted_str = rc4_decrypt(secret_key, encrypted_str)
print('解密字符串:', decrypted_str)
# 加密字符串:b'8tNVu3/U/veJR2KgyBw='
# 解密字符串:b'I love Python!'
// 引用 crypto-js 加密模块
var CryptoJS = require('crypto-js')
function rabbitEncrypt() {
return CryptoJS.Rabbit.encrypt(text, key).toString();
}
function rabbitDecrypt() {
return CryptoJS.Rabbit.decrypt(encryptedData, key).toString(CryptoJS.enc.Utf8);
}
var text = "I love Python!"
var key = "6f726c64f2c2057"
var encryptedData = rabbitEncrypt()
var decryptedData = rabbitDecrypt()
console.log("加密字符串: ", encryptedData)
console.log("解密字符串: ", decryptedData)
// 加密字符串: U2FsdGVkX1+ZVCHRXlhmG5Xw87YPWMNIBlbukuh8
// 解密字符串: I love Python!
// 引用 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)
/*
公钥:
-----BEGIN PUBLIC KEY-----
MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAOV1BwTJSVce/QjJAro5fXG9WzOpal09
Qtv1yuXKE81vZSNTHxW6dICwPT/kjCfC3bA5Qs6wnYBANuwD6wlAS0UCAwEAAQ==
-----END PUBLIC KEY-----
私钥:
-----BEGIN PRIVATE KEY-----
MIIBVAIBADANBgkqhkiG9w0BAQEFAASCAT4wggE6AgEAAkEA5XUHBMlJVx79CMkC
ujl9cb1bM6lqXT1C2/XK5coTzW9lI1MfFbp0gLA9P+SMJ8LdsDlCzrCdgEA27APr
CUBLRQIDAQABAkAiXwJbJC+5PioXG80tyhjRZdT4iyMkrl2Kh2oKO9f1iLaBXLya
D0HW82wFh+cUy8GcMl9jse8DE8wd1TdORmHhAiEA/rwmWjXHVgDqcH/fqk8Ufku0
fXvs56h5QDoh1so5vokCIQDmmL3JDW6Y7RuK2qwFbHBZtYPRFRVdn5X1oqU2FOSX
3QIhAOVTjVN5RtNuT6Cn/jvcpZ5tmTe+8TA8w6vGqeAsfn/BAiBvKKIUEQ2HWoU0
YkUaODPQiteIKomqIAvB5S2O7HNlYQIgWMuLUxGZbbcAmIX+YmRXuET97S7OWv+z
WHVfb/rbXtI=
-----END PRIVATE KEY-----
加密字符串: hHXTF1K3w55Wd6OSjVYtqxceJ5VhlySNUahel9pwKD92Ef7wIT7DYPuJRKiqz5tuHtUqujbmbZBSL0qDE/EA+A==
解密字符串: I love Python!
*/
import rsa
def rsa_encrypt(pu_key, t):
# 公钥加密
rsa = rsa.encrypt(t.encode("utf-8"), pu_key)
return rsa
def rsa_decrypt(pr_key, t):
# 私钥解密
rsa = rsa.decrypt(t, pr_key).decode("utf-8")
return rsa
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)
'''
公钥:PublicKey(7636479066127060956100056267701318377455704072072698049978592945665550579944731953431504993757594103617537700972424661030900303472123028864161050235168613, 65537)
私钥:PrivateKey(7636479066127060956100056267701318377455704072072698049978592945665550579944731953431504993757594103617537700972424661030900303472123028864161050235168613, 65537, 3850457767980968449796700480128630632818465005441846698224554128042451115530564586537997896922067523638756079019054611200173122138274839877369624069360253, 4713180694194659323798858305046043997526301456820208338158979730140812744181638767, 1620238976946735819854194349514460863335347861649166352709029254680140139)
加密字符串:b"\x1aaeps\xa0c}\xb6\xcf\xa3\xb0\xbb\xedA\x7f}\x03\xdc\xd5\x1c\x9b\xdb\xda\xf9q\x80[=\xf5\x91\r\xd0'f\xce\x1f\x01\xef\xa5\xdb3\x96\t0qIxF\xbd\x11\xd6\xb25\xc5\xe1pM\xb4M\xc2\xd4\x03\xa6"
解密字符串:I love Python!
'''
import base64
from Cryptodome.PublicKey import RSA
from Cryptodome.Cipher import PKCS1_v1_5
data = "cKK8B2rWwfwWeXhz"
public_key = "MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAM1xhOWaThSMpfxFsjV5YaWOFHt+6RvS+zH2Pa47VVr8PkZYnRaaKKy2MYBuEh7mZfM/R1dUXTgu0gp6VTNeNQkCAwEAAQ=="
rsa_key = RSA.import_key(base64.b64decode(public_key)) # 导入读取到的公钥
cipher = PKCS1_v1_5.new(rsa_key) # 生成对象
cipher_text = base64.b64encode(cipher.encrypt(data.encode(encoding="utf-8")))
print(cipher_text)
—— 评论区 ——