https://kotlinlang.org logo
j

Jeff Tycz

02/22/2021, 3:45 AM
I am trying to convert this bit of code into kotlin
Copy code
- (NSString *)hmacsha1:(NSString *)data secret:(NSString *)key {

    const char *cKey  = [key cStringUsingEncoding:NSASCIIStringEncoding];
    const char *cData = [data cStringUsingEncoding:NSASCIIStringEncoding];

    unsigned char cHMAC[CC_SHA1_DIGEST_LENGTH];

    CCHmac(kCCHmacAlgSHA1, cKey, strlen(cKey), cData, strlen(cData), cHMAC);

    NSData *HMAC = [[NSData alloc] initWithBytes:cHMAC length:sizeof(cHMAC)];

    NSString *hash = [HMAC base64String];

    return hash;
}
This is currently what I have
Copy code
actual fun generateHmacSha1Signature(key: String, value: String): String = memScoped{
    val nsKey = NSString.create(string = key)
    val nsValue = NSString.create(string = value)
    val encodedKey = nsKey.cStringUsingEncoding(NSUTF16StringEncoding)
    val encodedValue = nsValue.cStringUsingEncoding(NSUTF16StringEncoding)

    val cHMAC = ByteArray(CC_SHA1_DIGEST_LENGTH)

    CCHmac(kCCHmacAlgSHA1, encodedKey, strlen(encodedKey?.toKString()), encodedValue, strlen(encodedValue?.toKString()), cHMAC.asUByteArray().toCValues())

    val data:NSData = NSData.create(bytes = allocArrayOf(cHMAC), length = cHMAC.size.toULong())

    return data.base64EncodedStringWithOptions(NSDataBase64DecodingIgnoreUnknownCharacters)
}
The problem with what I have though is that it does not seem to be generating a correct SHA1 signature. I get
AAAAAAAAAAAAAAAAAAAAAAAAAAA=
as a value when I use it. The part that don't think is correct is the
CCHmac
because I was not sure if I was getting the string length correctly and the
cHMAC
ByteArray correctly. Can anyone tell me where I went wrong?
t

tylerwilson

02/22/2021, 1:44 PM
Hi, I can’t debug your code, but if it helps, I have a method that does this that has been working for quite some time. Perhaps that will help?
j

Jeff Tycz

02/23/2021, 12:07 AM
Awesome I will give it a try thanks
31 Views