背景:
有个java生成token的实例想转python实现 token=base64(sha1(sha1('加密字符串')))
假设我们现在要加密的字符串是: APP000051527151133935949D49FDC0A86605313931B9BB9A4C87
java加密后为: mzHy6rfyM/R4gRLFDFqbzq+ypvU=
刚开始我的实现如下:
#!/usr/bin/python
# -*- coding: UTF-8 -*-
__author__ = 'huangbinghe@gmail.com'
import hashlib
import base64
s0 = 'APP000051527151133935949D49FDC0A86605313931B9BB9A4C87'
s1 = hashlib.sha1(bytes(s0, encoding='utf-8')).hexdigest()
print('s1:', s1)
s2 = hashlib.sha1(bytes(s1, encoding='utf-8')).hexdigest()
print('s2:', s2)
s3 = base64.b64encode(bytes(s2, encoding='utf-8')).decode('utf-8')
print('s3:', s3)
输出结果:
s1: 8401e33da06a147f15debf95a2a747e65e939c9a
s2: 9b50db1e5ed13fc22f5e864d5f32a4ee99f9f42f
s3: OWI1MGRiMWU1ZWQxM2ZjMjJmNWU4NjRkNWYzMmE0ZWU5OWY5ZjQyZg==
对比一下不对呀,哪里出错了呢? 我是phper,所以php也来验证一下
php代码:
$str = 'APP000051525682707629949D49FDC0A86605313931B9BB9A4C87';
$r = base64_encode(sha1(sha1($str)));
echo $r;
string(56) "MDg0ZmI3ZGQyYzU0ODMxMTdiYjczZmE3MDNhMzcyYmIzZGM4NmU1Mw=="
php与python执行结果一致,这个时候有点懵了,难道java比较特殊,后来查看了java源码
public static byte[] encryptSHA1(byte[] data)
throws NoSuchAlgorithmException
{
MessageDigest sha = MessageDigest.getInstance("SHA1");
sha.update(data);
return sha.digest();
}
public static String base64_encode(String str)
{
return new BASE64Encoder().encode(str.getBytes());
}
public static String base64_encode(byte[] b)
{
return new BASE64Encoder().encode(b);
}
发现了sha1加密后返回的是sha.digest(),于是百度了一下python里的digest与hexdigest区别,找到了一篇文章:
python3中digest()和hexdigest()区别
于是将python中的hexdigest改为digest后成功实现与java加密一致了,有点小激动,这个问题搞了好几天了
最后实现代码如下:
#!/usr/bin/python
# -*- coding: UTF-8 -*-
__author__ = 'huangbinghe@gmail.com'
import hashlib
import base64
s0 = 'APP000051527151133935949D49FDC0A86605313931B9BB9A4C87'
s1 = hashlib.sha1(bytes(s0, encoding='utf-8')).digest()
print('s1:', s1)
s2 = hashlib.sha1(s1).digest()
print('s2:', s2)
s3 = base64.b64encode(s2).decode('utf-8')
print('s3:', s3)
执行结果:
s1: b'\x84\x01\xe3=\xa0j\x14\x7f\x15\xde\xbf\x95\xa2\xa7G\xe6^\x93\x9c\x9a'
s2: b'\x9b1\xf2\xea\xb7\xf23\xf4x\x81\x12\xc5\x0cZ\x9b\xce\xaf\xb2\xa6\xf5'
s3: mzHy6rfyM/R4gRLFDFqbzq+ypvU=