create a password in swift

To create a secure password in Swift, you can use the CommonCrypto framework. Here's an example function that generates a random password with alphanumeric characters:

main.swift
import CommonCrypto

func generatePassword(length: Int) -> String? {
    let characters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
    let randomBytes = [UInt8](repeating: 0, count: length)
    let result = randomBytes.withUnsafeBufferPointer {
        bytes in
        return SecRandomCopyBytes(kSecRandomDefault, length, UnsafeMutableRawPointer(mutating: bytes.baseAddress!))
    }
    if result == errSecSuccess {
        let password = String(bytes: randomBytes, encoding: String.Encoding.utf8)!
        return password
    } else {
        return nil
    }
}
588 chars
17 lines

The generatePassword function takes a length parameter that specifies the length of the password you want to generate. It then uses the SecRandomCopyBytes function to generate random bytes and converts them to a String of alphanumeric characters using the String initializer that takes a bytes parameter.

You can call this function and use the returned password string to securely store or transmit passwords in your iOS app.

gistlibby LogSnag