简体   繁体   English

如何使用OpenPGP.js在Objective-C中加密/解密PGP消息

[英]How to encrypt/decrypt a PGP message in Objective-C using OpenPGP.js

I want to encrypt a message using a armored key. 我想使用铠装密钥来加密消息。 I want to accomplish this using OpenPGP.js. 我想使用OpenPGP.js完成此操作。

I'm answering my own question. 我在回答我自己的问题。 I figured this out a while ago and wanted to share, since I couldn't find anything similar. 不久前,我发现了这个问题,并想分享,因为找不到类似的东西。

Here is how encryption should look like: 这是加密的样子:

+ (NSString *)encryptMessage:(NSString *)message
                  forKey:(NSString *)key {
NSString *result = nil;

UIWebView *webView = [[UIWebView alloc] init];

NSString *path = [[NSBundle mainBundle] pathForResource:@"openpgp" ofType:@"js"];
NSString *content = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];
NSString *resultOfPGPLibEval = [webView stringByEvaluatingJavaScriptFromString:content];
if ([resultOfPGPLibEval isEqualToString:@"true"]) {//library was loaded successfully
    JSContext *context =  [webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"]; // Undocumented access
    context[@"key"] = key;
    context[@"message"] = message;
    [context evaluateScript:@"var openpgp = window.openpgp; var publicKey = openpgp.key.readArmored(key);var pgpMessage = openpgp.encryptMessage(publicKey.keys, message);"];
    JSValue *val2 = context[@"pgpMessage"];
    result = val2.toString;
}

return result;

} }

Notice that you must have the OpenPGP library in the bundle, in this example it is named 'openpgp.js'. 请注意,捆绑包中必须包含OpenPGP库,在此示例中,该库名为“ openpgp.js”。 Also the key in this example is armored, so keep that in mind. 另外,此示例中的键是铠装的,因此请记住这一点。

I feel that while wasteful to create a WebView just for one encryption round, it is more secure since it will fall out of scope as soon as the result is returned with it it's context. 我觉得虽然只为一个加密回合创建WebView是浪费时间,但它更加安全,因为一旦将结果连同上下文一起返回,它将超出范围。 Keep in mind that I'm not a security guy, so take that with a grain of salt. 请记住,我不是安全人员,所以要加一点盐。

I hope this helps someone. 我希望这可以帮助别人。

但是,如果您只想在没有javascript桥接的情况下进行加密,则可以尝试使用ObjectivePGP库。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM