Reputation: 7903
I have tried following code so far:
+(NSString*)encodeString:(NSString*)origString{
/* Here we can choose the algorithm */
NSData *keyData = [@"secret_key" dataUsingEncoding:NSUTF8StringEncoding];
NSData *textData = [origString dataUsingEncoding:NSUTF8StringEncoding];
uint8_t digest[CC_SHA1_DIGEST_LENGTH] = {0};
CCHmacContext hmacContext;
CCHmacInit(&hmacContext, kCCHmacAlgSHA1, keyData.bytes, keyData.length);
CCHmacUpdate(&hmacContext, textData.bytes, textData.length);
CCHmacFinal(&hmacContext, digest);
/* out is HMAC */
NSData *out = [NSData dataWithBytes:digest length:CC_SHA1_DIGEST_LENGTH];
/* resultString is Base64 encoded HMAC */
NSString *resultString = [out base64EncodedString];
return resultString;
}
This is giving correct result as wanted. But my android and Back-end partner want me to clone following code into objective-c:
private String encryptString(String origString) {
String encryptedString = "";
Cipher cipher = null;
byte[] encoded = null;
byte[] rawEnc =null;
try {
//Code which is working
cipher = Cipher.getInstance("AES/CBC/PKCS5Padding", "SunJCE");
SecretKeySpec key = new SecretKeySpec(SECRET_KEY.getBytes("UTF-8"), "AES");
cipher.init(Cipher.ENCRYPT_MODE, key, new IvParameterSpec(INITIALIZATIO_VECTOR.getBytes("UTF-8")));
rawEnc = cipher.doFinal(origString.getBytes("UTF-8"));
encoded = Base64.encodeBase64(rawEnc);
encryptedString = new String(encoded, "UTF-8");
} catch (NoSuchAlgorithmException e) {
System.out.println("No Such Algorithm Exception:" + e.getMessage());
} catch (NoSuchProviderException e) {
System.out.println("No Such Provider Exception:" + e.getMessage());
} catch (NoSuchPaddingException e) {
System.out.println("No Such Padding Exception:" + e.getMessage());
} catch (InvalidKeyException | InvalidAlgorithmParameterException
| UnsupportedEncodingException e) {
System.out.println("Exception:" + e.getMessage());
} catch (Exception e) {
System.out.println("Exception:" + e.getMessage());
}
return encryptedString;
}
private static final String SECRET_KEY = "secret_key";
private static final String INITIALIZATIO_VECTOR = "123456";
}
And android's output is different than iOS and is as required by back-end developer. So, I have to convert code according to theirs.
The only things differs is INITIALIZATIO_VECTOR
.
I want above code in objective-C.
Upvotes: 0
Views: 85
Reputation: 112875
The question contains: "Implementing Base 64".
There is no need on iOS, just use the Apple NSData
Base64 APIs:
Create a Base-64 encoded NSString from the receiver's contents using the given options:
- base64EncodedStringWithOptions:
Returns a data object initialized with the given Base-64 encoded data:
- initWithBase64EncodedData:options:
Returns a data object initialized with the given Base-64 encoded string:
- initWithBase64EncodedString:options:
etc.
Upvotes: 1