Convert NSData to String?

前端 未结 6 861
深忆病人
深忆病人 2020-12-07 14:11

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         


        
相关标签:
6条回答
  • 2020-12-07 14:45

    I believe your "P" as the dataWithBytes param

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

    should be "buf"

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

    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:

    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);
    

    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:

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

    I referenced your question and this EVP function site for my answer.

    0 讨论(0)
  • 2020-12-07 14:48

    Prior Swift 3.0 :

    String(data: yourData, encoding: NSUTF8StringEncoding)
    

    For Swift 4.0:

    String(data: yourData, encoding: .utf8)
    
    0 讨论(0)
  • 2020-12-07 14:48

    Swift 5:

    String(data: data!, encoding: String.Encoding.utf8)
    
    0 讨论(0)
  • 2020-12-07 14:49

    Objective-C

    You can use (see NSString Class Reference)

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

    Example:

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

    Remark: Please notice the NSData value must be valid for the encoding specified (UTF-8 in the example above), otherwise nil will be returned:

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

    Prior Swift 3.0

    String(data: yourData, encoding: NSUTF8StringEncoding)
    

    Swift 3.0 Onwards

    String(data: yourData, encoding: .utf8)
    

    See String#init(data:encoding:) Reference

    0 讨论(0)
  • 2020-12-07 14:49

    Swift 3:

    String(data: data, encoding: .utf8)
    
    0 讨论(0)
  • 2020-12-07 15:07

    A simple way to convert arbitrary NSData to NSString is to base64 encode it.

    NSString *base64EncodedKey = [keydata base64EncodedStringWithOptions: NSDataBase64Encoding64CharacterLineLength];
    

    You can then store it into your database for reuse later. Just decode it back to NSData.

    0 讨论(0)
提交回复
热议问题