base64编码、解码
2017-04-27 本文已影响50人
CoderCurtis
PS: Base64是一种数据编码方式,目的是让数据符合传输协议的要求,有些人误用它进行数据加密
//base64编码
- (NSString *)base64EncodedStringWithString:(NSString *)string
{
NSData *data = [string dataUsingEncoding:NSUTF8StringEncoding];
return [data base64EncodedStringWithOptions:0];
}
//base64解码
- (NSString *)base64DecodedStringWithString:(NSString *)string
{
NSData *data = [[NSData alloc]initWithBase64EncodedString:string options:0];
return [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
}
调用:
//编码
NSString *encodeStr = [self base64EncodedStringWithString:@"Hello, World!"];
NSLog(@"%@", encodeStr);
//解码
NSString *decodeStr = [self base64DecodedStringWithString:encodeStr];
NSLog(@"%@", decodeStr);
Output:
SGVsbG8sIFdvcmxkIQ==
Hello, World!