JAVA和IOS的不同HMAC

时间:2016-12-19 16:25:59

标签: java ios objective-c hmac

我有一个java方法,它根据字符串值和键生成HMAC(散列消息访问代码)。

public String generateHMAC(final String messge,final String key) throws APIGatewayException {

    String result;
    try {

        // get an hmac_sha1 key from the raw key bytes
        final SecretKeySpec signingKey = new SecretKeySpec(key.getBytes(), "HmacSHA256");

        // get an hmac_sha1 Mac instance and initialize with the signing key
        final Mac mac = Mac.getInstance("HmacSHA256");
        mac.init(signingKey);

        // compute the hmac on input data bytes
        final byte[] rawHmac = mac.doFinal(messge.getBytes());

        // base64-encode the hmac
        result = DatatypeConverter.printBase64Binary(rawHmac);

    } catch (Exception e) {
        LOGGER.error(e.getMessage(), e);
        throw new APIGatewayException("Failed to generate HMAC : " + e.getMessage());
    }
    return result;

}

IOS移动开发人员尝试使用相同的字符串和相同的密钥生成HMAC,但获得了不同的hmac。

 (NSString )hashedBase64ValueOfData:(NSString ) data WithSecretKey:(NSString*)secret {
        // ascii convirsion
        const char *cKey  = [secret cStringUsingEncoding:NSASCIIStringEncoding];
        const char *cData = [data cStringUsingEncoding:NSASCIIStringEncoding];

        // HMAC Data structure initializtion
        unsigned char cHMAC[CC_SHA256_DIGEST_LENGTH];
        CCHmac(kCCHmacAlgSHA256, cKey, strlen(cKey), cData, strlen(cData), cHMAC);

        // Gerating hased value
        NSData *da =  [[NSData alloc] initWithBytes:cHMAC length:sizeof(cHMAC)];

        NSString *base64Encoded = [da base64EncodedStringWithOptions:0];// conversion to base64 string & returns

        NSLog(@"third %@",base64Encoded);

        return base64Encoded;

    }

测试数据

Sample String :<roka><header><txn_type>P2P</txn_type><txn_id>11482143820872102</txn_id><response_option>2</response_option><pin_option>2</pin_option><notify_option>2</notify_option><timestamp>1482143820872</timestamp><app_type>App</app_type><bankId>6278</bankId></header><params><payer><roka_id>DDD1150</roka_id><bank>B1</bank><account>B1A1</account><amount>100<amount><value_date /><noisy_status>0</noisy_status></payer><payee><roka_id>DKS1415</roka_id><country>LK</country><bank/><account/></payee></params><IMEINO>AB641CCE-C102-4033-BCF1-707C831717BE</IMEINO><appType>IOS</appType><reqIP>116.75.152.182</reqIP></roka>

Key Used : FmM1WM6FtchBQAE0MnFzUMpos8H/gt9DgGS99bc0gAgVCqgOcAJMmX3Dssr9LK90CSD94cwsw32hGIgI8iwAzQ==

IOS HMAC  : QNlwxdl5kAHSk4oQRez9Y+DYwTwcD5XnsxZR42RDWpU=
Java HMAC : 5PJU/wHzqqvX9xKNPoQlaA4glrO56qr3XENj8HYYpyA=

我无法弄清楚不同的hmac的原因。我希望两个HMAC都一样。

0 个答案:

没有答案