如何在 Cocoa/Objective-C 中将文件编码和解码为 Base64 [英] How to encode and decode Files as Base64 in Cocoa / Objective-C

查看:32
本文介绍了如何在 Cocoa/Objective-C 中将文件编码和解码为 Base64的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在尝试让一个小型肥皂客户端工作,其中包括在请求的 xml 中发送证书文件.

I am currently trying to get a small soap client to work, which includes to send a certificate file within the xml of the request.

我可以毫不费力地将文件转换为 NSData 对象 - 但是我必须将其转换为一些 Base64 字符串.环境是Mac OSX,Xcode 4.3.

I have no trouble getting the file into an NSData object - but then I have to convert it to some Base64 String. Environment is Mac OSX, Xcode 4.3.

我发现很多较早的帖子都在处理这个问题 - 但我发现最好的是一些使用 OpenSSL 库的代码,其中包含大量已弃用的方法.

I have found a lot of older posting dealing with that - but the best I found was some code that made use of OpenSSL libs and where containing loads of deprecated methods.

所以,我的问题如下:有没有比使用 OpenSSL 库更好的方法?如果有,您是否有一些 URL 或更新的代码片段?

So, my question is as follows: Is there a better way than to use the OpenSSL libs? If yes, do you perchance have some URL or more recent code scraps?

如果不是,我想有一些可以推荐的处理 Base64 的项目.毕竟 Base64 并不少见.

If no, I guess there is some project out there which deals with Base64 that can be recommended. After all Base64 is not that uncommon.

感谢您的帮助!

推荐答案

这是使用 CommonCrypto 完成的 base64 编码:

Here is a base64 encoding done with CommonCrypto:

很简单的代码,归类也不难

it is very easy code, it would not be difficult to put it in a category

如果您将其添加到您的项目中,您还需要添加 Security.framework

if you add this to your project you need also to add the Security.framework

#include <CoreFoundation/CoreFoundation.h>
#include <Security/Security.h>

static NSData *base64helper(NSData *input, SecTransformRef transform)
{
    NSData *output = nil;

    if (!transform)
        return nil;

    if (SecTransformSetAttribute(transform, kSecTransformInputAttributeName, input, NULL))
        output = (NSData *)SecTransformExecute(transform, NULL);

    CFRelease(transform);

    return [output autorelease];
}

NSString *base64enc(NSData *input)
{
    SecTransformRef transform = SecEncodeTransformCreate(kSecBase64Encoding, NULL);

    return [[[NSString alloc] initWithData:base64helper(input, transform) encoding:NSASCIIStringEncoding] autorelease];
}

NSData *base64dec(NSString *input)
{
    SecTransformRef transform = SecDecodeTransformCreate(kSecBase64Encoding, NULL);

    return base64helper([input dataUsingEncoding:NSASCIIStringEncoding], transform);
}

这篇关于如何在 Cocoa/Objective-C 中将文件编码和解码为 Base64的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆