从 NSString 创建 SHA1 哈希值
如何从 NSString
创建 SHA1。
假设 NSString 设置为:
NSString *message = @"Message";
我可以使用 PHP 通过 sha($message)
创建 SHA1 哈希。但不幸的是,它在 Objective-C 中并不是这样工作的。
How can I create a SHA1 from a NSString
.
Let's say the NSString is set up as:
NSString *message = @"Message";
I can use PHP to create a SHA1 hash with sha($message)
. But unfortunately it doesn't work like that within Objective-C.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
我在 NSString 上的一个类别中有这个(可在 https://github.com/hypercrypt/NSString-Hashes< /a>):
从 Xcode 10.0 开始,您应该使用
import CommonCrypto
来代替,因为它现在在 Swift 中原生可用!如果您最近迁移到 Xcode 10.0 并使用旧方法,这可能是您进行更改的提示:I have this in a category on NSString (available at https://github.com/hypercrypt/NSString-Hashes):
Starting with Xcode 10.0, you should use
import CommonCrypto
instead since it is now natively available in Swift! If you have recently migrated to Xcode 10.0 and use the old approach, this can be your cue to make the change:我非常喜欢 hypercrypt 的答案,但我被鼓励发表评论。
您可以查看
CC_SHA1
,或这个相关的SO问题。
I quite like hypercrypt's answer, but I've been encouraged to post my comment.
You could look at
CC_SHA1
, or this related SO question.我花了一段时间才将 @hypercrypt 解决方案移植到 Swift,所以我决定与可能有相同问题的其他人分享。
需要注意的一件重要事情是,您需要 CommonCrypto 库,但该库没有 Swift 模块。最简单的解决方法是将其导入到桥接标头中:
导入后,您不需要任何其他内容。只需使用提供的字符串扩展:
请注意,我的解决方案不会影响原始帖子中
NSMutableString
的保留容量。不过我怀疑有人会看到其中的区别:)It took me a while to port @hypercrypt solution to Swift so I decided to share it with others that might have the same problem.
One important thing to note is that you need CommonCrypto library, but that library does not have Swift module. The easiest workaround is to import it in your bridging header:
Once imported there, you do not need anything else. Just use String extension provided:
Notice that my solution does not take effect of reserving capacity what
NSMutableString
has in original post. However I doubt anyone will see the difference :)试试这个:
try this:
我看到这篇文章中的答案有一些不同的可能的改进。
这是我的解决方案, 改编自优秀的 SocketRocket 库的 SRHash。米:
I'm seeing a few different possible improvements to the answers in this post.
Here's my solution, adapted from the excellent SocketRocket library's SRHash.m:
这是一个简洁且高度优化的 NSString类别:
Here's a concise and highly optimized NSString category: