From 6d0b1d28b084e614a58c6941bdd66d2c430f1b27 Mon Sep 17 00:00:00 2001 From: Sergey Abramchuk Date: Thu, 7 Sep 2017 14:07:42 +0300 Subject: [PATCH] Implement parsing private key DER and PEM data --- OpenVPN Adapter/OpenVPNPrivateKey.m | 38 +++++++++++++++++++++++++---- 1 file changed, 33 insertions(+), 5 deletions(-) diff --git a/OpenVPN Adapter/OpenVPNPrivateKey.m b/OpenVPN Adapter/OpenVPNPrivateKey.m index 924b425..4963e3f 100644 --- a/OpenVPN Adapter/OpenVPNPrivateKey.m +++ b/OpenVPN Adapter/OpenVPNPrivateKey.m @@ -14,7 +14,7 @@ @interface OpenVPNPrivateKey () -@property (nonatomic, assign) mbedtls_pk_context *key; +@property (nonatomic, assign) mbedtls_pk_context *ctx; @end @@ -23,8 +23,8 @@ - (instancetype)init { self = [super init]; if (self) { - self.key = malloc(sizeof(mbedtls_pk_context)); - mbedtls_pk_init(self.key); + self.ctx = malloc(sizeof(mbedtls_pk_context)); + mbedtls_pk_init(self.ctx); } return self; } @@ -32,18 +32,46 @@ + (nullable OpenVPNPrivateKey *)keyWithPEM:(NSData *)pemData password:(NSString *)password error:(out NSError **)error { OpenVPNPrivateKey *key = [OpenVPNPrivateKey new]; + NSString *pemString = [[NSString alloc] initWithData:pemData encoding:NSUTF8StringEncoding]; + + int result = mbedtls_pk_parse_key(key.ctx, (const unsigned char *)pemString.UTF8String, pemData.length + 1, (const unsigned char *)password.UTF8String, password.length + 1); + if (result < 0) { + if (error) { + NSString *reason = [NSError reasonFromResult:result]; + *error = [NSError errorWithDomain:OpenVPNIdentityErrorDomain code:result userInfo:@{ + NSLocalizedDescriptionKey: @"Failed to read PEM data.", + NSLocalizedFailureReasonErrorKey: reason + }]; + } + + return nil; + } + return key; } + (nullable OpenVPNPrivateKey *)keyWithDER:(NSData *)derData password:(NSString *)password error:(out NSError **)error { OpenVPNPrivateKey *key = [OpenVPNPrivateKey new]; + int result = mbedtls_pk_parse_key(key.ctx, derData.bytes, derData.length, (const unsigned char *)password.UTF8String, password.length + 1); + if (result < 0) { + if (error) { + NSString *reason = [NSError reasonFromResult:result]; + *error = [NSError errorWithDomain:OpenVPNIdentityErrorDomain code:result userInfo:@{ + NSLocalizedDescriptionKey: @"Failed to read DER data.", + NSLocalizedFailureReasonErrorKey: reason + }]; + } + + return nil; + } + return key; } - (void)dealloc { - mbedtls_pk_free(self.key); - free(self.key); + mbedtls_pk_free(self.ctx); + free(self.ctx); } @end