3 posts / 0 new
Last post
priteshpatel3067
HMAC & Authorization Generation in Android App

Hi

We are trying to integrate Payezzy into our android and iOS app, we are confused here, about generating an HMAC. I have all the KEY's which will be used for sandbox testing, however, i dont know how can get Authorization & HMAC ????

I tried looking into your existing Android app, but still no luck.. Any help regarding the same will be really great.

Thank You


nileshdafeniles...
Re: HMAC & Authorization Generation in Android App

Following is the code for HMac generation for android. The HMAC generation is taken care of by the android SDK and SDK user need not worry about HMAC generation. The authorization is the token used for the transactions.

 public String getMacValue(Map<String,String> data) throws Exception{
        Mac mac=Mac.getInstance("HmacSHA256");
        String apiSecret= data.get(APISECRET);
        MessageLogger.logMessage(String.format("API_SECRET:{}",apiSecret));
        SecretKeySpec secret_key = new SecretKeySpec(apiSecret.getBytes(), "HmacSHA256");
        mac.init(secret_key);
        StringBuilder buff=new StringBuilder();
        buff.append(data.get(APIKEY))
        .append(data.get(NONCE))
        .append(data.get(TIMESTAMP));
        if(data.get(TOKEN)!=null)
            buff.append(data.get(TOKEN));
        if(data.get(PAYLOAD)!=null)
            buff.append(data.get(PAYLOAD));
        String bufferData = buff.toString();
        MessageLogger.logMessage(String.format(bufferData));
        byte[] macHash=mac.doFinal(bufferData.getBytes("UTF-8"));
        MessageLogger.logMessage(Integer.toString(macHash.length));
        MessageLogger.logMessage(String.format("MacHAsh:{}",Arrays.toString( macHash)));
        
        String authorizeString=android.util.Base64.encodeToString(toHex(macHash), android.util.Base64.NO_WRAP);
        
        MessageLogger.logMessage(String.format("Authorize: {}",authorizeString));
        return authorizeString;
}

 

Thanks and Regards,

Nilesh Dafe 


atulparmar983
Re: HMAC & Authorization Generation in Android App

Hello Pritesh Patel: For HMAC generation: 

#import <CommonCrypto/CommonDigest.h>

#import <CommonCrypto/CommonCryptor.h>
#import <CommonCrypto/CommonHMAC.h>
#import <Security/SecRandom.h>
#import "SBJson4Writer.h"
#import <netinet/in.h>
#import <netinet6/in6.h>
#import <SystemConfiguration/SystemConfiguration.h>

/*********************************************************************************************
 Security and Authentication
 Methods: secureRandomNumber, getEpochTimeStamp for HMAC
 *******************************************************************************************/

-(NSString *)getEpochTimeStamp
{
    NSString *timeStamp = [NSString stringWithFormat:@"%.0f",round([[NSDate date]timeIntervalSince1970]*1000)];
    return timeStamp;
}

- (NSString *)secureRandomNumber
{
    unsigned int randomNumber;
    
    NSMutableData *data = [NSMutableData dataWithLength:kCCKeySizeAES256];
    
    SecRandomCopyBytes(kSecRandomDefault, [data length], data.mutableBytes);
    
    NSString* dataString = [self convertByteArrayToHexString:data];// data to hex
    
    NSScanner* scanner = [NSScanner scannerWithString:dataString];
    
    [scanner scanHexInt:&randomNumber];
    
    return [NSString stringWithFormat:@"%u",randomNumber];
}

/*********************************************************************************************
 *                      PAuth 1.0 - Preferred Authentication using HMAC SHA256
 *
 *      This authentication scheme is been deviced to prevent payload tampering during transaction processing.
 *  Method:
 *          Append the following 5 key params (in same order) to obain the HMAC message string and compute the HMAC of it using apiSecret. This is

 *           a shared secret between the developer and Payeezy.
 *
 *
 *  1. ApiKey (Obtained from Payeezy Site)
 *  2. Nonce(Secure-Random number string of length 19)
 *  3. Timestamp (Epoch UTC time stamp in milli seconds)
 *  4. Merchant Token  (Obtained from Payeezy Site)
 *  5. Payload (Use JSON string of payload to make the HMAC message string)
 *
 *   Note: APISECRET is also to be obtained from Payeezy site. Developers are advised not to share this
 *         with any other person due to security reasons.
 *
 *  Header Fields : 'Authorization' , 'timestamp' , 'nonce' follow the order
 *
 *******************************************************************************************/

- (NSString*)generateHMACforpayload:(NSDictionary*)payload
                          timeStamp:(NSString*)timeStamp
                              nonce:(NSString*)nonce
{
    unsigned char outputHMAC[CC_SHA256_DIGEST_LENGTH];
    
    SBJson4Writer * parseString = [[SBJson4Writer alloc] init];
    
    NSString* payloadString = [parseString stringWithObject:payload];
    
    NSString *hmacData = [NSString stringWithFormat:@"%@%@%@%@%@",self.apiKey,nonce,timeStamp,self.merchantToken,payloadString];
    
    const char *keyChar = [self.apiSecret cStringUsingEncoding:NSASCIIStringEncoding];
    
    const char *dataChar = [hmacData cStringUsingEncoding:NSUTF8StringEncoding];
    
    CCHmac(kCCHmacAlgSHA256, keyChar, strlen(keyChar), dataChar, strlen(dataChar), outputHMAC);
    
    NSData *HMAC = [[NSData alloc] initWithBytes:outputHMAC length:sizeof(outputHMAC)];
    
    
    //    get NSData as hex string - another alternative to use deprecated method -(NSString*)convertByteArrayToHexString:(NSData*)dataToBeConverted{
    //    NSString* hmacString = [self convertByteArrayToHexString:HMAC]; // Get HMAC hash in hex
    
    //    TODO: better way to convert ByteArray to hex.
    
    NSString*hmacString = [self convertByteArrayToHexString:HMAC];
    
    
    //    Return Base64 of (HMAC hash in hex)
    return [[hmacString dataUsingEncoding:NSUTF8StringEncoding] base64EncodedStringWithOptions:0];
    
}

 

Please let us know if you face any compilation issue. 

Pl note= Minimum System requirements: The iOS mobile SDK requires iOS SDK 6 and XCode 5.1 and above