参考链接:Get SSL certificate details
最近在做SSL证书加密,因为证书有有效期,因此需要考虑证书过期前的更新机制:用sha1值是否变更,来判断服务端的SSL证书是否已更新。
首先,将.cer证书转成NSData类型。
获取sha1值方法:
+(NSString*)sha1:(NSData*)certData {
unsigned char sha1Buffer[CC_SHA1_DIGEST_LENGTH];
CC_SHA1(certData.bytes, certData.length, sha1Buffer);
NSMutableString *fingerprint = [NSMutableString stringWithCapacity:CC_SHA1_DIGEST_LENGTH * 3];
for (int i = 0; i < CC_SHA1_DIGEST_LENGTH; ++i)
[fingerprint appendFormat:@"%02x ",sha1Buffer[i]];
return [fingerprint stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
}
获取sha256值方法:
+(NSString*)sha256:(NSData*)certData {
unsigned char sha256Buffer[CC_SHA256_DIGEST_LENGTH];
CC_SHA256(certData.bytes, certData.length, sha256Buffer);
NSMutableString *fingerprint = [NSMutableString stringWithCapacity:CC_SHA256_DIGEST_LENGTH * 3];
for (int i = 0; i < CC_SHA256_DIGEST_LENGTH; ++i)
[fingerprint appendFormat:@"%02x ",sha256Buffer[i]];
return [fingerprint stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
}