随机

一个 Swift 软件包,用于生成密码学安全的随机字节和数字。使用 swift-nioswift-nio-ssl 构建。

功能

安装

Random 软件包添加到您的 Package.swift 文件中

// swift-tools-version:6.0
import PackageDescription

let package = Package(
    name: "YourProject",
    dependencies: [
        .package(url: "https://github.com/GiacomoLeopizzi/random-swift", from: "1.0.0"),
    ],
    targets: [
        .target(
            name: "YourTarget",
            dependencies: [
                .product(name: "Random", package: "random-swift")
            ]
        ),
    ]
)

用法

1. 生成安全随机数

使用 SecureRandomNumberGenerator 生成密码学安全的随机数

import Random

var generator = SecureRandomNumberGenerator()
let randomValue = generator.next() // Generates a secure random UInt64

2. 创建安全随机字节数组

生成一个填充了安全随机字节的数组

import Random

let randomBytes = [UInt8](withSecureRandom: 16) // An array of 16 secure random bytes

3. 将安全随机字节写入 ByteBuffer

import Random
import NIO

var buffer = ByteBuffer()
buffer.writeSecureRandomBytes(count: 32) // Writes 32 secure random bytes into the buffer

4. 使用安全随机字节填充缓冲区

使用 UnsafeMutableRawBufferPointer

import Random

var rawBuffer = UnsafeMutableRawBufferPointer.allocate(byteCount: 16, alignment: 1)

defer {
    rawBuffer.deallocate()
}

let success = rawBuffer.fillWithSecureRandomBytes()
assert(success, "Failed to fill buffer with secure random bytes")

使用 UnsafeMutableBufferPointer

import Random

var buffer = UnsafeMutableBufferPointer<UInt8>.allocate(capacity: 16)

defer {
    buffer.deallocate()
}

let success = buffer.fillWithSecureRandomBytes()
assert(success, "Failed to fill buffer with secure random bytes")

5. 扩展指针

UnsafeMutablePointer

将安全随机字节写入指针指向的内存

import Random

let pointer = UnsafeMutablePointer<UInt8>.allocate(capacity: 16)

defer {
    pointer.deallocate()
}

pointer.writeSecureRandomBytes(count: 16)

UnsafeMutableRawPointer

import Random

let rawPointer = UnsafeMutableRawPointer.allocate(byteCount: 16, alignment: 1)

defer {
    rawPointer.deallocate()
}

rawPointer.writeSecureRandomBytes(count: 16)

6. 将 SecureRandomNumberGenerator 与集合一起使用

SecureRandomNumberGenerator 遵循 RandomNumberGenerator 协议,这意味着它可以用于为标准的 Swift 集合 API(如 randomElement(using:))生成安全随机值。

示例:从字符串中选择一个随机字符

import Random

let alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
var generator = SecureRandomNumberGenerator()

if let char = alphabet.randomElement(using: &generator) {
    print("Random character: \(char)")
}

示例:安全地打乱数组

import Random

var numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
var generator = SecureRandomNumberGenerator()

numbers.shuffle(using: &generator)

print("Shuffled array: \(numbers)")

示例:生成安全随机密码

import Random

let characters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*()"
var generator = SecureRandomNumberGenerator()

let passwordLength = 16
let password = String((0..<passwordLength).compactMap { _ in characters.randomElement(using: &generator) })

print("Secure random password: \(password)")

API 参考

SecureRandomNumberGenerator

一个密码学安全的随机数生成器。遵循 RandomNumberGenerator 协议。

扩展

Array

ByteBuffer

UnsafeMutableBufferPointer

UnsafeMutableRawBufferPointer

UnsafeMutablePointer

UnsafeMutableRawPointer

贡献

欢迎贡献! 欢迎随时提交拉取请求或打开 issue 以提出改进或错误修复。