[英]Swift SHA1 function without HMAC
i try to get SHA1 working in swift. 我试图让SHA1快速工作。 without using CommonCrypto since it is not default in swift.
不使用CommonCrypto,因为它不是快速默认值。
please see https://gist.github.com/wdg/f7c8c4088030c59f0f45 (since it's a little to big to post) 请参阅https://gist.github.com/wdg/f7c8c4088030c59f0f45 (因为要发布的内容有点大)
if i run a test case in Xcode: 如果我在Xcode中运行测试用例:
func test_sha1() {
XCTAssertEqual(sha1("test"), "a94a8fe5ccb19ba61c4c0873d391e987982fbbd3")
}
it will fail, and return 2d891cc96e32c32e8d26704d101208b954f435a5
它将失败,并返回
2d891cc96e32c32e8d26704d101208b954f435a5
i got the hash with: 我得到的哈希值:
$ php -r "echo sha1('test');echo(PHP_EOL);"
a94a8fe5ccb19ba61c4c0873d391e987982fbbd3
i think the problem is that in the javascript file they use >>>
and i don't know what this operator is. 我认为问题在于他们在javascript文件中使用
>>>
而我不知道该运算符是什么。 So i have used >>
. 所以我用过
>>
。
i hope someone can help. 我希望有人能帮帮忙。
Thanks in advance 提前致谢
Use Common Crypto for several reasons: 1. It is correct. 使用通用加密有以下几个原因:1.正确。 2. It is FIPS 140-2 certified.
2.已通过FIPS 140-2认证。 3. It is over 1000 times faster than a code based Swift implementation.
3.它比基于代码的Swift实现快1000倍以上。
Note: Common Crypto uses the hardware encryption engine. 注意:Common Crypto使用硬件加密引擎。
Just add a bridging header with the include: 只需添加包含头的桥接头即可:
#import <CommonCrypto/CommonCrypto.h>
Example code for SHA256 (SHA1 should no longer be used): SHA256的示例代码(不应再使用SHA1):
func sha256(dataIn dataIn:NSData) -> NSData {
let digest: NSMutableData! = NSMutableData(length: Int(CC_SHA256_DIGEST_LENGTH));
CC_SHA256(dataIn.bytes, CC_LONG(dataIn.length), UnsafeMutablePointer<UInt8>(digest.mutableBytes));
return digest;
}
or 要么
func sha1(dataIn dataIn:NSData) -> NSData {
let digest: NSMutableData! = NSMutableData(length: Int(CC_SHA1_DIGEST_LENGTH));
CC_SHA1(dataIn.bytes, CC_LONG(dataIn.length), UnsafeMutablePointer<UInt8>(digest.mutableBytes));
return digest;
}
or 要么
func sha1(string string: String) -> [UInt8] {
var digest = [UInt8](count: Int(CC_SHA1_DIGEST_LENGTH), repeatedValue: 0)
if let data = string.dataUsingEncoding(NSUTF8StringEncoding) {
CC_SHA1(data.bytes, CC_LONG(data.length), &digest)
}
return digest
}
I've got a solution, there was something wrong with the rotate function. 我有一个解决方案,旋转功能出了点问题。
i have changed the rotate function to 我将旋转功能更改为
func rotate(n: Int, _ s: Int) -> Int {
return ((n << s) & 0xFFFFFFFF) | (n >> (32 - s))
}
and now it works. 现在可以了。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.