[英]How can I change sha1 in base64 encoding in swift?
I have to convert string to sha1 and then use base64.我必须将字符串转换为 sha1,然后使用 base64。 Simply
base64_encode(sha1(My_String))
.只需
base64_encode(sha1(My_String))
。 I want to do that but I can't fix it correctly.我想这样做,但我无法正确修复它。 I can convert SHA1 with that code:
let firstTry = SHA1.hash(from: "call")
but when I try to make it in base64 it gave error which is say string not allowed.我可以使用该代码转换 SHA1:
let firstTry = SHA1.hash(from: "call")
但是当我尝试在 base64 中创建它时,它给出了错误,即不允许使用字符串。 How can I convert base64?如何转换base64? Thanks for your attention.
感谢您的关注。
I try to conver c[all] to sha1 with that code :我尝试使用该代码将 c[all] 转换为 sha1 :
let str = "c[all]"
let den3 = str.sha1()
its working good and return correct which is : 0fee061faab109e27b75010f2f1a0d8258bab7c5它的工作良好并返回正确的是:0fee061faab109e27b75010f2f1a0d8258bab7c5
And when I add let den3 = str.sha1().toBase64()
I get MGZlZTA2MWZhYWIxMDllMjdiNzUwMTBmMmYxYTBkODI1OGJhYjdjNQ== which is wrong actually I need to get that: D+4GH6qxCeJ7dQEPLxoNgli6t8U=当我添加
let den3 = str.sha1().toBase64()
我得到 MGZlZTA2MWZhYWIxMDllMjdiNzUwMTBmMmYxYTBkODI1OGJhYjdjNQ== 这实际上是错误的我需要得到那个: D+4GH6qxCeJ7dQEPL8U=UNgli6t
Where is my issue?我的问题在哪里?
Here my extensions这是我的扩展
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()
}
func toBase64() -> String {
return Data(self.utf8).base64EncodedString()
}
}
You could use CryptoKit like this你可以像这样使用 CryptoKit
import CryptoKit
let str: String = "Hello, world!"
//Get the SHA1 hash
let hash = Insecure.SHA1.hash(data: str.data(using: .utf8)!)
//Get string representation of the hash (matches hash.description)
let hashedString = hash.map({ String(format: "%02hhx", $0) }).joined()
//Get the base64 string
let encodedString = hashedString.data(using: .utf8)!.base64EncodedString()
On iOS 13+, you can use CryptoKit
as follows:在 iOS 13+ 上,您可以按如下方式使用
CryptoKit
:
import CryptoKit
extension String {
func base64EncodedSHA1Hash(using encoding: Encoding = .utf8) -> String? {
guard let data = data(using: encoding) else { return nil }
let hash = Data(Insecure.SHA1.hash(data: data))
return hash.base64EncodedString()
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.