I am storing a openssl private Key EVP_PKEY as nsdata. For this I am serializing into a byte stream using the code below
unsigned char *buf, *p;
int len;
len = i2d_PrivateKey(pkey, NULL);
buf = OPENSSL_malloc(len);
p = buf;
i2d_PrivateKey(pkey, &p);
where pkey is of type EVP_PKEY. Then I am storing the bytes from buffer 'p' as an NSData using the line given below
NSData *keydata = [NSData dataWithBytes:P length:len];
Now I am converting it to a NSString using the code given below but when i print it into console its giving some other characters.
NSString *content =[ NSString stringWithCString:[keydata bytes] encoding:NSUTF8StringEncoding];
Could someone help?
Basically I want to store the EVP_PKEY into a sqlite database
am I on the right track? Thanks.
Swift:
Prior Swift 3.0 :
For Swift 4.0:
Objective-C
You can use ( see NSString Class Reference )
Example :
Remark: Please notice the
NSData
value must be valid for the encoding specified (UTF-8 in the example above), otherwisenil
will be returned:Prior Swift 3.0
Swift 3.0
See String#init(data:encoding:) Reference
A simple way to convert arbitrary NSData to NSString is to base64 encode it.
You can then store it into your database for reuse later. Just decode it back to NSData.
Swift 3:
I believe your "P" as the dataWithBytes param
should be "buf"
since i2d_PrivateKey puts the pointer to the output buffer p at the end of the buffer and waiting for further input, and buf is still pointing to the beginning of your buffer.
The following code works for me where pkey is a pointer to an EVP_PKEY:
You can use an online converter to convert your binary data into base 64 (http://tomeko.net/online_tools/hex_to_base64.php?lang=en) and compare it to the private key in your cert file after using the following command and checking the output of mypkey.pem:
I referenced your question and this EVP function site for my answer.