如何在Swift中使用SHA1哈希NSString?

eimct9ow  于 2023-03-22  发布在  Swift
关注(0)|答案(8)|浏览(431)

在objective-c中,它看起来像这样:

#include <sys/xattr.h>

@implementation NSString (reverse)

-(NSString*)sha1
{
    NSData *data = [self dataUsingEncoding:NSUTF8StringEncoding];
    uint8_t digest[CC_SHA1_DIGEST_LENGTH];
    CC_SHA1(data.bytes, (int)data.length, digest);
    NSMutableString *output = [NSMutableString stringWithCapacity:CC_SHA1_DIGEST_LENGTH * 2];
    for (int i = 0; i < CC_SHA1_DIGEST_LENGTH; i++)
        [output appendFormat:@"%02x", digest[i]];
    return output;
}

@end

我需要这样的东西与Swift,这是可能的吗?
请展示工作示例。

8i9zcol2

8i9zcol21#

你的Objective-C代码(使用NSString类别)可以直接翻译成Swift(使用String扩展)。
首先,你必须创建一个“桥接头”,并添加

#import <CommonCrypto/CommonCrypto.h>

然后:

extension String {
    func sha1() -> String {
        let data = self.dataUsingEncoding(NSUTF8StringEncoding)!
        var digest = [UInt8](count:Int(CC_SHA1_DIGEST_LENGTH), repeatedValue: 0)
        CC_SHA1(data.bytes, CC_LONG(data.length), &digest)
        let output = NSMutableString(capacity: Int(CC_SHA1_DIGEST_LENGTH))
        for byte in digest {
            output.appendFormat("%02x", byte)
        }
        return output as String
    }
}

println("Hello World".sha1())

这可以写得稍微短一点,更快一点

extension String {
    func sha1() -> String {
        let data = self.dataUsingEncoding(NSUTF8StringEncoding)!
        var digest = [UInt8](count:Int(CC_SHA1_DIGEST_LENGTH), repeatedValue: 0)
        CC_SHA1(data.bytes, CC_LONG(data.length), &digest)
        let hexBytes = map(digest) { String(format: "%02hhx", $0) }
        return "".join(hexBytes)
    }
}

Swift 2更新:

extension String {
    func sha1() -> String {
        let data = self.dataUsingEncoding(NSUTF8StringEncoding)!
        var digest = [UInt8](count:Int(CC_SHA1_DIGEST_LENGTH), repeatedValue: 0)
        CC_SHA1(data.bytes, CC_LONG(data.length), &digest)
        let hexBytes = digest.map { String(format: "%02hhx", $0) }
        return hexBytes.joinWithSeparator("")
    }
}

要返回Base-64编码的字符串而不是十六进制编码的字符串,只需替换

let hexBytes = digest.map { String(format: "%02hhx", $0) }
        return hexBytes.joinWithSeparator("")

return NSData(bytes: digest, length: digest.count).base64EncodedStringWithOptions([])

Swift 3的更新:

extension String {
    func sha1() -> String {
        let data = self.data(using: String.Encoding.utf8)!
        var digest = [UInt8](repeating: 0, count:Int(CC_SHA1_DIGEST_LENGTH))
        data.withUnsafeBytes { 
            _ = CC_SHA1($0, CC_LONG(data.count), &digest)
        }
        let hexBytes = digest.map { String(format: "%02hhx", $0) }
        return hexBytes.joined()
    }
}

要返回Base-64编码的字符串而不是十六进制编码的字符串,只需替换

let hexBytes = digest.map { String(format: "%02hhx", $0) }
        return hexBytes.joined()

作者

return Data(bytes: digest).base64EncodedString()

Swift 4更新:

不再需要桥接头文件,可以使用import CommonCrypto

import CommonCrypto

extension String {
    func sha1() -> String {
        let data = Data(self.utf8)
        var digest = [UInt8](repeating: 0, count:Int(CC_SHA1_DIGEST_LENGTH))
        data.withUnsafeBytes { 
            _ = CC_SHA1($0, CC_LONG(data.count), &digest)
        }
        let hexBytes = digest.map { String(format: "%02hhx", $0) }
        return hexBytes.joined()
    }
}

Swift 5更新:

Data.withUnsafeBytes()方法现在使用UnsafeRawBufferPointer to调用闭包,baseAddress用于将初始地址传递给C函数:

import CommonCrypto

extension String {
    func sha1() -> String {
        let data = Data(self.utf8)
        var digest = [UInt8](repeating: 0, count:Int(CC_SHA1_DIGEST_LENGTH))
        data.withUnsafeBytes { 
            _ = CC_SHA1($0.baseAddress, CC_LONG(data.count), &digest)
        }
        let hexBytes = digest.map { String(format: "%02hhx", $0) }
        return hexBytes.joined()
    }
}
t5zmwmid

t5zmwmid2#

随着CryptoKit在iOS13中的加入,我们现在有了原生的Swift API:

import Foundation
import CryptoKit

// CryptoKit.Digest utils
extension Digest {
    var bytes: [UInt8] { Array(makeIterator()) }
    var data: Data { Data(bytes) }

    var hexStr: String {
        bytes.map { String(format: "%02X", $0) }.joined()
    }
}

func example() {
    guard let data = "hello world".data(using: .utf8) else { return }
    let digest = Insecure.SHA1.hash(data: data)
    print(digest.data) // 20 bytes
    print(digest.hexStr) // 2AAE6C35C94FCFB415DBE95F408B9CE91EE846ED
}
cngwdvgl

cngwdvgl3#

Swift 5的一个版本,在iOS 13上使用CryptoKit,否则福尔斯退到CommonCrypto:

import CommonCrypto
import CryptoKit
import Foundation

private func hexString(_ iterator: Array<UInt8>.Iterator) -> String {
    return iterator.map { String(format: "%02x", $0) }.joined()
}

extension Data {

    public var sha1: String {
        if #available(iOS 13.0, *) {
            return hexString(Insecure.SHA1.hash(data: self).makeIterator())
        } else {
            var digest = [UInt8](repeating: 0, count: Int(CC_SHA1_DIGEST_LENGTH))
            self.withUnsafeBytes { bytes in
                _ = CC_SHA1(bytes.baseAddress, CC_LONG(self.count), &digest)
            }
            return hexString(digest.makeIterator())
        }
    }

}

用法:

let string = "The quick brown fox jumps over the lazy dog"
let hexDigest = string.data(using: .ascii)!.sha1
assert(hexDigest == "2fd4e1c67a2d28fced849ee1bb76e7391b93eb12")

也可通过Swift包管理器使用:
https://github.com/ralfebert/TinyHashes

yh2wf1be

yh2wf1be4#

是的,这是可能的,复制这个类到您的项目。https://github.com/idrougge/sha1-swift
这将是容易的,就像:

SHA1.hexString(from: "myPhrase" )!

已测试Swift 3和Swift 4。

06odsfpq

06odsfpq5#

要获得NSData形式的结果,假设您在桥接头中包含了<CommonCrypto/CommonCrypto.h>

extension NSData {

    func sha1() -> NSData? {
        let len = Int(CC_SHA1_DIGEST_LENGTH)
        let digest = UnsafeMutablePointer<UInt8>.alloc(len)
        CC_SHA1(bytes, CC_LONG(length), digest)
        return NSData(bytesNoCopy: UnsafeMutablePointer<Void>(digest), length: len)
    }
}

也使用正确的指针分配。像这样调用它:

myString.dataUsingEncoding(NSUTF8StringEncoding)?.sha1()

如果你需要NSData的十六进制表示,看看我的其他答案。

eulz3vhy

eulz3vhy6#

我们可以通过三个步骤提取使用sha1加密字符串的逻辑:
1.将字符串转换为数据对象
1.使用SHA1函数对数据进行加密
1.将数据对象转换为十六进制字符串
恕我直言,它的可读性更强,这个版本不需要NSData。

extension String {

        var sha1: String {
            guard let data = data(using: .utf8, allowLossyConversion: false) else {
                // Here you can just return empty string or execute fatalError with some description that this specific string can not be converted to data
            }
            return data.digestSHA1.hexString
        }

    }

    fileprivate extension Data {

        var digestSHA1: Data {
            var bytes: [UInt8] = Array(repeating: 0, count: Int(CC_SHA1_DIGEST_LENGTH))

            withUnsafeBytes {
                _ = CC_SHA1($0, CC_LONG(count), &bytes)
            }

            return Data(bytes: bytes)
        }

        var hexString: String {
            return map { String(format: "%02x", UInt8($0)) }.joined()
        }

    }
xriantvc

xriantvc7#

是的,有可能:* 使Objective-C代码可从Swift访问 *
参见文件。
如果你得不到任何好处(比如使用swift特有的特性),我会避免用swift重写它。
另外,在我正在做的一个项目中,我使用了一些类似于你的objtive-c代码来处理散列。一开始我用swift编写它,然后我意识到重用旧的obj-c更容易,更好。

abithluo

abithluo8#

对于一行程序的家伙,没有必要使用令人毛骨悚然的swift扩展
斯威夫特5.7.3

import CryptoKit

func mysha1(_ str:String) -> String {

  return Insecure.SHA1.hash(data: str.data(using: String.Encoding.utf8)!).map
  { String(format: "%02x", $0) }.joined()

}

相关问题