I want to create connections with banks and as I see in the documentation of cardlink they want to calculate digest.
The main idea of this calculation is this
Digest=base64( sha-1( utf8bytes(value1|value2|...|secret) ) )
.
MessageDigestmdigest = MessageDigest.getInstance("SHA-1");
byte[] digestResult =digest.digest(concatString.getBytes("UTF-8"));
String calculatedDigest = Base64.encode(digestResult);
This is the code they have for java.
I started for testing this manually but I stucked with the convertion of bytes.
this is the finall step for base64
So my main question is how can I do the conversion to bytes and if It would help a lot if someone knows a way to do it with swift (ios).
Thanks in advance
EDIT
This is the example string I got:
2.045020311114033331503343429780020454510MDAwMDAwMDAwMDAwMDA2ODkzOTI=https://myeshop.gr/orders/Payment_Okhttps://myeshop.gr/orders/Payment_FailEURO123
And this is the result I want:
wXRSbgCX2Kq6gSOVE6+c9VpvSRQ=
Is this what you need?
import UIKit
extension String {
func sha1() -> String {
let data = self.dataUsingEncoding(NSUTF8StringEncoding)!
var digest = [UInt8](count:Int(CC_SHA1_DIGEST_LENGTH), repeatedValue: 0)
CC_SHA1(data.bytes, CC_LONG(data.length), &digest)
let hexBytes = digest.map { String(format: "%02hhx", $0) }
return hexBytes.joinWithSeparator("")
}
func sha1Data() -> NSData {
let data = self.dataUsingEncoding(NSUTF8StringEncoding)!
var digest = [UInt8](count:Int(CC_SHA1_DIGEST_LENGTH), repeatedValue: 0)
CC_SHA1(data.bytes, CC_LONG(data.length), &digest)
let digestData = NSData(bytes: digest, length: digest.count)
return digestData
}
}
class TestSHA1Digest: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
if let b64 = calculateDigest("2.045020311114033331503343429780020454510MDAwMDAwMDAwMDAwMDA2ODkzOTI=https://myeshop.gr/orders/Payment_Okhttps://myeshop.gr/orders/Payment_FailEURO123") {
print("SHA1: \(b64)")
} else {
print("Calcuate SHA1 failed")
}
}
func calculateDigest(data: String) -> String? {
let shaData = data.sha1Data()
return shaData.base64EncodedStringWithOptions(NSDataBase64EncodingOptions(rawValue: 0))
}
}
[Output] SHA1: wXRSbgCX2Kq6gSOVE6+c9VpvSRQ=
PS. I am using swift 2 + Xcode 7.3.1. Please let me know if you are using swift 3.