在iPhone应用程序中实现HMAC加密算法

Abh*_*nav 11 iphone encryption cocoa-touch objective-c ios

我想为我的iPhone应用程序实现HMAC加密算法.任何示例代码都会有所帮助.另外,请指导我简要实施相同的内容.

mor*_*ion 21

使用Common Crypto功能.该文件是在手册页,所以你需要去寻找它一下.它们位于iOS和Mac OS X上的libSystem中,因此无需在项目中添加其他库或框架.从下面的示例中可以看出,API与OpenSSL非常相似.

如果您真的对加密感兴趣,而不是验证数据,Common Crypto具有执行AES和3DES(和DES,但不使用它,它对于现代需求来说太弱)的功能.有关详细信息,请查看CCCryptor手册页.

以下示例等同于运行openssl dgst -md5 -hmac secret < myfile.txt.首先初始化CCHmacContext,然后只要有数据进行身份验证就调用CCHmacUpdate.当您读取所有字节时,请调用CCHmacFinal以将HMAC放入缓冲区.我提供了一种粗略的方法来将HMAC字节转换为可打印的十六进制.

#include <CommonCrypto/CommonHMAC.h>

#include <sys/types.h>
#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>

extern int      errno;

    int
main( int ac, char *av[] )
{
    CCHmacContext    ctx;
    char             *key = "secret";
    char             buf[ 8192 ];
    unsigned char    mac[ CC_MD5_DIGEST_LENGTH ];
    char             hexmac[ 2 * CC_MD5_DIGEST_LENGTH + 1 ];
    char             *p;
    int              fd;
    int              rr, i;

    if ( ac != 2 ) {
        fprintf( stderr, "usage: %s path\n", av[ 0 ] );
        exit( 1 );
    }

    if (( fd = open( av[ 1 ], O_RDONLY )) < 0 ) {
        fprintf( stderr, "open %s: %s\n", av[ 1 ], strerror( errno ));
        exit( 2 );
    }

    CCHmacInit( &ctx, kCCHmacAlgMD5, key, strlen( key ));

    while (( rr = read( fd, buf, sizeof( buf ))) > 0 ) {
        CCHmacUpdate( &ctx, buf, rr );
    }
    if ( rr < 0 ) {
        perror( "read" );
        exit( 2 );
    }
    CCHmacFinal( &ctx, mac );

    (void)close( fd );

    p = hexmac;
    for ( i = 0; i < CC_MD5_DIGEST_LENGTH; i++ ) {
        snprintf( p, 3, "%02x", mac[ i ] );
        p += 2;
    }

    printf( "%s\n", hexmac );

    return( 0 );
}
Run Code Online (Sandbox Code Playgroud)

  • 感谢那!我在我们的博客上对此进行了总结,并为NSString制作了一个类别以供进一步使用.请访问http://blog.blackwhale.at/?p=801查看.欢呼声,安卡 (2认同)