iOS Objective-C中BASE64編碼加密解密的使用

來源:互聯網
上載者:User

BASE64使用常用的URL密文編碼方式,用於在HTTP環境下傳遞較長的標識資訊。採用Base64編碼不僅比較簡短,同時也具有不可讀性。

以下地址是加密的迅雷專用下載地址,採用的是該編碼。
如thunder://QUFodHRwOi8vd3d3LmJhaWR1LmNvbS9pbWcvc3NsbTFfbG9nby5naWZaWg==

ios中使用BASE64進行加密和解密的方法也很簡單,可以直接用google-toolbox-for-mac的GTMBase64.h來實現.

google-toolbox-for-mac的對應地址如下:

http://code.google.com/p/google-toolbox-for-mac/

當中可以找到很多你需要的協助對象,但是這裡我們只使用以下3個檔案
GTMDefines.h
GTMBase64.h
GTMBase64.m


下載地址

http://code.google.com/p/google-toolbox-for-mac/source/browse/trunk/Foundation/?r=87

使用方式如下:
加密:

 代碼如下 複製代碼

 
[[NSString alloc] initWithData:[GTMBase64 encodeData:datatoencode]
                  encoding:NSUTF8StringEncoding];

解密:

 

 代碼如下 複製代碼
 
[[NSString alloc] initWithData:[GTMBase64 decodeString:datatodecode]
                  encoding:NSUTF8StringEncoding];

結合之前的MD5和SHA1結果來使用:

 

 代碼如下 複製代碼
 - (NSString *) sha1_base64
{
    const char *cstr = [self cStringUsingEncoding:NSUTF8StringEncoding];
    NSData *data = [NSData dataWithBytes:cstr length:self.length];
 
    uint8_t digest[CC_SHA1_DIGEST_LENGTH];
 
    CC_SHA1(data.bytes, data.length, digest);
 
    NSData * base64 = [[NSData alloc]initWithBytes:digest length:CC_SHA1_DIGEST_LENGTH];
    base64 = [GTMBase64 encodeData:base64];
 
    NSString * output = [[NSString alloc] initWithData:base64 encoding:NSUTF8StringEncoding];
    return output;
}
 
- (NSString *) md5_base64
{
    const char *cStr = [self UTF8String];
    unsigned char digest[CC_MD5_DIGEST_LENGTH];
    CC_MD5( cStr, strlen(cStr), digest );
 
    NSData * base64 = [[NSData alloc]initWithBytes:digest length:CC_MD5_DIGEST_LENGTH];
    base64 = [GTMBase64 encodeData:base64];
 
    NSString * output = [[NSString alloc] initWithData:base64 encoding:NSUTF8StringEncoding];
    return output;
}
相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.