mirror of
https://github.com/deneraraujo/OpenVPNAdapter.git
synced 2026-03-06 00:00:02 +08:00
Implement parsing private key DER and PEM data
This commit is contained in:
@@ -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
|
||||
|
||||
Reference in New Issue
Block a user