Convert AES encryption of android in Objective-c xcode - objective-c

I have to use AES Encryption and decryption similiar to below code
Need to pass similiar data like android did to generate KEY
package encypt.com;
import java.io.BufferedReader;
import java.io.FileReader;
import java.security.*;
import java.security.spec.InvalidKeySpecException;
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import sun.misc.*;
public class Testing {
private static final String ALGORITHM = "AES";
private static final int ITERATIONS = 2;
private static final byte[] keyValue =
new byte[] { 'T', 'h', 'i', 's', 'I', 's', 'A', 'S', 'e', 'c', 'r', 'e', 't', 'K', 'e', 'y'};
public static String encrypt(String value, String salt) throws Exception {
Key key = generateKey();
Cipher c = Cipher.getInstance(ALGORITHM);
c.init(Cipher.ENCRYPT_MODE, key);
String valueToEnc = null;
String eValue = value;
for (int i = 0; i < ITERATIONS; i++) {
valueToEnc = salt + eValue;
byte[] encValue = c.doFinal(valueToEnc.getBytes());
eValue = new BASE64Encoder().encode(encValue);
}
return eValue;
}
public static String decrypt(String value, String salt) throws Exception {
Key key = generateKey();
Cipher c = Cipher.getInstance(ALGORITHM);
c.init(Cipher.DECRYPT_MODE, key);
String dValue = null;
String valueToDecrypt = value;
for (int i = 0; i < ITERATIONS; i++) {
byte[] decordedValue = new BASE64Decoder().decodeBuffer(valueToDecrypt);
byte[] decValue = c.doFinal(decordedValue);
dValue = new String(decValue).substring(salt.length());
valueToDecrypt = dValue;
}
return dValue;
}
private static Key generateKey() throws Exception {
Key key = new SecretKeySpec(keyValue, ALGORITHM);
// SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(ALGORITHM);
// key = keyFactory.generateSecret(new DESKeySpec(keyValue));
return key;
}
for iOS i used
 I've found this code through lots of research:
#import "<CommonCrypto/CommonCryptor.h>"
#implementation NSMutableData(AES)
For encryption:
- (NSMutableData*) EncryptAES:(NSString *)key {
char keyPtr[kCCKeySizeAES256+1];
bzero( keyPtr, sizeof(keyPtr) );
[key getCString: keyPtr maxLength: sizeof(keyPtr) encoding: NSUTF16StringEncoding];
size_t numBytesEncrypted = 0;
NSUInteger dataLength = [self length];
size_t bufferSize = dataLength + kCCBlockSizeAES128;
void *buffer = malloc(bufferSize);
NSMutableData *output = [[NSData alloc] init];
CCCryptorStatus result = CCCrypt(kCCEncrypt, kCCAlgorithmAES128, kCCOptionPKCS7Padding, keyPtr, kCCKeySizeAES256, NULL, [self mutableBytes], [self length], buffer, bufferSize, &numBytesEncrypted);
output = [NSMutableData dataWithBytesNoCopy:buffer length:numBytesEncrypted];
if(result == kCCSuccess) {
return output;
}
return NULL;
}
For Decryption:
- (NSMutableData*)DecryptAES: (NSString*)key andForData:(NSMutableData*)objEncryptedData {
char keyPtr[kCCKeySizeAES256+1];
bzero( keyPtr, sizeof(keyPtr) );
[key getCString:keyPtr maxLength:sizeof(keyPtr) encoding:NSUTF16StringEncoding];
size_t numBytesEncrypted = 0;
NSUInteger dataLength = [self length];
size_t bufferSize = dataLength + kCCBlockSizeAES128;
void *buffer_decrypt = malloc(bufferSize);
NSMutableData *output_decrypt = [[NSData alloc] init];
CCCryptorStatus result = CCCrypt(kCCDecrypt , kCCAlgorithmAES128, kCCOptionPKCS7Padding, keyPtr, kCCKeySizeAES256, NULL, [self mutableBytes], [self length], buffer_decrypt, bufferSize, &numBytesEncrypted);
output_decrypt = [NSMutableData dataWithBytesNoCopy:buffer_decrypt length:numBytesEncrypted];
if(result == kCCSuccess) {
return output_decrypt;
}
return NULL;
}
}
This is the code I made that I would like to correspond with the above code:
- (void)Encrypt {
//Convert NSString to NSData so that it can be used to encrypt the Input
NSString *Input = [Inputbox text];
NSData *InputData = [Input dataUsingEncoding:NSUTF8StringEncoding];
//What to do here
}
How do I use this code, these methods? Where does it go in my Implementation file?
This line near the top says you're adding AES functionality to NSMutableData:
#implementation NSMutableData(AES)
In Objective-C, this is called a category; categories let you extend an existing class.
This code would typically go in a file named NSMutableData-AES.m. Create a header file too, NSMutableData-AES.h. It should contain:
#interface NSMutableData(AES)
- (NSMutableData*) EncryptAES: (NSString *) key;
#end
Include (#import) that header in your main file. Add a call to the encryption function in your code:
NSData *InputData = [Input dataUsingEncoding:NSUTF8StringEncoding];
NSData *encryptedData = [InputData EncryptAES:#"myencryptionkey"];
Similarly for decryption.
BUT i am unable to set keyValue and SALT like android did!
Please help
private static final byte[] keyValue =
new byte[] { 'T', 'h', 'i', 's', 'I', 's', 'A', 'S', 'e', 'c', 'r', 'e', 't', 'K', 'e', 'y'};
valueToEnc = salt + eValue;

You can use third party library RNCryptor in cocoapods to en/decryption
// Encryption
NSData *data = ...
NSString *password = #"Secret password";
NSData *ciphertext = [RNCryptor encryptData:data password:password];
// Decryption
NSError *error = nil;
NSData *plaintext = [RNCryptor decryptData:ciphertext password:password error:&error];
if (error != nil) {
NSLog(#"ERROR:%#", error);
return
}
// ...

Related

About 3DES encryption / TripleDES different result in Objective-C and vb

Now there is a demand, let me change the VB program of win to Mac cocoa program.
There is a 3DES encryption problem that bothers me
The encrypted strings of Mac and vb are completely different.
VB uses the TripleDES library, but Mac cannot import this library. I had to write one myself, but the results were different.
Mac:Objective-C,
Win:vb
I will upload my program, please help me. Thank you
//obj code
- (NSString*)doEncryptStr:(NSString*)originalStr { //withKey:(NSString*)key
NSString *key = #"XXXX";
uint8_t keyByte[kSecrectKeyLength];
//NSMutableData *keyData = [[NSMutableData alloc] init];
int i;
for (i=0; i < [key length]/2; i++) {
NSString *tempNumber = [key substringWithRange: NSMakeRange(i * 2, 2)];
//NSLog(#"tempNum == %#", tempNumber);
NSScanner *scanner = [NSScanner scannerWithString:tempNumber];
//NSLog(#"scanner == %#", scanner.string);
unsigned int temp;
[scanner scanHexInt:&temp];
Byte B = (Byte)(0xFF & temp);
keyByte[i] = B;
}
//NSUTF8StringEncoding
NSData* data = [originalStr dataUsingEncoding:NSUTF16StringEncoding];
size_t plainTextBufferSize = [data length];
const void *vplainText = (const void *)[data bytes];
CCCryptorStatus ccStatus;
uint8_t *bufferPtr = NULL;
size_t bufferPtrSize = 0;
size_t movedBytes = 0;
bufferPtrSize = (plainTextBufferSize + kCCBlockSize3DES) & ~(kCCBlockSize3DES - 1);
bufferPtr = malloc(bufferPtrSize * sizeof(uint8_t));
memset((void *)bufferPtr, 0x0, bufferPtrSize);
const void *vkey = (const void *) keyByte;
const void *vinitVec = (const void *) [gIv UTF8String];
ccStatus = CCCrypt(
kCCEncrypt,
kCCAlgorithmDES,
kCCOptionPKCS7Padding,
vkey,
kCCKeySizeDES,
vinitVec,
vplainText,
plainTextBufferSize,
(void *)bufferPtr,
bufferPtrSize,
&movedBytes);
NSData *myData = [NSData dataWithBytes:(const void *)bufferPtr length:(NSUInteger)movedBytes];
NSString *result = [GTMBase64 stringByEncodingData:myData];
NSLog(#"result == %#",result);
return result;
}
Below is the vb code
Public Function EncryptData(ByVal plaintext As String) As String
' Convert the plaintext string to a byte array.
Dim plaintextBytes() As Byte = _
System.Text.Encoding.Unicode.GetBytes(plaintext)
' Create the stream.
Dim ms As New System.IO.MemoryStream
' Create the encoder to write to the stream.
Dim encStream As New CryptoStream(ms, _
TripleDes.CreateEncryptor(), _
System.Security.Cryptography.CryptoStreamMode.Write)
' Use the crypto stream to write the byte array to the stream.
encStream.Write(plaintextBytes, 0, plaintextBytes.Length)
encStream.FlushFinalBlock()
' Convert the encrypted stream to a printable string.
Return Convert.ToBase64String(ms.ToArray)
End Function

How to encrypt with AES 256 CBC in Objective C

I am building an iPhone app which gets a encrypt string and sent it to backend.
In PHP I am encrypting the string like this:
$encrypt_method = "AES-256-CBC";
$secret_key = 'This is my secret key';
$secret_iv = 'This is my secret iv';
// hash
$key = hash('sha256', $secret_key);
// iv - encrypt method AES-256-CBC expects 16 bytes - else you will get a warning
$iv = substr(hash('sha256', $secret_iv), 0, 16);
if( $action == 'encrypt' ) {
$output = openssl_encrypt($string, $encrypt_method, $key, 0, $iv);
$output = base64_encode($output);
}
How I do the same like that but in Objective C
#import <CommonCrypto/CommonCryptor.h>
#define key #"YOUR_KEY"
#define iv #"YOUR_IV"
- (NSData *) cryptOperation:(CCOperation)operation
{
// 'key' should be 32 bytes for AES256, will be null-padded otherwise
char keys[kCCKeySizeAES256 + 1];
[key getCString:keys maxLength:sizeof(keys) encoding:NSUTF8StringEncoding];
// Perform PKCS7Padding on the key.
unsigned long bytes_to_pad = sizeof(keys) - [key length];
if (bytes_to_pad > 0)
{
char byte = bytes_to_pad;
for (unsigned long i = sizeof(keys) - bytes_to_pad; i < sizeof(keys); i++)
keys[i] = byte;
}
NSUInteger dataLength = [self length];
//See the doc: For block ciphers, the output size will always be less than or
//equal to the input size plus the size of one block.
//That's why we need to add the size of one block here
size_t bufferSize = dataLength + kCCBlockSizeAES128;
void *buffer = malloc(bufferSize);
size_t numBytesDecrypted = 0;
CCCryptorStatus status = CCCrypt(operation, kCCAlgorithmAES128,
kCCOptionPKCS7Padding,
keys, kCCKeySizeAES256,
[iv UTF8String],
[self bytes], dataLength, /* input */
buffer, bufferSize, /* output */
&numBytesDecrypted);
if (status == kCCSuccess)
{
//the returned NSData takes ownership of buffer and will free it on dealloc
return [NSData dataWithBytesNoCopy:buffer length:numBytesDecrypted];
}
free(buffer); //free the buffer;
return nil;
}
- (NSData *)AES256Encrypt
{
return [self cryptOperation:kCCEncrypt];
}
- (NSData *)AES256Decrypt
{
return [self cryptOperation:kCCDecrypt];
}
you can use this method by following way..
NSString *receivedDataDecryptString = [self decrypt:#"YOUR_STRING"];
NSString *receivedDataEncryptString = [self encrypt:#"YOUR_STRING"];
-(NSString *)encrypt:(NSString *)string
{
NSData *data = [string dataUsingEncoding:NSUTF8StringEncoding];
NSData *dataEncrypted = [data AES256Encrypt];
NSString *strRecordEncrypted = [dataEncrypted base64EncodedStringWithOptions:0];
return strRecordEncrypted;
}
-(NSString *)decrypt:(NSString *)string
{
if([string containsString:#"\n"] || [string containsString:#"\t"])
{
string = [[string componentsSeparatedByCharactersInSet:[NSCharacterSet newlineCharacterSet]] componentsJoinedByString:#""];
string = [string stringByReplacingOccurrencesOfString:#"\t" withString:#""];
}
NSData *keyData = [[NSData alloc] initWithBase64EncodedString:string options:0];
NSData *dataDecrypted = [keyData AES256Decrypt];
NSString *receivedDataDecryptString = [[NSString alloc]initWithData:dataDecrypted encoding:NSUTF8StringEncoding];
return receivedDataDecryptString;
}
Thanks Nirav Kotecha for your answer.
I ended up using CrytoSwift and Add Extension class NSString and String to call it.

How to get IV from AES encryption in objective C?

I am new to AES encryption.
I am using following java code for encrypting my password and it works fine.
private void startEncryption() throws UnsupportedEncodingException {
String text = "15";
String key = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
String ivString = "LXUJOLKDEJKGTMAV";
byte[] valueBytes = text.getBytes();
byte[] keyBytes = keyString.getBytes("UTF-8");
byte[] ivBytes = ivString.getBytes();
byte[] ivFinalBytes = new byte[16];
for(int i=0; i<16; i++){
ivFinalBytes[i] = ivBytes[i];
}
encrypt(valueBytes, keyBytes, ivFinalBytes);
}
private void encrypt(byte[] valueBytes, byte[] keyBytes, byte[] ivBytes) {
try {
SecretKeySpec ks = new SecretKeySpec(keyBytes, "AES");
Cipher c = Cipher.getInstance("AES/CBC/PKCS7Padding");
IvParameterSpec ivParameterSpec = new IvParameterSpec(ivBytes);
c.init(Cipher.ENCRYPT_MODE, ks, ivParameterSpec);
byte[] clearText = c.doFinal(valueBytes);
String ivPass = Base64.encodeToString(c.getIV(), Base64.DEFAULT);
String pass = Base64.encodeToString(clearText, Base64.DEFAULT);
encryptedPassword = ivPass+pass;
encryptedPassword = encryptedPassword.replace("\n", "").replace("\r", "");
} catch (Exception e) {
System.out.println("exception: "+e);
}
}
Output looks like following:
azhTMrwGqTN21O4oRenR6Q==VE5LTU9GT1BCWldRSEREQQ==
Now I am trying to do same thing in objective C. Following is the code which i am using right now:
-(NSString*)testActuallyEncrypting:(NSString *)data
{
NSString *key = #"xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
NSString *iv = #"LXUJOLKDEJKGTMAV";
NSData *dataIn = [data dataUsingEncoding:NSUTF8StringEncoding];
NSData *keyData = [key dataUsingEncoding:NSUTF8StringEncoding];
NSData *ivData = [iv dataUsingEncoding:NSUTF8StringEncoding];
CCCryptorStatus ccStatus = kCCSuccess;
size_t cryptBytes = 0;
NSMutableData *dataOut = [NSMutableData dataWithLength:dataIn.length + kCCBlockSizeAES128];
ccStatus = CCCrypt( kCCEncrypt,
kCCAlgorithmAES128,
kCCOptionPKCS7Padding,
keyData.bytes, kCCKeySizeAES256,
ivData.bytes,
dataIn.bytes, dataIn.length,
dataOut.mutableBytes, dataOut.length,
&cryptBytes);
if (ccStatus != kCCSuccess) {
NSLog(#"CCCrypt status: %d", ccStatus);
}
dataOut.length = cryptBytes;
NSString *objcEncrypted = [dataOut base64EncodedStringWithOptions:0];
NSLog(#"objcEncrypted: %#", objcEncrypted);
return objcEncrypted;
}
Seems like I am getting the right encrypted password.
VE5LTU9GT1BCWldRSEREQQ==
How can I get IV which should be like azhTMrwGqTN21O4oRenR6Q==?
I figured it out and adding following line of codes solved my problem:
NSString *ivEncrypted = [ivData base64EncodedStringWithOptions:0];
NSString *encryptedString = [NSString stringWithFormat:#"%#%#", ivEncrypted, objcEncrypted];
and then return encryptedString

encrypt nsstring with 3des ios7

I am new with iOS7 development and objective c, and i need to develop an application which will send encrypted data with 3DES to a server,I have searched in stack overflow and Net but still unable to get it work, finally i tried this code but i got null as result,
+ (NSString*)encrypt:(NSString*)plainText withKey:(NSString*)key{
uint8_t keyByte[kSecrectKeyLength];
NSMutableData *keyData = [[NSMutableData alloc] init];
int i;
for (i=0; i < [key length] / 2; i++) {
NSString *tempNumber = [key substringWithRange: NSMakeRange(i * 2, 2)];
NSScanner *scanner=[NSScanner scannerWithString:tempNumber];
unsigned int temp;
[scanner scanHexInt:&temp];
Byte B = (Byte)(0xFF & temp);
keyByte[i] = B;
}
NSData* data = [plainText dataUsingEncoding:NSUTF8StringEncoding];
size_t plainTextBufferSize = [data length];
const void *vplainText = (const void *)[data bytes];
CCCryptorStatus ccStatus;
uint8_t *bufferPtr = NULL;
size_t bufferPtrSize = 0;
size_t movedBytes = 0;
bufferPtrSize = (plainTextBufferSize + kCCBlockSize3DES) & ~(kCCBlockSize3DES - 1);
bufferPtr = malloc( bufferPtrSize * sizeof(uint8_t));
memset((void *)bufferPtr, 0x0, bufferPtrSize);
const void *vkey = (const void *) keyByte;
const void *vinitVec = (const void *) [gIv UTF8String];
ccStatus = CCCrypt(kCCEncrypt,
kCCAlgorithm3DES,
kCCOptionPKCS7Padding,
vkey,
kCCKeySize3DES,
vinitVec,
vplainText,
plainTextBufferSize,
(void *)bufferPtr,
bufferPtrSize,
&movedBytes);
NSData *myData = [NSData dataWithBytes:(const void *)bufferPtr length:(NSUInteger)movedBytes];
//NSString *result = [GTMBase64 stringByEncodingData:myData];
NSString *result = [[NSString alloc] initWithData:myData encoding:NSUTF8StringEncoding];
NSLog(#"result=%#",result);
return result;
}
Please have u any idea about the solution???
lol i just struggled with this myself the other day, i have a working solution now using this code
+ (NSData *)tripleDesEncryptString:(NSString *)input
key:(NSString *)key
error:(NSError **)error
{
NSParameterAssert(input);
NSParameterAssert(key);
NSData *inputData = [input dataUsingEncoding:NSUTF8StringEncoding];
NSData *keyData = [key dataUsingEncoding:NSUTF8StringEncoding];
size_t outLength;
NSAssert(keyData.length == kCCKeySize3DES, #"the keyData is an invalid size");
NSMutableData *outputData = [NSMutableData dataWithLength:(inputData.length + kCCBlockSize3DES)];
CCCryptorStatus
result = CCCrypt(kCCEncrypt, // operation
kCCAlgorithm3DES, // Algorithm
kCCOptionPKCS7Padding | kCCOptionECBMode, // options
keyData.bytes, // key
keyData.length, // keylength
nil,// iv
inputData.bytes, // dataIn
inputData.length, // dataInLength,
outputData.mutableBytes, // dataOut
outputData.length, // dataOutAvailable
&outLength); // dataOutMoved
if (result != kCCSuccess) {
if (error != NULL) {
*error = [NSError errorWithDomain:#"com.your_domain.your_project_name.your_class_name."
code:result
userInfo:nil];
}
return nil;
}
[outputData setLength:outLength];
return outputData;
}
+ (NSString *)tripleDesDecryptData:(NSData *)input
key:(NSString *)key
error:(NSError **)error
{
NSParameterAssert(input);
NSParameterAssert(key);
NSData *inputData = input;
NSData *keyData = [key dataUsingEncoding:NSUTF8StringEncoding];
size_t outLength;
NSAssert(keyData.length == kCCKeySize3DES, #"the keyData is an invalid size");
NSMutableData *outputData = [NSMutableData dataWithLength:(inputData.length + kCCBlockSize3DES)];
CCCryptorStatus
result = CCCrypt(kCCDecrypt, // operation
kCCAlgorithm3DES, // Algorithm
kCCOptionPKCS7Padding | kCCOptionECBMode, // options
keyData.bytes, // key
keyData.length, // keylength
nil,// iv
inputData.bytes, // dataIn
inputData.length, // dataInLength,
outputData.mutableBytes, // dataOut
outputData.length, // dataOutAvailable
&outLength); // dataOutMoved
if (result != kCCSuccess) {
if (error != NULL) {
*error = [NSError errorWithDomain:#"com.your_domain.your_project_name.your_class_name."
code:result
userInfo:nil];
}
return nil;
}
[outputData setLength:outLength];
return [[NSString alloc] initWithData:outputData encoding:NSUTF8StringEncoding];
}
you probably want to base64 encode the data the comes out of the encryption method, and then un-base64 anything that you want to decrypt as well, there are built in methods for NSData to do this now, eg:
[data base64EncodedDataWithOptions:(NSDataBase64EncodingOptions)];
to test if the functions work, i used this test function
+ (void) testEncryptionAndDecryption {
NSData *encrypted = [self tripleDesEncryptString:#"test" key:#"123456789123456789123456" error:nil];
NSLog(#"encrypted data length: %lu", (unsigned long)encrypted.length);
NSString *decrypted = [self tripleDesDecryptData:encrypted key:#"123456789123456789123456" error:nil];
NSLog(#"decrypted text: %#", decrypted);
}
this gave me the correct output that you would expect

Equivalent Hashing in C# and Objective-C using HMAC256

I'm working with a partner and we're not able to get C# and Objective-C to produce the same hashes using what we think are the same tools in the respective languages. In C#, I'm doing this:
byte[] noncebytes=new byte[32];
//We seed the hash generator with a new 32 position array. Each position is 0.
//In prod code this would be random, but for now it's all 0s.
HMACSHA256 hmac256 = new HMACSHA256(noncebytes);
string plaintext = "hello";
string UTFString = Convert.ToBase64String(
System.Text.Encoding.UTF8.GetBytes(plaintext));
string HashString = Convert.ToBase64String(
hmac256.ComputeHash(System.Text.Encoding.UTF8.GetBytes(plaintext))); //Convert that hash to a string.
This produces the following base64string hash:
Q1KybjP+DXaaiSKmuikAQQnwFojiasyebLNH5aWvxNo=
What is the equivalent Objective-C code to do this? We need the client and the server to be able to generate matching hashes for matching data.
Here is the Objective-C code we are currently using:
...
NSData *zeroNumber = [self zeroDataWithBytes:32]; //empty byte array
NSString *nonceTest = [zeroNumber base64String]; // using MF_Base64Additions.h here
NSData *hashTest = [self hmacForKeyAndData:nonceTest withData:#"hello"]; //creating hash
NSString *hashTestText = [hashTest base64String];
NSLog(#"hello hash is %#", hashTestText);
...
//functions for zeroing out the byte. I'm sure there's a better way
- (NSData *)zeroDataWithBytes: (NSUInteger)length {
NSMutableData *mutableData = [NSMutableData dataWithCapacity: length];
for (unsigned int i = 0; i < length; i++) {
NSInteger bits = 0;
[mutableData appendBytes: (void *) &bits length: 1];
} return mutableData;
}
//hash function
-(NSData *) hmacForKeyAndData:(NSString *)key withData:(NSString *) data {
const char *cKey = [key cStringUsingEncoding:NSASCIIStringEncoding];
const char *cData = [data cStringUsingEncoding:NSASCIIStringEncoding];
unsigned char cHMAC[CC_SHA256_DIGEST_LENGTH];
CCHmac(kCCHmacAlgSHA256, cKey, strlen(cKey), cData, strlen(cData), cHMAC);
return [[NSData alloc] initWithBytes:cHMAC length:sizeof(cHMAC)];
}
UPDATE:
There is a pretty good project on GitHub that seems to accomplish everything you want, plus a lot more encryption related options; includes unit tests.
NSData *hmacForKeyAndData(NSString *key, NSString *data)
{
const char *cKey = [key cStringUsingEncoding:NSASCIIStringEncoding];
const char *cData = [data cStringUsingEncoding:NSASCIIStringEncoding];
unsigned char cHMAC[CC_SHA256_DIGEST_LENGTH];
CCHmac(kCCHmacAlgSHA256, cKey, strlen(cKey), cData, strlen(cData), cHMAC);
return [[NSData alloc] initWithBytes:cHMAC length:sizeof(cHMAC)];
}
(Source)
With the above, I think you will have import <CommonCrypto/CommonHMAC.h>. The next step for encoding to Base64:
+ (NSString *)Base64Encode:(NSData *)data
{
//Point to start of the data and set buffer sizes
int inLength = [data length];
int outLength = ((((inLength * 4)/3)/4)*4) + (((inLength * 4)/3)%4 ? 4 : 0);
const char *inputBuffer = [data bytes];
char *outputBuffer = malloc(outLength);
outputBuffer[outLength] = 0;
//64 digit code
static char Encode[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
//start the count
int cycle = 0;
int inpos = 0;
int outpos = 0;
char temp;
//Pad the last to bytes, the outbuffer must always be a multiple of 4
outputBuffer[outLength-1] = '=';
outputBuffer[outLength-2] = '=';
/* http://en.wikipedia.org/wiki/Base64
Text content M a n
ASCII 77 97 110
8 Bit pattern 01001101 01100001 01101110
6 Bit pattern 010011 010110 000101 101110
Index 19 22 5 46
Base64-encoded T W F u
*/
while (inpos < inLength){
switch (cycle) {
case 0:
outputBuffer[outpos++] = Encode[(inputBuffer[inpos]&0xFC)>>2];
cycle = 1;
break;
case 1:
temp = (inputBuffer[inpos++]&0x03)<<4;
outputBuffer[outpos] = Encode[temp];
cycle = 2;
break;
case 2:
outputBuffer[outpos++] = Encode[temp|(inputBuffer[inpos]&0xF0)>> 4];
temp = (inputBuffer[inpos++]&0x0F)<<2;
outputBuffer[outpos] = Encode[temp];
cycle = 3;
break;
case 3:
outputBuffer[outpos++] = Encode[temp|(inputBuffer[inpos]&0xC0)>>6];
cycle = 4;
break;
case 4:
outputBuffer[outpos++] = Encode[inputBuffer[inpos++]&0x3f];
cycle = 0;
break;
default:
cycle = 0;
break;
}
}
NSString *pictemp = [NSString stringWithUTF8String:outputBuffer];
free(outputBuffer);
return pictemp;
}
Note the second line of code in the objective-c portion of the question.
NSString *nonceTest = [zeroNumber base64String];
but it should be this:
NSString *nonceTest = [[NSString alloc] initWithData:zeroNumber encoding:NSASCIIStringEncoding];
It was a case of converting the string to base64 when we didn't need to for the hmac seeeding.
We now get: Q1KybjP+DXaaiSKmuikAQQnwFojiasyebLNH5aWvxNo= as the hash on both platforms.