一、SHA1
sha1全称是安全哈希算法(Secure Hash Algorithm)是一种非对称加密算法,其安全性比 MD5更强。对于长度小于 2^{64} 位的消息,SHA1会产生一个160位的消息摘要。主要适用于数字签名标准里边定义的数字签名算法。
1.1、python
import hashlib
sha1 = hashlib.sha1()
sha1.update(data.encode('utf-8'))
sha1_data = sha1.hexdigest()
1.2、java
1.3、C++
1.4、js
二、HMAC
散列消息鉴别码(Hash Message Authentication Code), HMAC 加密算法是一种安全的基于加密 hash 函数和共享密钥的消息认证协议。实现原理是用公开函数和密钥产生一个固定长度的值作为认证标识,用这个标识鉴别消息的完整性。使用一个密钥生成一个固定大小的小数据块,即 MAC,并将其加入到消息中,然后传输。接收方利用与发送方共享的密钥进行鉴别认证等。
2.1、python
import hmac
import hashlib
mac = hmac.new('key', 'message', hashlib.md5)
# 第一个参数是密钥
# 第二个参数是加密内容
# 第三个参数是hash函数
mac.digest() # 字符串的ascii格式
mac.hexdigest # 加密后字符串的十六进制格式
2.2、js
const crypto = require('crypto');
// 创建一个hmac对象
const hmac = crypto.createHmac('md5', 'abc');
// 往hmac对象中添加摘要内容
const up = hmac.update('123456');
// 使用 digest 方法输出摘要内容
const result = up.digest('hex');
console.log(result); // 8c7498982f41b93eb0ce8216b48ba21d
三、MD5
MD5消息摘要算法(英语:MD5 Message-Digest Algorithm),一种被广泛使用的密码散列函数,可以产生出一个128位(16字节)的散列值(hash value),用于确保信息传输完整一致。md5加密算法是不可逆的,所以解密一般都是通过暴力穷举方法,通过网站的接口实现解密。
3.1、python
import hashlib
m = hashlib.md5()
m.update(data.encode('utf-8'))
res = sha1.hexdigest()
3.2 javescript
const crypto = require('crypto');
const str = 'abc';
// 创建一个hash对象
const md5 = crypto.createHash('md5');
// 往hash对象中添加摘要内容
md5.update(str);
// 使用 digest 方法输出摘要内容,不使用编码格式的参数 其输出的是一个Buffer对象
// console.log(md5.digest());
// 输出 <Buffer 90 01 50 98 3c d2 4f b0 d6 96 3f 7d 28 e1 7f 72>
// 使用编码格式的参数,输出的是一个字符串格式的摘要内容
console.log(md5.digest('hex')); // 输出 900150983cd24fb0d6963f7d28e17f72
四、AES
高级加密标准(英语:Advanced Encryption Standard),在密码学中又称 Rijndael 加密法,是美国联邦政府采用的一种区块加密标准。这个标准用来替代原先的 DES,已经被多方分析且广为全世界所使用。
4.1、python
import base64
from Crypto.Clipher import AES
def add_to_16(value):
while len(value)%16!=0:
value +='\0'
return str.encode(value)
# 加密过程
def encrypt(key, text):
aes = AES.new(add_to_16(key), AES.MODE_ECB)
encrypt_aes = aes.encrypt(add_to_16(text))
encrypt_text = str(base64.encodebytes(enctypt_aes), encoding='utf-8')
return encrypt_text
def decrypt(key, text):
aes = AES.new(add_to_16(key), AES.MODE_ECB)
base64_decrypted = base64.decodebytes(text.encode(encoding='utf-8'))
decrypted_text = str(aes.decrypt(base64_decrypted), encoding='utf-8').replace('\0', '')
return decrypted_text
五、RSA
Rivest-Shamir-Adleman,RSA 加密算法是一种非对称加密算法。在公开密钥加密和电子商业中 RSA 被广泛使用。它被普遍认为是目前最优秀的公钥方案之一。RSA 是第一个能同时用于加密和数字签名的算法,它能够抵抗到目前为止已知的所有密码攻击。
5.1、python
ras 库
import base64
import rsa
from rsa import common
# 使用 rsa库进行RSA签名和加解密
class RsaUtil(object):
PUBLIC_KEY_PATH = '/Users/anonyper/Desktop/key/company_rsa_public_key.pem' # 公钥
PRIVATE_KEY_PATH = '/Users/anonyper/Desktop/key/company_rsa_private_key.pem' # 私钥
# 初始化key
def __init__(self,
company_pub_file=PUBLIC_KEY_PATH,
company_pri_file=PRIVATE_KEY_PATH):
if company_pub_file:
self.company_public_key = rsa.PublicKey.load_pkcs1_openssl_pem(open(company_pub_file).read())
if company_pri_file:
self.company_private_key = rsa.PrivateKey.load_pkcs1(open(company_pri_file).read())
def get_max_length(self, rsa_key, encrypt=True):
"""加密内容过长时 需要分段加密 换算每一段的长度.
:param rsa_key: 钥匙.
:param encrypt: 是否是加密.
"""
blocksize = common.byte_size(rsa_key.n)
reserve_size = 11 # 预留位为11
if not encrypt: # 解密时不需要考虑预留位
reserve_size = 0
maxlength = blocksize - reserve_size
return maxlength
# 加密 支付方公钥
def encrypt_by_public_key(self, message):
"""使用公钥加密.
:param message: 需要加密的内容.
加密之后需要对接过进行base64转码
"""
encrypt_result = b''
max_length = self.get_max_length(self.company_public_key)
while message:
input = message[:max_length]
message = message[max_length:]
out = rsa.encrypt(input, self.company_public_key)
encrypt_result += out
encrypt_result = base64.b64encode(encrypt_result)
return encrypt_result
def decrypt_by_private_key(self, message):
"""使用私钥解密.
:param message: 需要加密的内容.
解密之后的内容直接是字符串,不需要在进行转义
"""
decrypt_result = b""
max_length = self.get_max_length(self.company_private_key, False)
decrypt_message = base64.b64decode(message)
while decrypt_message:
input = decrypt_message[:max_length]
decrypt_message = decrypt_message[max_length:]
out = rsa.decrypt(input, self.company_private_key)
decrypt_result += out
return decrypt_result
# 签名 商户私钥 base64转码
def sign_by_private_key(self, data):
"""私钥签名.
:param data: 需要签名的内容.
使用SHA-1 方法进行签名(也可以使用MD5)
签名之后,需要转义后输出
"""
signature = rsa.sign(str(data), priv_key=self.company_private_key, hash='SHA-1')
return base64.b64encode(signature)
def verify_by_public_key(self, message, signature):
"""公钥验签.
:param message: 验签的内容.
:param signature: 对验签内容签名的值(签名之后,会进行b64encode转码,所以验签前也需转码).
"""
signature = base64.b64decode(signature)
return rsa.verify(message, signature, self.company_public_key)
message = 'hell world'
print("明文内容:>>> ")
print(message)
rsaUtil = RsaUtil()
encrypy_result = rsaUtil.encrypt_by_public_key(message)
print("加密结果:>>> ")
print(encrypy_result)
decrypt_result = rsaUtil.decrypt_by_private_key(encrypy_result)
print("解密结果:>>> ")
print(decrypt_result)
sign = rsaUtil.sign_by_private_key(message)
print("签名结果:>>> ")
print(sign)
print("验签结果:>>> ")
print(rsaUtil.verify_by_public_key(message, sign))
#执行结果
明文内容:>>>
hell world
加密结果:>>>
sWx9r30CCLXip0iemCb2r1gsZIedgLp1Vmk9uCDaQttcQNftwQyI98shN2Hpn7snE27ziJnH6qYmaf68TWBerhJVGEzr16wLYInVft0Bj0+kcCmLL7tMJRZWydqHi/YzgIfsFEvqLOUFv6E9bCAXhJkikacBAG4FWTMBrXUQHjE=
解密结果:>>>
hell world
签名结果:>>>
GS3MPpb4zMLIL7mqcxZEevOoH1Fse9fjHefWIUpDaMplhoPUNK85TreYmOwvF8QJNxgLcJoKKfRm51gemsQd1/e1FBPo/4VS3kvneJyLUtQAPdOOl+R4h//0gFec+ELI+KS8A74Dkm2bFKztZ4BxIcWD63pHRiGAnS8+cQeq2QM=
验签结果:>>>
True
Crypto
import base64
from Crypto.Cipher import PKCS1_v1_5 as PKCS1_v1_5_cipper
from Crypto.Signature import PKCS1_v1_5
from Crypto.PublicKey import RSA
from Crypto.Hash import SHA
import Crypto
# 使用 rsa库进行RSA签名和加解密
class RsaUtil(object):
PUBLIC_KEY_PATH = '/Users/anonyper/Desktop/key/company_rsa_public_key.pem' # 公钥
PRIVATE_KEY_PATH = '/Users/anonyper/Desktop/key/company_rsa_private_key.pem' # 私钥
# 初始化key
def __init__(self,
company_pub_file=PUBLIC_KEY_PATH,
company_pri_file=PRIVATE_KEY_PATH):
if company_pub_file:
self.company_public_key = RSA.importKey(open(company_pub_file).read())
if company_pri_file:
self.company_private_key = RSA.importKey(open(company_pri_file).read())
def get_max_length(self, rsa_key, encrypt=True):
"""加密内容过长时 需要分段加密 换算每一段的长度.
:param rsa_key: 钥匙.
:param encrypt: 是否是加密.
"""
blocksize = Crypto.Util.number.size(rsa_key.n) / 8
reserve_size = 11 # 预留位为11
if not encrypt: # 解密时不需要考虑预留位
reserve_size = 0
maxlength = blocksize - reserve_size
return maxlength
# 加密 支付方公钥
def encrypt_by_public_key(self, encrypt_message):
"""使用公钥加密.
:param encrypt_message: 需要加密的内容.
加密之后需要对接过进行base64转码
"""
encrypt_result = b''
max_length = self.get_max_length(self.company_public_key)
cipher = PKCS1_v1_5_cipper.new(self.company_public_key)
while encrypt_message:
input_data = encrypt_message[:max_length]
encrypt_message = encrypt_message[max_length:]
out_data = cipher.encrypt(input_data)
encrypt_result += out_data
encrypt_result = base64.b64encode(encrypt_result)
return encrypt_result
# 加密 支付方私钥
def encrypt_by_private_key(self, encrypt_message):
"""使用私钥加密.
:param encrypt_message: 需要加密的内容.
加密之后需要对接过进行base64转码
"""
encrypt_result = b''
max_length = self.get_max_length(self.company_private_key)
cipher = PKCS1_v1_5_cipper.new(self.company_public_key)
while encrypt_message:
input_data = encrypt_message[:max_length]
encrypt_message = encrypt_message[max_length:]
out_data = cipher.encrypt(input_data)
encrypt_result += out_data
encrypt_result = base64.b64encode(encrypt_result)
return encrypt_result
def decrypt_by_public_key(self, decrypt_message):
"""使用公钥解密.
:param decrypt_message: 需要解密的内容.
解密之后的内容直接是字符串,不需要在进行转义
"""
decrypt_result = b""
max_length = self.get_max_length(self.company_public_key, False)
decrypt_message = base64.b64decode(decrypt_message)
cipher = PKCS1_v1_5_cipper.new(self.company_public_key)
while decrypt_message:
input_data = decrypt_message[:max_length]
decrypt_message = decrypt_message[max_length:]
out_data = cipher.decrypt(input_data, '')
decrypt_result += out_data
return decrypt_result
def decrypt_by_private_key(self, decrypt_message):
"""使用私钥解密.
:param decrypt_message: 需要解密的内容.
解密之后的内容直接是字符串,不需要在进行转义
"""
decrypt_result = b""
max_length = self.get_max_length(self.company_private_key, False)
decrypt_message = base64.b64decode(decrypt_message)
cipher = PKCS1_v1_5_cipper.new(self.company_private_key)
while decrypt_message:
input_data = decrypt_message[:max_length]
decrypt_message = decrypt_message[max_length:]
out_data = cipher.decrypt(input_data, '')
decrypt_result += out_data
return decrypt_result
# 签名 商户私钥 base64转码
def sign_by_private_key(self, message):
"""私钥签名.
:param message: 需要签名的内容.
签名之后,需要转义后输出
"""
cipher = PKCS1_v1_5.new(self.company_private_key) # 用公钥签名,会报错 raise TypeError("No private key") 如下
# if not self.has_private():
# raise TypeError("No private key")
hs = SHA.new(message)
signature = cipher.sign(hs)
return base64.b64encode(signature)
def verify_by_public_key(self, message, signature):
"""公钥验签.
:param message: 验签的内容.
:param signature: 对验签内容签名的值(签名之后,会进行b64encode转码,所以验签前也需转码).
"""
signature = base64.b64decode(signature)
cipher = PKCS1_v1_5.new(self.company_public_key)
hs = SHA.new(message)
# digest = hashlib.sha1(message).digest() # 内容摘要的生成方法有很多种,只要签名和解签用的是一样的就可以
return cipher.verify(hs, signature)
message = 'hell worldhell worldhell worldhell worldhell worldhell worldhell worldhell worldhell worldhell worldhell worldhell worldhell worldhell worldhell worldhell worldhell worldhell worldhell world'
print("明文内容:>>> ")
print(message)
rsaUtil = RsaUtil()
encrypy_result = rsaUtil.encrypt_by_public_key(message)
print("加密结果:>>> ")
print(encrypy_result)
decrypt_result = rsaUtil.decrypt_by_private_key(encrypy_result)
print("解密结果:>>> ")
print(decrypt_result)
sign = rsaUtil.sign_by_private_key(message)
print("签名结果:>>> ")
print(sign)
print("验签结果:>>> ")
print(rsaUtil.verify_by_public_key(message, sign))
#执行结果:
明文内容:>>>
hell worldhell worldhell worldhell worldhell worldhell worldhell worldhell worldhell worldhell worldhell worldhell worldhell worldhell worldhell worldhell worldhell worldhell worldhell world
加密结果:>>>
PC8/knkmszKby2pHtlKJa/Uv7EADImNhrFwZQK3YHpwPwDpt5A4bFTxsDu2o8U0yc+X50+M3Bi53C0sOHjiOCStG/Bp1nfowHQBgUFCETp4G3fpLAl7eWynqqu6gInjHQeNMbBz1wvRhSiXoMB2lJm8b9fLuzDuQQRFZPqD356kgTKnBM+lju4HE4zMjAT8jMam5Z4EnmaRfX7kYDGzga+PgbkkGon354i3CRhuRWtpvQeXnmjZq8MpfDC6//L7I/vvw4/LMJhiQJkXUbGEgSok8yg6jZzGx+bllc+qn7DH5nkNZKkOnqaeJHbEktgdhua/QXJcRR/5Lm0Y8ovs54A==
解密结果:>>>
hell worldhell worldhell worldhell worldhell worldhell worldhell worldhell worldhell worldhell worldhell worldhell worldhell worldhell worldhell worldhell worldhell worldhell worldhell world
签名结果:>>>
VinHhT+iJfDvIgseJ0ZsmJcLk+yDdx0323B6vMKMUHDlUF2HDWqQhEEoqmSstjsSfR/T+4829t5DhtaJ5w1O7K7ZyP/+yu/lupc8apmfYSIziozi3vPy20p/CYNaXAy0LLGOwrtVNn3jTaq7Gb0yI4/Zhin2jNmTk09g8Qx9rGI=
验签结果:>>>
True
M2Crypto
import base64
import M2Crypto
from M2Crypto import EVP
# 使用 M2Crypto库进行RSA签名和加解密
class RsaUtil(object):
PUBLIC_KEY_PATH = '/Users/anonyper/Desktop/key/company_rsa_public_key.pem' # 公钥
PRIVATE_KEY_PATH = '/Users/anonyper/Desktop/key/company_rsa_private_key.pem' # 私钥
# 初始化key
def __init__(self,
company_pub_file=PUBLIC_KEY_PATH,
company_pri_file=PRIVATE_KEY_PATH):
if company_pub_file:
self.company_public_key = M2Crypto.RSA.load_pub_key(company_pub_file)
if company_pri_file:
self.company_private_key = M2Crypto.RSA.load_key(company_pri_file)
def get_max_length(self, rsa_key, encrypt=True):
"""加密内容过长时 需要分段加密 换算每一段的长度.
:param rsa_key: 钥匙.
:param encrypt: 是否是加密.
"""
blocksize = rsa_key.__len__() / 8
reserve_size = 11 #
if not encrypt:
reserve_size = 0
maxlength = blocksize - reserve_size
return maxlength
# 加密 支付方公钥
def encrypt_by_public_key(self, encrypt_message):
"""使用公钥加密.
:param encrypt_message: 需要加密的内容.
加密之后需要对接过进行base64转码
"""
encrypt_result = b''
max_length = self.get_max_length(self.company_public_key)
print(max_length)
while encrypt_message:
input_data = encrypt_message[:max_length]
encrypt_message = encrypt_message[max_length:]
out_data = self.company_public_key.public_encrypt(input_data, M2Crypto.RSA.pkcs1_padding)
encrypt_result += out_data
encrypt_result = base64.b64encode(encrypt_result)
return encrypt_result
# 加密 支付方私钥
def encrypt_by_private_key(self, encrypt_message):
"""使用私钥加密.
:param encrypt_message: 需要加密的内容.
加密之后需要对接过进行base64转码
"""
encrypt_result = b''
max_length = self.get_max_length(self.company_private_key)
while encrypt_message:
input_data = encrypt_message[:max_length]
encrypt_message = encrypt_message[max_length:]
out_data = self.company_private_key.private_encrypt(input_data, M2Crypto.RSA.pkcs1_padding)
encrypt_result += out_data
encrypt_result = base64.b64encode(encrypt_result)
return encrypt_result
def decrypt_by_public_key(self, decrypt_message):
"""使用公钥解密.
:param decrypt_message: 需要解密的内容.
解密之后的内容直接是字符串,不需要在进行转义
"""
decrypt_result = b""
max_length = self.get_max_length(self.company_private_key, False)
decrypt_message = base64.b64decode(decrypt_message)
while decrypt_message:
input_data = decrypt_message[:max_length]
decrypt_message = decrypt_message[max_length:]
out_data = self.company_public_key.public_encrypt(input_data, M2Crypto.RSA.pkcs1_padding)
decrypt_result += out_data
return decrypt_result
def decrypt_by_private_key(self, decrypt_message):
"""使用私钥解密.
:param decrypt_message: 需要解密的内容.
解密之后的内容直接是字符串,不需要在进行转义
"""
decrypt_result = b""
max_length = self.get_max_length(self.company_private_key, False)
decrypt_message = base64.b64decode(decrypt_message)
while decrypt_message:
input_data = decrypt_message[:max_length]
decrypt_message = decrypt_message[max_length:]
out_data = self.company_private_key.private_decrypt(input_data, M2Crypto.RSA.pkcs1_padding)
decrypt_result += out_data
return decrypt_result
# 签名 商户私钥 base64转码
def sign_by_private_key(self, message):
"""私钥签名.
:param message: 需要签名的内容.
签名之后,需要转义后输出
"""
hs = EVP.MessageDigest('sha1')
hs.update(message)
digest = hs.final()
# digest = hashlib.sha1(message).digest() # 内容摘要的生成方法有很多种,只要签名和解签用的是一样的就可以
signature = self.company_private_key.sign(digest)
# self.company_public_key.sign(digest) # 用公钥签名IDE会崩
return base64.b64encode(signature)
def verify_by_public_key(self, message, signature):
"""公钥验签.
:param message: 验签的内容.
:param signature: 对验签内容签名的值(签名之后,会进行b64encode转码,所以验签前也需转码).
"""
hs = EVP.MessageDigest('sha1')
hs.update(message)
digest = hs.final()
# digest = hashlib.sha1(message).digest() # 内容摘要的生成方法有很多种,只要签名和解签用的是一样的就可以
signature = base64.b64decode(signature)
return self.company_public_key.verify(digest, signature)
message = 'hell worldhell worldhell worldhell worldhell worldhell worldhell worldhell worldhell worldhell worldhell worldhell worldhell worldhell worldhell worldhell worldhell worldhell worldhell world'
print("明文内容:>>> ")
print(message)
rsaUtil = RsaUtil()
encrypy_result = rsaUtil.encrypt_by_public_key(message)
print("加密结果:>>> ")
print(encrypy_result)
decrypt_result = rsaUtil.decrypt_by_private_key(encrypy_result)
print("解密结果:>>> ")
print(decrypt_result)
sign = rsaUtil.sign_by_private_key(message)
print("签名结果:>>> ")
print(sign)
print("验签结果:>>> ")
print(rsaUtil.verify_by_public_key(message, sign))
#执行结果
明文内容:>>>
hell worldhell worldhell worldhell worldhell worldhell worldhell worldhell worldhell worldhell worldhell worldhell worldhell worldhell worldhell worldhell worldhell worldhell worldhell world
加密结果:>>>
fu4RgyOaokEcLmA5k0otMirZoiFBDBkEgycgehEajtPU+xP7Wf5rN05kwbsDNI7/kUR5wOvS0XE8jD1nYmKv4uBWfR5Z28BHdK20uue/8zTnPgdsAmRdzA6Lb2EIk/g38o2EtRZ4jILNOdikpW0kYpYRdaJgoHTWTOlE/RL9zcVKzYELFPpWui2jZ8EVMe+6ZiPkRKCKL571f/OTb1qOdg4GTiowZCNMIknTxXawvZl9Funz7TNz0WsNDejL+r3tM8erwhE0ygIMtemOiVy8yBVsHpHPzfdlNRoXXgtgupFEgVgEOODUp9y4LzX6UDf0+i8uI7/SpyQoa9jSpcsIjA==
解密结果:>>>
hell worldhell worldhell worldhell worldhell worldhell worldhell worldhell worldhell worldhell worldhell worldhell worldhell worldhell worldhell worldhell worldhell worldhell worldhell world
签名结果:>>>
VinHhT+iJfDvIgseJ0ZsmJcLk+yDdx0323B6vMKMUHDlUF2HDWqQhEEoqmSstjsSfR/T+4829t5DhtaJ5w1O7K7ZyP/+yu/lupc8apmfYSIziozi3vPy20p/CYNaXAy0LLGOwrtVNn3jTaq7Gb0yI4/Zhin2jNmTk09g8Qx9rGI=
验签结果:>>>
1