美文网首页
HmacSHA256

HmacSHA256

作者: 跬步千里_LenSky | 来源:发表于2018-04-09 23:43 被阅读34次
    #import <CommonCrypto/CommonDigest.h>  
    #import <CommonCrypto/CommonHMAC.h>  
      
    @implementation HmacUtils  
      
    /** 
     *  加密方式,MAC算法: HmacSHA256 
     * 
     *  @param plaintext 要加密的文本 
     *  @param key       秘钥 
     * 
     *  @return 加密后的字符串 
     */  
    + (NSString *)hmac:(NSString *)plaintext withKey:(NSString *)key  
    {  
        const charchar *cKey  = [key cStringUsingEncoding:NSASCIIStringEncoding];  
        const charchar *cData = [plaintext cStringUsingEncoding:NSASCIIStringEncoding];  
        unsigned char cHMAC[CC_SHA256_DIGEST_LENGTH];  
        CCHmac(kCCHmacAlgSHA256, cKey, strlen(cKey), cData, strlen(cData), cHMAC);  
        NSData *HMACData = [NSData dataWithBytes:cHMAC length:sizeof(cHMAC)];  
        const unsigned charchar *buffer = (const unsigned charchar *)[HMACData bytes];  
        NSMutableString *HMAC = [NSMutableString stringWithCapacity:HMACData.length * 2];  
        for (int i = 0; i < HMACData.length; ++i){  
            [HMAC appendFormat:@"%02x", buffer[i]];  
        }  
          
        return HMAC;  
    }  
      
    @end  

    相关文章

      网友评论

          本文标题:HmacSHA256

          本文链接:https://www.haomeiwen.com/subject/nbgwhftx.html