I'm in trouble in implementing RSA encryption
and decryption in Objective-C
, I made it in Java
very simply and now I tried to translate this java
code in objc
.
Here is my java
code:
public static byte[] encryptRSA(byte[] text, PublicKey key) throws Exception {
byte[] cipherText = null;
// get an RSA cipher object and print the provider
Cipher cipher = Cipher.getInstance("RSA");
// encrypt the plaintext using the public key
cipher.init(Cipher.ENCRYPT_MODE, key);
cipherText = cipher.doFinal(text);
return cipherText;
}
public static byte[] decryptRSA(byte[] text, PrivateKey key) throws Exception {
byte[] dectyptedText = null;
// decrypt the text using the private key
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.DECRYPT_MODE, key);
dectyptedText = cipher.doFinal(text);
return dectyptedText;
}
and this is how i generate the key pair
String seed = "SOMERANDOMSEED"+Long.toString(System.currentTimeMillis());
KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
SecureRandom rand = new SecureRandom(seed.getBytes());
keyGen.initialize(4096,rand);
KeyPair keyPair = keyGen.generateKeyPair();
PrivateKey privateKey = keyPair.getPrivate();
PublicKey publicKey = keyPair.getPublic();
now in objC I have writed some code that sems to work, but I don't know hot to generate the rsa they from a seed, like i do in java, and how to import the key that i save in java with this method
//for import
public static byte[] hexStringToByteArray(String s) {
byte[] b = new byte[s.length() / 2];
for (int i = 0; i < b.length; i++) {
int index = i * 2;
int v = Integer.parseInt(s.substring(index, index + 2), 16);
b[i] = (byte) v;
}
return b;
}
//for export
public static String byteArrayToHexString(byte[] b) {
StringBuilder sb = new StringBuilder(b.length * 2);
for (int i = 0; i < b.length; i++) {
int v = b[i] & 0xff;
if (v < 16) {
sb.append('0');
}
sb.append(Integer.toHexString(v));
}
return sb.toString().toUpperCase();
}
here is my objc code
//this works properly
+(NSString *)decryptRSA:(NSString *)cipherString key:(SecKeyRef) privateKey {
size_t plainBufferSize = SecKeyGetBlockSize(privateKey);
uint8_t *plainBuffer = malloc(plainBufferSize);
NSData *incomingData = [cipherString decodeFromHexidecimal];
uint8_t *cipherBuffer = (uint8_t*)[incomingData bytes];
size_t cipherBufferSize = SecKeyGetBlockSize(privateKey);
SecKeyDecrypt(privateKey,
kSecPaddingOAEPKey,
cipherBuffer,
cipherBufferSize,
plainBuffer,
&plainBufferSize);
NSData *decryptedData = [NSData dataWithBytes:plainBuffer length:plainBufferSize];
NSString *decryptedString = [[NSString alloc] initWithData:decryptedData encoding:NSUTF8StringEncoding];
return decryptedString;
}
//this works properly
+(NSString *)encryptRSA:(NSString *)plainTextString key:(SecKeyRef)publicKey {
size_t cipherBufferSize = SecKeyGetBlockSize(publicKey);
uint8_t *cipherBuffer = malloc(cipherBufferSize);
uint8_t *nonce = (uint8_t *)[plainTextString UTF8String];
SecKeyEncrypt(publicKey,
kSecPaddingOAEPKey,
nonce,
strlen( (char*)nonce ),
&cipherBuffer[0],
&cipherBufferSize);
NSData *encryptedData = [NSData dataWithBytes:cipherBuffer length:cipherBufferSize];
return [encryptedData hexadecimalString];
}
//here i generate the key pair
#define kPublicKeyTag "com.apple.sample.publickey"
#define kPrivateKeyTag "com.apple.sample.privatekey"
//i should use these as seed!?!!?
- (void)generateKeyPair:(NSUInteger)keySize {
OSStatus sanityCheck = noErr;
publicKeyRef = NULL;
privateKeyRef = NULL;
// Container dictionaries.
NSMutableDictionary * privateKeyAttr = [[NSMutableDictionary alloc] init];
NSMutableDictionary * publicKeyAttr = [[NSMutableDictionary alloc] init];
NSMutableDictionary * keyPairAttr = [[NSMutableDictionary alloc] init];
// Set top level dictionary for the keypair.
[keyPairAttr setObject:(id)kSecAttrKeyTypeRSA forKey:(id)kSecAttrKeyType];
[keyPairAttr setObject:[NSNumber numberWithUnsignedInteger:keySize] forKey:(id)kSecAttrKeySizeInBits];
// Set the private key dictionary.
[privateKeyAttr setObject:[NSNumber numberWithBool:YES] forKey:(id)kSecAttrIsPermanent];
[privateKeyAttr setObject:privateTag forKey:(id)kSecAttrApplicationTag];
// See SecKey.h to set other flag values.
// Set the public key dictionary.
[publicKeyAttr setObject:[NSNumber numberWithBool:YES] forKey:(id)kSecAttrIsPermanent];
[publicKeyAttr setObject:publicTag forKey:(id)kSecAttrApplicationTag];
// See SecKey.h to set other flag values.
// Set attributes to top level dictionary.
[keyPairAttr setObject:privateKeyAttr forKey:(id)@kSecPrivateKeyAttrs];
[keyPairAttr setObject:publicKeyAttr forKey:(id)@kSecPublicKeyAttrs];
// SecKeyGeneratePair returns the SecKeyRefs just for educational purposes.
sanityCheck = SecKeyGeneratePair((__bridge CFDictionaryRef)keyPairAttr, &publicKeyRef, &privateKeyRef);
}
this is the method i use to export keys in objc, it seems work just like the java method
+ (NSString *)fromPrivateKeyToString: (SecKeyRef) privateKey {
size_t pkeySize = SecKeyGetBlockSize(privateKey);
NSData* pkeyData = [NSData dataWithBytes:privateKey length:pkeySize];
NSString* pkeyString = [pkeyData hexadecimalString];
return pkeyString;
}