简体   繁体   中英

OpenSSL encrypting with public pem in objective-c

I have compiled and built openssl to my iOS project,

but struggling in objective-c with writing an equivalent code to this command line:

openssl rsautl -encrypt -inkey publicKey.pem -pubin -in textfile.txt -out encrypted.bin

How can I achieve this?

hi i have been the same problem finally I found what I was searching for. What I need like CodeInChaos say is my self-signed certificate. With it my code works fine. To do it I use this command:

openssl req -x509 -out public_key.der -outform der -new -newkey rsa:1024 -keyout private_key.pem -days 3650

I have found very usefull this post:

http://blog.iamzsx.me/show.html?id=155002

It responds to a lot of questions. Is not in english but google translated well so it's not a big problem.

I have did this little function to encrypt data with code I found and my own. I have my public key in my bundle and I return the message in a NSDaa encoded in base64 to send it to the server:

+ (NSString *)encryptWithPublicKeyMessage:(NSString *) message
{
NSLog(@"encrypting...");
NSData *inputData = [message dataUsingEncoding:NSUTF8StringEncoding];
const void *bytes = [inputData bytes];
int length = [inputData length];
uint8_t *plainText = malloc(length);
memcpy(plainText, bytes, length);

/* Open and parse the cert*/
NSData *certData = [NSData dataWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"public_key" ofType:@"der"]];
SecCertificateRef cert = SecCertificateCreateWithData(kCFAllocatorDefault, (__bridge CFDataRef)certData);
SecPolicyRef policy = SecPolicyCreateBasicX509();
SecTrustRef trust;
OSStatus status = SecTrustCreateWithCertificates(cert, policy, &trust);

/* You can ignore the SecTrustResultType, but you have to run SecTrustEvaluate
 * before you can get the public key */
SecTrustResultType trustResult;
if (status == noErr) {
    status = SecTrustEvaluate(trust, &trustResult);
}

/* Now grab the public key from the cert */
SecKeyRef publicKey = SecTrustCopyPublicKey(trust);

/* allocate a buffer to hold the cipher text */
size_t cipherBufferSize;
uint8_t *cipherBuffer; 
cipherBufferSize = SecKeyGetBlockSize(publicKey);
cipherBuffer = malloc(cipherBufferSize);

/* encrypt!! */
SecKeyEncrypt(publicKey, kSecPaddingPKCS1, plainText, length, cipherBuffer, &cipherBufferSize);


 NSData *d = [NSData dataWithBytes:cipherBuffer length:cipherBufferSize];

/* Free the Security Framework Five! */
CFRelease(cert);
CFRelease(policy);
CFRelease(trust);
CFRelease(publicKey);
free(cipherBuffer);
NSLog(@"encrypted");
return [d encodeBase64ForData];
}

I hope it helps at me it takes my a while to find the correct code

So I resolved my problem, here is the function to my question that encrypts an NSString:

I modified the code from the code in this question: send RSA public key to iphone and use it to encrypt

(Also at the end of my code I use QSUtilities to encode the message in base64)

#pragma mark Encryption using OpenSSL
+ (NSString *)EncryptMessage:(NSString *)message {
NSString *path = [[NSBundle mainBundle] pathForResource:@"pubkey" ofType:@"pem"];
FILE *pubkey = fopen([path cStringUsingEncoding:1], "r");
if (pubkey == NULL) {
    NSLog(@"duh: %@", [path stringByAppendingString:@" not found"]);
    return NULL;
}

RSA *rsa = PEM_read_RSA_PUBKEY(pubkey, NULL, NULL, NULL);
if (rsa == NULL) {
    NSLog(@"Error reading RSA public key.");
    return NULL;
}

const char *msgInChar = [message UTF8String];
unsigned char *encrypted = (unsigned char *) malloc(512); //I'm not so sure about this size
int bufferSize = RSA_public_encrypt(strlen(msgInChar), (unsigned char *)msgInChar, encrypted, rsa, RSA_PKCS1_PADDING);
if (bufferSize == -1) {
    NSLog(@"Encryption failed");
    return NULL;
}

NSData *data = [NSData dataWithBytes:(const void *)encrypted length:512]; //I'm not so sure about this length
NSString *result = [QSStrings encodeBase64WithData:data];

free(rsa);
fclose(pubkey);
free(encrypted);

return result;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM