I have a RSA key (pair) represented as big integeger modulus and exponent and need to encrypt/decrypt with those.
I figured out how to handle keys as needed in iOS using swift.
To my question: Is there any way to convert the modulus/exponent representation to a standard SecKeyRef?
Both is formatted as big int (coming from android),
a modulus for example looks like this:
23986589886077318012326064844037831693417390067186403792990846282531380456965701688980194375481519508455379138899060072530724598302129656976140458275478340281694599774176865257462922861492999970413042311221914141827738166785420817621605554859384423695247859963064446809695729281306530681131568503935369097838468173777374667631401317163094053418212485192857751897040859007584244053136110895205839896478287122804119514727484734998762296502939823974188856604771622873660784676915716476754048257418841069214486772931445697194023455179601077893872576165858771367831752886749210944303260745331014786145738511592470796648651
I had exactly the same task - given a modulus and an exponent I had to create a public key and encrypt a message using that key. After a long time spent in reading and trying various libraries, I was able to accomplish this with OpenSSL. I'm posting my way of doing it below. Although it's written in Objective-C, it might be helpful.
NSData* message, modulus, exponent;
BIGNUM* mod = BN_bin2bn((unsigned char *)[modulus bytes], (int)modulus.length, NULL);
if (mod == NULL) {
NSLog(#"Error creating modulus BIGNUM");
}
BIGNUM* exp = BN_bin2bn((unsigned char *)[exponent bytes], (int)exponent.length, NULL);
if (exp == NULL) {
NSLog(#"Error creating exponent BIGNUM");
}
RSA* rsa = RSA_new();
rsa->pad = 0;
rsa->e = exp;
rsa->n = mod;
int keylen = RSA_size(rsa);
unsigned char* enc = malloc(keylen);
char* err = malloc(130);
int status = RSA_public_encrypt((int)message.length, (const unsigned char*)[message bytes], enc, rsa, RSA_NO_PADDING);
if (status != -1) {
NSData* encryptedMessage = [NSData dataWithBytes:enc length:keylen];
NSLog(#"Encryption SUCCESSFUL: %#", encryptedMessage);
}
else {
ERR_load_crypto_strings();
ERR_error_string(ERR_get_error(), err);
NSLog(#"Encryption failed with error: %s", err);
}
free(enc);
free(err);
So first I'm creating big integers out of my NSData modulus and exponent. You already have them as big integers, but if they're not represented as OpenSSL's BIGNUM type, you'll have to convert them. BIGNUM has other useful functions for creating big integers like BN_hex2bn and BN_dec2bn - these create big integers out of C strings containing hexadecimal or decimal numbers. In my case the modulus and exponent are stored as a byte array in an NSData and BN_bin2bn creates a BIGNUM directly from that.
Moving on, I create an RSA structure which represents a key and holds the modulus and exponent, and the enc buffer, which will hold the raw encrypted bytes. The length of enc is the same as the size of the key, because RSA can not encrypt messages longer that the key.
The main work is done by the RSA_public_encrypt() function. It takes five arguments - the size of the message that you're going to encrypt, the actual message bytes, an output buffer to store the encrypted message in, the RSA key and a padding scheme. I'm using no padding here, because my message is exactly the same size as the key, but in the rsa.h there are macros that represent the most common padding schemes.
Lastly I check the status which holds the number of encrypted bytes and print an error message if something went wrong.
I hope this will help you and somebody else. Tell me if you managed to do it in Swift. Cheers ;-)
P.S. Adding OpenSSL to your iOS project is easy using CocoaPods. Just add
pod 'OpenSSL-Universal', '1.0.1.k'
to your podfile.
Related
i'm using external library OpenSSL-Universal for encrypting password using RSA_PKCS1_PADDING. Unfortunately the output of char encoded result have an inconsistent length. Let say i have 2048 bit modulus the length result i expect is 128 otherwise it will be failed to decrypt back to plain text.
BIGNUM *xponent = BN_new();
BIGNUM *modulus = BN_new();
BN_hex2bn(&xponent,xponentInHex);
BN_hex2bn(&modulus,modInHex);
RSA *rsa = RSA_new();
rsa->e = xponent;
rsa->n = modulus;
char encoded[1024] = {0};
RSA_public_encrypt(
(int)strlen(charString),// from len
(const unsigned char *)charString, // from
(unsigned char *)encoded, // to
rsa,
RSA_PKCS1_PADDING
);
RSA_free(rsa);
NSLog(#"%lu", strlen(encoded));
if there is anything wrong with my implements or if you have some explanation about inconsistent length result please let me know
Encrypted Output from RSA_public_encrypt is not a string, so you cannot check it's length using strlen. I hope you do realize that strlen will consider any '\0' seen in your encrypted output as end of string and will return the numbers of bytes till that point as length of the string. But, encrypted buffer can have valid bytes which can be '\0'.
Also, please note that RSA_public_encrypt returns the length of the encrypted data, which you should be using.
You can try using Objective-C-RSA third-party libraries,Or read the source code and then realize by yourself.
I have been using UUIDString as an encrption key for the files stored on my iPAD, but the security review done on my app by a third party suggested the following.
With the launch of the application, a global database key is generated and stored in the keychain. During generation, the method UUIDString of the class NSUUID provided by the iOS is used. This function generates a random string composed of letters A to F, numbers and hyphens and unnecessarily restricts the key space, resulting in a weakening of the entropy.
Since the key is used only by application logic and does not have to be read, understood or processed by an individual, there is no need to restrict the key space to readable characters. Therefore, a random 256-bit key generated via SecRandomCopyBytes () should be used as the master key.
Now I have searched a lot and tried some code implementation but havent found the exact thing.
What I have tried:
NSMutableData* data = [NSMutableData dataWithLength:32];
int result = SecRandomCopyBytes(kSecRandomDefault, 32, data.mutableBytes);
NSLog(#"Description %d",result);
My understanding is that this should give me an integer and I should convert it to an NSString and use this as my key, but I am pretty sure that this is not what is required here and also the above method always gives the result as 0. I am completely lost here and any help is appreciated.
Thanks.
The result of SecRandomCopyBytes should always be 0, unless there is some error (which I can't imagine why that might happen) and then the result would be -1. You're not going to convert that into a NSString.
The thing you're trying to get are the random bytes which are being written into the mutable bytes section, and that's what you'll be using as your "master key" instead of the UUID string.
The way I would do it would be:
uint8_t randomBytes[16];
int result = SecRandomCopyBytes(kSecRandomDefault, 16, randomBytes);
if(result == 0) {
NSMutableString *uuidStringReplacement = [[NSMutableString alloc] initWithCapacity:16*2];
for(NSInteger index = 0; index < 16; index++)
{
[uuidStringReplacement appendFormat: #"%02x", randomBytes[index]];
}
NSLog(#"uuidStringReplacement is %#", uuidStringReplacement);
} else {
NSLog(#"SecRandomCopyBytes failed for some reason");
}
Using a UUIDString feels secure enough to me, but it sounds like your third party security audit firm is trying really hard to justify their fees.
EDITED: since I'm now starting to collect downvotes because of Vlad's alternative answer and I can't delete mine (as it still has the accepted checkmark), here's another version of my code. I'm doing it with 16 random bytes (which gets doubled in converting to Hex).
The NSData generated does not guarantee UTF16 chars.
This method will generate 32byte UTF string which is equivalent to 256bit. (Advantage is this is plain text and can be sent in GET requests ext.)
Since the length of Base64 hash is = (3/4) x (length of input string) we can work out input length required to generate 32byte hash is 24 bytes long. Note: Base64 may pad end with one, two or no '=' chars if not divisible.
With OSX 10.9 & iOS 7 you can use:
-[NSData base64EncodedDataWithOptions:]
This method can be used to generate your UUID:
+ (NSString*)generateSecureUUID {
NSMutableData *data = [NSMutableData dataWithLength:24];
int result = SecRandomCopyBytes(NULL, 24, data.mutableBytes);
NSAssert(result == 0, #"Error generating random bytes: %d", result);
NSString *base64EncodedData = [data base64EncodedStringWithOptions:0];
return base64EncodedData;
}
A UUID is a 16 bytes (128 bits) unique identifier, so you aren't using a 256 bits key here. Also, as #zaph pointed out, UUIDs use hardware identifiers and other inputs to guarantee uniqueness. These factors being predictable are definitely not cryptographically secure.
You don't have to use a UUID as an encryption key, instead I would go for a base 64 or hexadecimal encoded data of 32 bytes, so you'll have your 256 bit cryptographically secure key:
/** Generates a 256 bits cryptographically secure key.
* The output will be a 44 characters base 64 string (32 bytes data
* before the base 64 encoding).
* #return A base 64 encoded 256 bits secure key.
*/
+ (NSString*)generateSecureKey
{
NSMutableData *data = [NSMutableData dataWithLength:32];
int result = SecRandomCopyBytes(kSecRandomDefault, 32, data.mutableBytes);
if (result != noErr) {
return nil;
}
return [data base64EncodedStringWithOptions:kNilOptions];
}
To answer the part about generate UUID-like (secure) random numbers, here's a good way, but remember these will be 128 bits only keys:
/** Generates a 128 bits cryptographically secure key, formatted as a UUID.
* Keep that you won't have the same guarantee for uniqueness
* as you have with regular UUIDs.
* #return A cryptographically secure UUID.
*/
+ (NSString*)generateCryptoSecureUUID
{
unsigned char bytes[16];
int result = SecRandomCopyBytes(kSecRandomDefault, 16, bytes);
if (result != noErr) {
return nil;
}
return [[NSUUID alloc] initWithUUIDBytes:bytes].UUIDString;
}
Cryptography is great, but doing it right is really hard (it's easy to leave security breaches). I cannot recommend you more the use of RNCryptor, which will push you through the use of good encryption standards, will make sure you're not unsafely reusing the same keys, will derivate encryption keys from passwords correctly, etc.
And i try this code for length 16 and bytes 16 :
uint8_t randomBytes[16];
NSMutableString *ivStr;
int result = SecRandomCopyBytes(kSecRandomDefault, 16, randomBytes);
if(result == 0) {
ivStr = [[NSMutableString alloc] initWithCapacity:16];
for(NSInteger index = 0; index < 8; index++)
{
[ivStr appendFormat: #"%02x", randomBytes[index]];
}
NSLog(#"uuidStringReplacement is %#", ivStr);
} else {
NSLog(#"SecRandomCopyBytes failed for some reason");
}
Successful
Since the Key usually needs to be UTF-8 encoded and "readable" - i.e. with no UTF-8 control characters- I decided to filter the randomly generated bytes generated using SecRandomCopyBytes so it'd only have characters from the Basic Latin Unicode block.
/*!
* #brief Generates NSData from a randomly generated byte array with a specific number of bits
* #param numberOfBits the number of bits the generated data must have
* #return the randomly generated NSData
*/
+ (NSData *)randomKeyDataGeneratorWithNumberBits:(int)numberOfBits {
int numberOfBytes = numberOfBits/8;
uint8_t randomBytes[numberOfBytes];
int result = SecRandomCopyBytes(kSecRandomDefault, numberOfBytes, randomBytes);
if(result == 0) {
return [NSData dataWithBytes:randomBytes length:numberOfBytes];
} else {
return nil;
}
}
/*!
* #brief Generates UTF-8 NSData from a randomly generated byte array with a specific number of bits
* #param numberOfBits the number of bits the generated data must have
* #return the randomly generated NSData
*/
+ (NSData *)randomKeyUTF8DataGeneratorWithNumberBits:(int)numberOfBits {
NSMutableData *result = [[NSMutableData alloc] init];
int numberOfBytes = numberOfBits/8;
while (result.length < numberOfBytes) {
// Creates a random byte
NSData *byte = [self randomKeyDataGeneratorWithNumberBits:8];
int asciiValue = [[[NSString alloc] initWithData:byte encoding:NSUTF8StringEncoding] characterAtIndex:0];
// Checks if the byte is UTF-8
if (asciiValue > 32 && asciiValue < 127) {
[result appendData:byte];
}
}
return result;
}
If you want to make your key a little more "readable" you can try and make it Base64 URL Safe
/*!
* #brief Encodes a String Base 64 with URL and Filename Safe Alphabet
* #discussion Base64url Encoding The URL- and filename-safe Base64 encoding described in RFC 4648 [RFC4648] (https://tools.ietf.org/html/rfc4648)
* #discussion Section 5 (https://tools.ietf.org/html/rfc4648#section-5)
* #param string the string to be enconded
* #return the encoded string
*/
+ (NSString *)base64URLandFilenameSafeString:(NSString *)string {
NSString *base64String = string;
base64String = [base64String stringByReplacingOccurrencesOfString:#"/"
withString:#"_"];
base64String = [base64String stringByReplacingOccurrencesOfString:#"+"
withString:#"-"];
return base64String;
}
Generate a UTF-8 256 bits key:
NSData *key = [self randomKeyUTF8DataGeneratorWithNumberBits:256];
NSString *UTF8String = [[NSString alloc] initWithBytes:[key bytes] length:data.length encoding:NSUTF8StringEncoding];
NSString *base64URLSafeString = [self base64URLandFilenameSafeString:UTF8String];
I'm using the following code to obfuscate a passcode for a test app of mine.
- (NSString *)obfuscate:(NSString *)string withKey:(NSString *)key
{
// Create data object from the string
NSData *data = [string dataUsingEncoding:NSUTF8StringEncoding];
// Get pointer to data to obfuscate
char *dataPtr = (char *) [data bytes];
// Get pointer to key data
char *keyData = (char *) [[key dataUsingEncoding:NSUTF8StringEncoding] bytes];
// Points to each char in sequence in the key
char *keyPtr = keyData;
int keyIndex = 0;
// For each character in data, xor with current value in key
for (int x = 0; x < [data length]; x++)
{
// Replace current character in data with
// current character xor'd with current key value.
// Bump each pointer to the next character
*dataPtr = *dataPtr++ ^ *keyPtr++;
// If at end of key data, reset count and
// set key pointer back to start of key value
if (++keyIndex == [key length])
keyIndex = 0, keyPtr = keyData;
}
return [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
}
This works like a charm with all strings, but i've ran into a bit of a problem comparing the following results
NSLog([[self obfuscate:#"0000", #"maki"]); //Returns 0]<W
NSLog([[self obfuscate:#"0809", #"maki"]); //Returns 0]<W
As you can see, the two strings with numbers in, while different, return the same result! Whats gone wrong in the code i've attached to result in the same result for these two numbers?
Another example:
NSLog([self obfuscate:#"8000" withKey:#"maki"]); //Returns 8U4_
NSLog([self obfuscate:#"8290" withKey:#"maki"]); //Returns 8U4_ as well
I may be misunderstanding the concept of obfuscation, but I was under the impression that each unique string returns a unique obfuscated string!
Please help me fix this bug/glitch
Source of Code: http://iosdevelopertips.com/cocoa/obfuscation-encryption-of-string-nsstring.html
The problem is your last line. You create the new string with the original, unmodified data object.
You need to create a new NSData object from the modified dataPtr bytes.
NSData *newData = [NSData dataWithBytes:dataPtr length:data.length];
return [[NSString alloc] initWithData:newData encoding:NSUTF8StringEncoding];
But you have some bigger issues.
The calls to bytes returns a constant, read-only reference to the bytes in the NSData object. You should NOT be modifying that data.
The result of your XOR on the character data could, in theory, result in a byte stream that is no longer a valid UTF-8 encoded string.
The obfuscation algorithm that you have selected is based on XORing the data and the "key" values together. Generally, this is not very strong. Moreover, since XOR is symmetric, the results are very prone to producing duplicates.
Although your implementation is currently broken, fixing it would not be of much help in preventing the algorithm from producing identical results for different data: it is relatively straightforward to construct key/data pairs that produce the same obfuscated string - for example,
[self obfuscate:#"0123" withKey:#"vwxy"]
[self obfuscate:#"pqrs" withKey:#"6789"]
will produce identical results "FFJJ", even though both the strings and the keys look sufficiently different.
If you would like to "obfuscate" your strings in a cryptographically strong way, use a salted secure hash algorithm: it will produce very different results for even slightly different strings.
i've a problem..when i decrypt the data that is returned from my php page,
if the length of the string is less than 16, the char \0 is append to string.
Original string is: 100000065912248
I decrypt the encrypted string with this function:
#define FBENCRYPT_ALGORITHM kCCAlgorithmAES128
#define FBENCRYPT_BLOCK_SIZE kCCBlockSizeAES128
#define FBENCRYPT_KEY_SIZE kCCKeySizeAES256
+ (NSData*)decryptData:(NSData*)data key:(NSData*)key iv:(NSData*)iv;
{
NSData* result = nil;
// setup key
unsigned char cKey[FBENCRYPT_KEY_SIZE];
bzero(cKey, sizeof(cKey));
[key getBytes:cKey length:FBENCRYPT_KEY_SIZE];
// setup iv
char cIv[FBENCRYPT_BLOCK_SIZE];
bzero(cIv, FBENCRYPT_BLOCK_SIZE);
if (iv) {
[iv getBytes:cIv length:FBENCRYPT_BLOCK_SIZE];
}
// setup output buffer
size_t bufferSize = [data length] + FBENCRYPT_BLOCK_SIZE;
void *buffer = malloc(bufferSize);
int length = [data length];
// do decrypt
size_t decryptedSize = 0;
CCCryptorStatus cryptStatus = CCCrypt(kCCDecrypt,
FBENCRYPT_ALGORITHM,
0,
cKey,
FBENCRYPT_KEY_SIZE,
cIv,
[data bytes],
[data length],
buffer,
bufferSize,
&decryptedSize);
if (cryptStatus == kCCSuccess) {
result = [NSData dataWithBytesNoCopy:buffer length:decryptedSize];
} else {
free(buffer);
NSLog(#"[ERROR] failed to decrypt| CCCryptoStatus: %d", cryptStatus);
}
return result;
}
I send a nil "iv" parameter to the function and after i use "cIv" in function, and it contain this:
The result is exactly, but the length of string is 16 instead of 15 (string: 100000065912248). In fact, the last character is \0.
Why? how can i solve?
EDIT:
PHP encrypt function:
function encrypt($plaintext) {
$key = 'a16byteslongkey!a16byteslongkey!';
$base64encoded_ciphertext = base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $key, $plaintext, MCRYPT_MODE_CBC));
$base64encoded_ciphertext = trim($base64encoded_ciphertext);
return $base64encoded_ciphertext;
}
AES is a block cypher and encrypts/decrypts blocks of length 128 bits (16 bytes). So if the data is not a block size some padding must be added. The most popular and supported by Apple is PKCS7.
Interfacing with PHP one must consider padding and possible base64 encoding.
The solution is to use the same padding on both sides, PHP and iOS.
AES always operates on 16 bytes, there is no option--so, if you have 15 bytes a byte is going to have to be added, that is padding. From what I understand (not much about PHP encryption) PHP does not do true PCKS7padding and it is best to pad yourself. Lookup PKCS7 in Wikipedia.
You should be OK with zero padding (the default) if you only operate on strings, but I would recommend PKCS#7 padding, if only for interoperability reasons.
With zero padding the plaintext is padded with 00 valued bytes, but only if required. This is different from PKCS#7 padding, which is always deployed. After decryption you can use the trim function on the resulting plaintext after decryption. You should then get the original string.
This obviously wont work on binary data because it may end with a character that is removed by the trim function. Beware that trim in PHP seems to strip off 00 bytes. This is not a given, officially 00 is not whitespace, even though it is treated that way by many runtimes.
You have to remove padding from the decrypted data
function removePadding($decryptedText){
$strPad = ord($decryptedText[strlen($decryptedText)-1]);
$decryptedText= substr($decryptedText, 0, -$strPad);
return $decryptedText;
}
I’m trying to write a simple encryption routine in C using OpenSSL and I’ve found something strange. I’m not a C guru nor OpenSSL professional. So I might have made a mistake.
The function is as follows
char *rsa_encrypt(char *data)
{
const char xponent_in_hex[] = "010001";
const char modulus_in_hex[] = "D0BA16F11907E7B0819705A15264AC29BEE9F1EC5F22642992
D3E27100B7F212864A624A12FFB6D531712B0B0225AAD0C2E313D077A7DB2A5A33483EEFF41A9D";
BIGNUM *xponent = NULL;
BIGNUM *modulus = NULL;
BN_hex2bn(&xponent, xponent_in_hex);
BN_hex2bn(&modulus, modulus_in_hex);
RSA *rsa = RSA_new();
rsa->e = xponent;
rsa->n = modulus;
rsa->iqmp = NULL;
rsa->d = NULL;
rsa->p = NULL;
rsa->q = NULL;
char encoded[512] = { 0 };
RSA_public_encrypt(
strlen(data),
(const unsigned char *)data,
(unsigned char *)encoded,
rsa,
RSA_PKCS1_OAEP_PADDING
);
RSA_free(rsa);
return (encoded);
}
int _tmain(int argc, _TCHAR* argv[])
{
printf("%s\n", base64_encode(rsa_encrypt("ABC")));
printf("%s\n", base64_encode(rsa_encrypt("ABC")));
printf("%s\n", base64_encode(rsa_encrypt("ABC")));
}
I call that function on same data several times and it generates different value each time it is called. It is apparently wrong because exponent and modulus for created RSA structure are constant and input data is the same in each call.
So why RSA_public_encrypt behaves that way?
How should I generate a public key for RSA encryption based on exponent and modulus?
And where I’ve made mistake?
This is actually correct, and you're not making a mistake. Your confusion stems from the RSA_PKCS1_OAEP_PADDING parameter to RSA_public_encrypt.
The RSA encryption process is actually:
Take the plaintext (plain) and encode it , producing encoded_plain.
Encrypt encoded_plain.
(As you would expect, the decryption process requires you to both decrypt the value, and then decode the message).
The RSA_PKCS1_OAEP_PADDING parameter specifies how the plaintext should be encoded (that OAEP encoding should be used).
A simplified explanation is that OAEP padding uses some random values for the padding, so both xxxxxxxABC and yyyyyyyABC and zzzzzzzABC are all valid encoded_plain values for your plaintext, and those encoded_plain encrypts to a different value. If you perform the corresponding decrypt (and decode, by passing the same RSA_PKCS1_OAEP_PADDING paramater to RSA_private_decrypt) operation, you should still get "ABC" as an output for each of the ciphertexts, as the padding stripped off all three.
(If you want to be precise, the OAEP encoding scheme is more complicated that, see RFC 3447 section 7.1.1. But those are probably details you don't care about.)
The scope of encoded ends at the end of the rsa_encrypt function. Your return pointer will point to an invalid area of memory, that might not contain what you expect anymore because somebody else (another thread, for example) wrote over it. The answer explaining the padding is correct.