在iPhone应用程序中实现HMAC加密算法
我想为我的 iPhone 应用程序实现 HMAC 加密算法。任何示例代码都会很有帮助。另外,请指导我简要实施相同的内容。
I want to implement HMAC encryption algorithm for my iPhone application. Any sample code will really help. Also, please guide me with brief implementation of the same.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
使用通用加密函数。 文档 在手册页中,因此您需要稍微寻找一下。它们位于 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 字节转换为可打印十六进制的粗略方法。Use the Common Crypto functions. The documentation is in man pages, so you'll need to hunt for it a bit. They're in libSystem on iOS and Mac OS X, so no need to add another library or framework to your project. As you can see from the example below, the API is very similar to OpenSSL's.
If you are actually interested in encrypting, as opposed to authenticating data, Common Crypto has functions to perform AES and 3DES (and DES, but don't use it, it's far too weak for modern needs). Take a look at the CCCryptor man page for details.
The example below is equivalent to running
openssl dgst -md5 -hmac secret < myfile.txt
. Start by initializing the the CCHmacContext, and then call CCHmacUpdate as long as you have data to authenticate. When you've read all the bytes, call CCHmacFinal to get the HMAC into a buffer. I've provided a crude method to convert the HMAC bytes into printable hex.HMAC 不是一种加密机制,而是一种身份验证摘要。它使用底层消息摘要函数(例如 SHA-1、SHA-256、MD5 等)和密钥来生成可用于验证数据的代码。
生成 HMAC 摘要非常简单。以下是 RFC2104 的描述(来自 Wikipedia)
设:
然后 HMAC(K, m) 的数学定义为:
HMAC(K,m) = H((K ⊕ opad) | H((K ⊕ ipad) | m))。
对于底层摘要函数,您可以使用 OpenSSL 的 C 实现之一。事实上,它还有 HMAC 的 C 实现,您可以按原样使用。
HMAC is not an encryption mechanism, but an authentication digest. It uses an underlying message digest function such as SHA-1, SHA-256, MD5 etc, with a secret key to generate a code that can be used to authenticate data.
Generating an HMAC digest is extremely simple. Here is the description from RFC2104 (via Wikipedia)
Let:
Then HMAC(K,m) is mathematically defined by:
HMAC(K,m) = H((K ⊕ opad) | H((K ⊕ ipad) | m)).
For the underlying digest function you can help yourself to one of the C implementations from OpenSSL. In fact it also has a C implementation of HMAC that you can probably just use as is.