简体   繁体   中英

Swift SHA1 function without HMAC

i try to get SHA1 working in swift. without using CommonCrypto since it is not default in swift.

please see https://gist.github.com/wdg/f7c8c4088030c59f0f45 (since it's a little to big to post)

if i run a test case in Xcode:

func test_sha1() {
    XCTAssertEqual(sha1("test"), "a94a8fe5ccb19ba61c4c0873d391e987982fbbd3")
}

it will fail, and return 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. So i have used >> .

i hope someone can help.

Thanks in advance

Use Common Crypto for several reasons: 1. It is correct. 2. It is FIPS 140-2 certified. 3. It is over 1000 times faster than a code based Swift implementation.

Note: Common Crypto uses the hardware encryption engine.

Just add a bridging header with the include:

#import <CommonCrypto/CommonCrypto.h>

Example code for SHA256 (SHA1 should no longer be used):

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM