[英]Base64 encoding of CryptoDigest / SHA1 - string doesn't match the result from Java / Python
I'm trying to get message digest of a string on IOS. 我正在尝试获取IOS上字符串的消息摘要。 I have tried nv-ios-digest 3rd party Hash lib but still no use. 我已经尝试过nv-ios-digest 3rd Hash lib,但是还是没用。
Below is the function i'm using to get the base64encoded string of a message digest. 下面是我用来获取消息摘要的base64encoded字符串的函数。
-(NSString*) sha1:(NSString*)input //sha1- Digest
{
NSData *data = [input dataUsingEncoding:NSUTF8StringEncoding];
uint8_t digest[CC_SHA1_DIGEST_LENGTH];
CC_SHA1(data.bytes, data.length, digest);
NSMutableString* output = [NSMutableString stringWithCapacity:CC_SHA1_DIGEST_LENGTH * 2];
for(int i = 0; i < CC_SHA1_DIGEST_LENGTH; i++){
[output appendFormat:@"%02x", digest[i]];//digest
}
return [NSString stringWithFormat:@"%@",[[[output description] dataUsingEncoding:NSUTF8StringEncoding]base64EncodedStringWithOptions:0]]; //base64 encoded
}
Here is my sample input string - '530279591878676249714013992002683ec3a85216db22238a12fcf11a07606ecbfb57b5' 这是我的示例输入字符串-'530279591878676249714013992002683ec3a85216db22238a12fcf11a07606ecbfb57b5'
When I use this string either in java or python I get same result - '5VNqZRB1JiRUieUj0DufgeUbuHQ=' 当我在Java或python中使用此字符串时,我得到相同的结果-'5VNqZRB1JiRUieUj0DufgeUbuHQ ='
But in IOS I get 'ZTU1MzZhNjUxMDc1MjYyNDU0ODllNTIzZDAzYjlmODFlNTFiYjg3NA==' 但是在IOS中,我得到了'ZTU1MzZhNjUxMDc1MjYyNDU0ODllNTIzZDAzYjlmODFlNTFiYjg3NA =='
Here is the code I'm using in python: 这是我在python中使用的代码:
import hashlib
import base64
def checkForDigestKey(somestring):
msgDigest = hashlib.sha1()
msgDigest.update(somestring)
print base64.b64encode(msgDigest.digest())
Let me know if there is anyway to get the same result for IOS. 让我知道IOS是否可以获得相同的结果。
You are producing a binary digest in Python, a hexadecimal digest in iOS. 您正在Python中生成二进制摘要,而在iOS中则是十六进制摘要。
The digests are otherwise equal: 否则摘要是相等的:
>>> # iOS-produced base64 value
...
>>> 'ZTU1MzZhNjUxMDc1MjYyNDU0ODllNTIzZDAzYjlmODFlNTFiYjg3NA=='.decode('base64')
'e5536a65107526245489e523d03b9f81e51bb874'
>>> # Python-produced base64 value
...
>>> '5VNqZRB1JiRUieUj0DufgeUbuHQ='.decode('base64')
'\xe5Sje\x10u&$T\x89\xe5#\xd0;\x9f\x81\xe5\x1b\xb8t'
>>> from binascii import hexlify
>>> # Python-produced value converted to a hex representation
...
>>> hexlify('5VNqZRB1JiRUieUj0DufgeUbuHQ='.decode('base64'))
'e5536a65107526245489e523d03b9f81e51bb874'
Use base64.b64encode(msgDigest.hexdigest())
in Python to produce the same value, or Base-64 encode the digest
bytes instead of hexadecimal characters in iOS. 在Python中使用base64.b64encode(msgDigest.hexdigest())
产生相同的值,或者在iOS中使用Base-64编码digest
字节而不是十六进制字符。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.