Search
 
SCRIPT & CODE EXAMPLE
 

SWIFT

swift md5 cryptokit

import Foundation
import var CommonCrypto.CC_MD5_DIGEST_LENGTH
import func CommonCrypto.CC_MD5
import typealias CommonCrypto.CC_LONG

func MD5(string: String) -> Data {
        let length = Int(CC_MD5_DIGEST_LENGTH)
        let messageData = string.data(using:.utf8)!
        var digestData = Data(count: length)

        _ = digestData.withUnsafeMutableBytes { digestBytes -> UInt8 in
            messageData.withUnsafeBytes { messageBytes -> UInt8 in
                if let messageBytesBaseAddress = messageBytes.baseAddress, let digestBytesBlindMemory = digestBytes.bindMemory(to: UInt8.self).baseAddress {
                    let messageLength = CC_LONG(messageData.count)
                    CC_MD5(messageBytesBaseAddress, messageLength, digestBytesBlindMemory)
                }
                return 0
            }
        }
        return digestData
    }

//Test:
let md5Data = MD5(string:"Hello")

let md5Hex =  md5Data.map { String(format: "%02hhx", $0) }.joined()
print("md5Hex: (md5Hex)")

let md5Base64 = md5Data.base64EncodedString()
print("md5Base64: (md5Base64)")
Comment

PREVIOUS NEXT
Code Example
Swift :: swift variables 
Swift :: how to check if something is in a set in swift 
Swift :: Swift convenience Initializer 
Swift :: Swift Nested Ternary Operators 
Swift :: implement swift protocol in kotlin 
Swift :: Swift Dictionary Inside a Tuple 
Swift :: access tuple elements 
Swift :: how to print body moya swift 
Swift :: array of button listeners swift 
Swift :: Swift while Loop to Display Game Level 
Swift :: uilabel without constraint 
Swift :: check and uncheck cells in uitableview swift 5 
Swift :: swift uibutton text resets to default 
Swift :: jsonserialization swift 
Swift :: swift split an array into chunks 
Swift :: Swift Modify the Elements of an Array 
Swift :: page view controller disable swipe 
Swift :: swift uicollectionview reloaddata completion 
Ruby :: validates length rails 
Ruby :: ruby get current datetime utc 
Ruby :: remove ruby 
Ruby :: ruby reference a file in a gem 
Ruby :: post request rails link_to 
Ruby :: rails strftime 
Ruby :: ruby substring remove 
Ruby :: if rails.env.development 
Ruby :: ruby 
Ruby :: rails image tag data attribute 
Ruby :: ruby empty array 
Ruby :: one line each loop ruby 
ADD CONTENT
Topic
Content
Source link
Name
4+5 =