Convert NSData to String?

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.

184609 次浏览

目标 C

你可以使用(见 NSString 类引用)

- (id)initWithData:(NSData *)data encoding:(NSStringEncoding)encoding

例如:

NSString *myString = [[NSString alloc] initWithData:myData encoding:NSUTF8StringEncoding];

注意 : 请注意 NSData值必须对指定的编码有效(上面示例中的 UTF-8) ,否则将返回 nil:

Returns nil if the initialization fails for some reason (for example if data does not represent valid data for encoding).

斯威夫特先驱3.0

String(data: yourData, encoding: NSUTF8StringEncoding)

Swift 3.0向前发展

String(data: yourData, encoding: .utf8)

参见 String#init(data:encoding:) Reference

我相信你的“ P”是 dataWithBytes 参数

NSData *keydata = [NSData dataWithBytes:P length:len];

应该是“轻松”

NSData *keydata = [NSData dataWithBytes:buf length:len];

因为 i2d _ PrivateKey 将指向输出缓冲区 p 的指针放在缓冲区的末尾并等待进一步的输入,而 buf 仍然指向缓冲区的开头。

下面的代码适用于我,pkey 是指向 EVP _ PKEY 的指针:

unsigned char *buf, *pp;
int len = i2d_PrivateKey(pkey, NULL);
buf = OPENSSL_malloc(len);
pp = buf;
i2d_PrivateKey(pkey, &pp);


NSData* pkeyData = [NSData dataWithBytes:(const void *)buf length:len];
DLog(@"Private key in hex (%d): %@", len, pkeyData);

使用以下命令并检查 mypkey.pem 的输出之后,可以使用在线转换器将二进制数据转换为基数64(http://tomeko.net/online_tools/hex_to_base64.php?lang=en) ,并将其与证书文件中的私钥进行比较:

openssl pkcs12 -in myCert.p12 -nocerts -nodes -out mypkey.pem

I referenced your question and 本执行副总裁职能的网站 for my answer.

Prior Swift 3.0 :

String(data: yourData, encoding: NSUTF8StringEncoding)

对于 Swift 4.0:

String(data: yourData, encoding: .utf8)

斯威夫特5:

String(data: data!, encoding: String.Encoding.utf8)

斯威夫特3:

String(data: data, encoding: .utf8)

将任意 NSData 转换为 NSString 的一个简单方法是 base64编码它。

NSString *base64EncodedKey = [keydata base64EncodedStringWithOptions: NSDataBase64Encoding64CharacterLineLength];

然后您可以将其存储到数据库中以便以后重用。