0

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

2 Answers2

1

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
}
zaph
  • 111,848
  • 21
  • 189
  • 228
  • The problem is that i need to use SHA1 in a framework, and since frameworks don't support a bridging header it is not useable. – Wesley De Groot Mar 20 '16 at 10:56
  • [bugreport.apple.com](https://idmsa.apple.com/IDMSWebAuth/login.html?appIdKey=77e2a60d4bdfa6b7311c854a56505800be3c24e3a27a670098ff61b69fc5214b&sslEnabled=true&rv=3). There are solutions house Common Crypto in a Framework, each SO. There is also a Swift implementation of SHA1 on GitHub. It also helps to be more specific in the question. – zaph Mar 20 '16 at 12:19
0

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.