mirror of
https://github.com/apple/swift-crypto
synced 2026-11-22 04:30:39 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
b51f1d6845 | ||
|
|
faad1cf4fd |
No files matched your search
+1
-1
@@ -1,4 +1,4 @@
|
||||
// swift-tools-version:5.6
|
||||
// swift-tools-version:5.7
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the SwiftCrypto open source project
|
||||
|
||||
@@ -108,14 +108,15 @@ If you believe you have identified a vulnerability in Swift Crypto, please [repo
|
||||
|
||||
### Swift versions
|
||||
|
||||
The most recent versions of Swift Crypto support Swift 5.6 and newer. The minimum Swift version supported by Swift Crypto releases are detailed below:
|
||||
The most recent versions of Swift Crypto support Swift 5.7 and newer. The minimum Swift version supported by Swift Crypto releases are detailed below:
|
||||
|
||||
Swift Crypto | Minimum Swift Version
|
||||
------------------|----------------------
|
||||
`2.0.0 ..< 2.1.0` | 5.2
|
||||
`2.1.0 ..< 2.2.0` | 5.4
|
||||
`2.2.0 ..< 2.4.2` | 5.5
|
||||
`2.4.2 ...` | 5.6
|
||||
`2.4.2 ..< 3.1.0` | 5.6
|
||||
`3.1.0 ...` | 5.7
|
||||
|
||||
### Compatibility
|
||||
|
||||
|
||||
@@ -0,0 +1,179 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the SwiftCrypto open source project
|
||||
//
|
||||
// Copyright (c) 2023 Apple Inc. and the SwiftCrypto project authors
|
||||
// Licensed under Apache License v2.0
|
||||
//
|
||||
// See LICENSE.txt for license information
|
||||
// See CONTRIBUTORS.md for the list of SwiftCrypto project authors
|
||||
//
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
import Crypto
|
||||
import Foundation
|
||||
|
||||
extension AES {
|
||||
/// The Advanced Encryption Standard (AES) Cipher Block Chaining (CBC) cipher
|
||||
/// suite.
|
||||
public enum _CBC {
|
||||
private static var blockSize: Int { 16 }
|
||||
|
||||
private static func encryptBlockInPlace(
|
||||
_ plaintext: inout Block,
|
||||
priorCiphertextBlock: Block,
|
||||
using key: SymmetricKey
|
||||
) throws {
|
||||
assert([128, 192, 256].contains(key.bitCount))
|
||||
|
||||
plaintext ^= priorCiphertextBlock
|
||||
try AES.permute(&plaintext, key: key)
|
||||
}
|
||||
|
||||
/// Encrypts data using AES-CBC.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - plaintext: The message to encrypt.
|
||||
/// - key: A encryption key.
|
||||
/// - iv: The initialization vector.
|
||||
/// - Returns: The encrypted ciphertext.
|
||||
public static func encrypt<Plaintext: DataProtocol>(_ plaintext: Plaintext, using key: SymmetricKey, iv: AES._CBC.IV) throws -> Data {
|
||||
guard [128, 192, 256].contains(key.bitCount) else {
|
||||
throw CryptoKitError.incorrectKeySize
|
||||
}
|
||||
|
||||
let requiresFullPaddingBlock = (plaintext.count % AES._CBC.blockSize) == 0
|
||||
|
||||
var ciphertext = Data()
|
||||
ciphertext.reserveCapacity(plaintext.count + Self.blockSize) // Room for padding.
|
||||
|
||||
var previousBlock = Block(iv)
|
||||
var plaintext = plaintext[...]
|
||||
|
||||
while plaintext.count > 0 {
|
||||
var block = Block(blockBytes: plaintext.prefix(Self.blockSize))
|
||||
try Self.encryptBlockInPlace(&block, priorCiphertextBlock: previousBlock, using: key)
|
||||
ciphertext.append(contentsOf: block)
|
||||
previousBlock = block
|
||||
plaintext = plaintext.dropFirst(Self.blockSize)
|
||||
}
|
||||
|
||||
if requiresFullPaddingBlock {
|
||||
var block = Block.paddingBlock
|
||||
try Self.encryptBlockInPlace(&block, priorCiphertextBlock: previousBlock, using: key)
|
||||
ciphertext.append(contentsOf: block)
|
||||
}
|
||||
|
||||
return ciphertext
|
||||
}
|
||||
|
||||
private static func decryptBlockInPlace(_ ciphertext: inout Block, priorCiphertextBlock: Block, using key: SymmetricKey) throws {
|
||||
assert([128, 192, 256].contains(key.bitCount))
|
||||
|
||||
try AES.inversePermute(&ciphertext, key: key)
|
||||
ciphertext ^= priorCiphertextBlock
|
||||
}
|
||||
|
||||
/// Decrypts data using AES-CBC.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - ciphertext: The encrypted ciphertext.
|
||||
/// - key: A decryption key.
|
||||
/// - iv: The initialization vector.
|
||||
/// - Returns: The decrypted message.
|
||||
public static func decrypt<Ciphertext: DataProtocol>(_ ciphertext: Ciphertext, using key: SymmetricKey, iv: AES._CBC.IV) throws -> Data {
|
||||
guard [128, 192, 256].contains(key.bitCount) else {
|
||||
throw CryptoKitError.incorrectKeySize
|
||||
}
|
||||
|
||||
var plaintext = Data()
|
||||
plaintext.reserveCapacity(ciphertext.count)
|
||||
|
||||
var previousBlock = Block(iv)
|
||||
var ciphertext = ciphertext[...]
|
||||
|
||||
while ciphertext.count > 0 {
|
||||
let ctBlock = Block(blockBytes: ciphertext.prefix(Self.blockSize))
|
||||
var block = ctBlock
|
||||
try Self.decryptBlockInPlace(&block, priorCiphertextBlock: previousBlock, using: key)
|
||||
plaintext.append(contentsOf: block)
|
||||
previousBlock = ctBlock
|
||||
ciphertext = ciphertext.dropFirst(Self.blockSize)
|
||||
}
|
||||
|
||||
try plaintext.trimPadding()
|
||||
return plaintext
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension AES._CBC {
|
||||
/// An initialization vector.
|
||||
public struct IV {
|
||||
// AES CBC uses a 128-bit IV.
|
||||
var ivBytes: (
|
||||
UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8,
|
||||
UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8
|
||||
)
|
||||
|
||||
public init() {
|
||||
var rng = SystemRandomNumberGenerator()
|
||||
let (first, second) = (rng.next(), rng.next())
|
||||
|
||||
self.ivBytes = (
|
||||
UInt8(truncatingIfNeeded: first),
|
||||
UInt8(truncatingIfNeeded: first >> 8),
|
||||
UInt8(truncatingIfNeeded: first >> 16),
|
||||
UInt8(truncatingIfNeeded: first >> 24),
|
||||
UInt8(truncatingIfNeeded: first >> 32),
|
||||
UInt8(truncatingIfNeeded: first >> 40),
|
||||
UInt8(truncatingIfNeeded: first >> 48),
|
||||
UInt8(truncatingIfNeeded: first >> 56),
|
||||
UInt8(truncatingIfNeeded: second),
|
||||
UInt8(truncatingIfNeeded: second >> 8),
|
||||
UInt8(truncatingIfNeeded: second >> 16),
|
||||
UInt8(truncatingIfNeeded: second >> 24),
|
||||
UInt8(truncatingIfNeeded: second >> 32),
|
||||
UInt8(truncatingIfNeeded: second >> 40),
|
||||
UInt8(truncatingIfNeeded: second >> 48),
|
||||
UInt8(truncatingIfNeeded: second >> 56)
|
||||
)
|
||||
}
|
||||
|
||||
public init<IVBytes: Collection>(ivBytes: IVBytes) throws where IVBytes.Element == UInt8 {
|
||||
// We support a 128-bit IV.
|
||||
guard ivBytes.count == 16 else {
|
||||
throw CryptoKitError.incorrectKeySize
|
||||
}
|
||||
|
||||
self.ivBytes = (
|
||||
0, 0, 0, 0, 0, 0, 0, 0,
|
||||
0, 0, 0, 0, 0, 0, 0, 0
|
||||
)
|
||||
|
||||
withUnsafeMutableBytes(of: &self.ivBytes) { bytesPtr in
|
||||
bytesPtr.copyBytes(from: ivBytes)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension Data {
|
||||
fileprivate mutating func trimPadding() throws {
|
||||
guard let paddingBytes = self.last else {
|
||||
// Degenerate case, empty string. This is forbidden:
|
||||
// we must always pad.
|
||||
throw CryptoKitError.incorrectParameterSize
|
||||
}
|
||||
|
||||
guard paddingBytes > 0 &&
|
||||
self.count >= paddingBytes &&
|
||||
self.suffix(Int(paddingBytes)).allSatisfy({ $0 == paddingBytes }) else {
|
||||
throw CryptoKitError.incorrectParameterSize
|
||||
}
|
||||
|
||||
self = self.dropLast(Int(paddingBytes))
|
||||
}
|
||||
}
|
||||
@@ -62,7 +62,8 @@ extension AES {
|
||||
} ?? true
|
||||
|
||||
if requiresSlowPath {
|
||||
try AES.Block.withStackStorage { blockBytes in
|
||||
var block = AES.Block()
|
||||
try block.withUnsafeMutableBytes { blockBytes in
|
||||
precondition(blockBytes.count == payload.count)
|
||||
|
||||
blockBytes.copyBytes(from: payload)
|
||||
@@ -109,25 +110,87 @@ extension AES {
|
||||
}
|
||||
}
|
||||
|
||||
private struct Block {
|
||||
private var storage: (UInt64, UInt64)
|
||||
struct Block {
|
||||
private static var blockSize: Int { 16 }
|
||||
|
||||
private init() {
|
||||
assert(MemoryLayout<Self>.size == Int(AES.blockSize))
|
||||
self.storage = (0, 0)
|
||||
typealias BlockBytes = (
|
||||
UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8,
|
||||
UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8
|
||||
)
|
||||
|
||||
// 128-bit block size
|
||||
private var blockBytes: BlockBytes
|
||||
|
||||
fileprivate init() {
|
||||
self.blockBytes = (
|
||||
0, 0, 0, 0, 0, 0, 0, 0,
|
||||
0, 0, 0, 0, 0, 0, 0, 0
|
||||
)
|
||||
}
|
||||
|
||||
private mutating func withUnsafeMutableBytes<ReturnType>(
|
||||
_ body: (UnsafeMutableRawBufferPointer) throws -> ReturnType
|
||||
) rethrows -> ReturnType {
|
||||
return try Swift.withUnsafeMutableBytes(of: &self.storage, body)
|
||||
init(_ blockBytes: BlockBytes) {
|
||||
self.blockBytes = blockBytes
|
||||
}
|
||||
|
||||
static func withStackStorage<ReturnType>(
|
||||
_ body: (UnsafeMutableRawBufferPointer) throws -> ReturnType
|
||||
) rethrows -> ReturnType {
|
||||
var storage = Self()
|
||||
return try storage.withUnsafeMutableBytes(body)
|
||||
init(_ iv: AES._CBC.IV) {
|
||||
self.blockBytes = iv.ivBytes
|
||||
}
|
||||
|
||||
init<BlockBytes: Collection>(blockBytes: BlockBytes) where BlockBytes.Element == UInt8 {
|
||||
// The block size is always 16. Pad out past there.
|
||||
precondition(blockBytes.count <= Self.blockSize)
|
||||
|
||||
self.blockBytes = (
|
||||
0, 0, 0, 0, 0, 0, 0, 0,
|
||||
0, 0, 0, 0, 0, 0, 0, 0
|
||||
)
|
||||
|
||||
Swift.withUnsafeMutableBytes(of: &self.blockBytes) { bytesPtr in
|
||||
bytesPtr.copyBytes(from: blockBytes)
|
||||
|
||||
// Early exit here.
|
||||
if blockBytes.count == Self.blockSize {
|
||||
return
|
||||
}
|
||||
|
||||
var remainingBytes = bytesPtr.dropFirst(blockBytes.count)
|
||||
let padByte = UInt8(remainingBytes.count)
|
||||
|
||||
for index in remainingBytes.indices {
|
||||
remainingBytes[index] = padByte
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static var paddingBlock: Block {
|
||||
// The padding block is a full block of value blocksize.
|
||||
let value = UInt8(truncatingIfNeeded: Self.blockSize)
|
||||
return Block((
|
||||
value, value, value, value, value, value, value, value,
|
||||
value, value, value, value, value, value, value, value
|
||||
))
|
||||
}
|
||||
|
||||
func withUnsafeBytes<ReturnType>(_ body: (UnsafeRawBufferPointer) throws -> ReturnType) rethrows -> ReturnType {
|
||||
return try Swift.withUnsafeBytes(of: self.blockBytes, body)
|
||||
}
|
||||
|
||||
mutating func withUnsafeMutableBytes<ReturnType>(_ body: (UnsafeMutableRawBufferPointer) throws -> ReturnType) rethrows -> ReturnType {
|
||||
return try Swift.withUnsafeMutableBytes(of: &self.blockBytes, body)
|
||||
}
|
||||
|
||||
static func ^= (lhs: inout Block, rhs: Block) {
|
||||
// Ideally we'd not use raw pointers for this.
|
||||
lhs.withUnsafeMutableBytes { lhsPtr in
|
||||
rhs.withUnsafeBytes { rhsPtr in
|
||||
assert(lhsPtr.count == Self.blockSize)
|
||||
assert(rhsPtr.count == Self.blockSize)
|
||||
|
||||
for index in 0..<Self.blockSize {
|
||||
lhsPtr[index] ^= rhsPtr[index]
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -141,3 +204,50 @@ extension AES {
|
||||
}
|
||||
}
|
||||
|
||||
extension AES.Block: RandomAccessCollection, MutableCollection {
|
||||
var startIndex: Int {
|
||||
0
|
||||
}
|
||||
|
||||
var endIndex: Int {
|
||||
Self.blockSize
|
||||
}
|
||||
|
||||
subscript(position: Int) -> UInt8 {
|
||||
get {
|
||||
precondition(position >= 0)
|
||||
precondition(position < Self.blockSize)
|
||||
|
||||
return self.withUnsafeBytes { $0[position] }
|
||||
}
|
||||
|
||||
set {
|
||||
precondition(position >= 0)
|
||||
precondition(position < Self.blockSize)
|
||||
|
||||
self.withUnsafeMutableBytes { $0[position] = newValue }
|
||||
}
|
||||
}
|
||||
|
||||
func withContiguousStorageIfAvailable<ReturnValue>(
|
||||
_ body: (UnsafeBufferPointer<UInt8>) throws -> ReturnValue)
|
||||
rethrows -> ReturnValue? {
|
||||
return try withUnsafePointer(to: self.blockBytes) { tuplePtr in
|
||||
// Homogeneous tuples are always bound to the element type as well as to their own type.
|
||||
let retyped = UnsafeRawPointer(tuplePtr).assumingMemoryBound(to: UInt8.self)
|
||||
let bufferised = UnsafeBufferPointer(start: retyped, count: Self.blockSize)
|
||||
return try body(bufferised)
|
||||
}
|
||||
}
|
||||
|
||||
mutating func withContiguousMutableStorageIfAvailable<ReturnValue>(
|
||||
_ body: (inout UnsafeMutableBufferPointer<UInt8>) throws -> ReturnValue)
|
||||
rethrows -> ReturnValue? {
|
||||
return try withUnsafeMutablePointer(to: &self.blockBytes) { tuplePtr in
|
||||
// Homogeneous tuples are always bound to the element type as well as to their own type.
|
||||
let retyped = UnsafeMutableRawPointer(tuplePtr).assumingMemoryBound(to: UInt8.self)
|
||||
var bufferised = UnsafeMutableBufferPointer(start: retyped, count: Self.blockSize)
|
||||
return try body(&bufferised)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -34,7 +34,7 @@ struct AESGCMTestVector: Codable {
|
||||
let result: String
|
||||
}
|
||||
|
||||
class AESGCMSIVTests: XCTestCase {
|
||||
final class AESGCMSIVTests: XCTestCase {
|
||||
func testPropertiesStayTheSameAfterFailedOpening() throws {
|
||||
let message = Data("this is a message".utf8)
|
||||
let sealed = try AES.GCM._SIV.seal(message, using: SymmetricKey(size: .bits128))
|
||||
|
||||
@@ -0,0 +1,107 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the SwiftCrypto open source project
|
||||
//
|
||||
// Copyright (c) 2023 Apple Inc. and the SwiftCrypto project authors
|
||||
// Licensed under Apache License v2.0
|
||||
//
|
||||
// See LICENSE.txt for license information
|
||||
// See CONTRIBUTORS.md for the list of SwiftCrypto project authors
|
||||
//
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
import Crypto
|
||||
import Foundation
|
||||
import _CryptoExtras
|
||||
import XCTest
|
||||
|
||||
final class CBCTests: XCTestCase {
|
||||
func testWycheproofDecrypt() throws {
|
||||
try wycheproofTest(
|
||||
jsonName: "aes_cbc_pkcs5_test",
|
||||
testFunction: { (group: AESCBCTestGroup) in
|
||||
for test in group.tests {
|
||||
do {
|
||||
let decrypted = try AES._CBC.decrypt(
|
||||
test.computedCt, using: test.computedKey, iv: test.computedIv
|
||||
)
|
||||
|
||||
switch test.result {
|
||||
case "valid":
|
||||
XCTAssertTrue(decrypted == test.computedMsg, "Unexpected invalid test \(test.tcId) (\(test.comment))")
|
||||
case "invalid":
|
||||
XCTAssertFalse(decrypted != test.computedMsg, "Unexpected valid test \(test.tcId) (\(test.comment))")
|
||||
default:
|
||||
fatalError("Unexpected result type")
|
||||
}
|
||||
} catch {
|
||||
XCTAssertTrue(test.result == "invalid", "Unexpected invalid test \(test.tcId) (\(test.comment))")
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func testWycheproofEncrypt() throws {
|
||||
try wycheproofTest(
|
||||
jsonName: "aes_cbc_pkcs5_test",
|
||||
testFunction: { (group: AESCBCTestGroup) in
|
||||
for test in group.tests {
|
||||
if test.result == "invalid" { continue }
|
||||
|
||||
do {
|
||||
let encrypted = try AES._CBC.encrypt(
|
||||
test.computedMsg, using: test.computedKey, iv: test.computedIv
|
||||
)
|
||||
XCTAssertEqual(encrypted, test.computedCt, "Unexpected invalid test \(test.tcId) (\(test.comment))")
|
||||
} catch {
|
||||
XCTFail("Unexpected invalid test \(test.tcId) (\(test.comment))")
|
||||
}
|
||||
}
|
||||
}
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
struct AESCBCTestGroup: Codable {
|
||||
var keySize: Int
|
||||
var ivSize: Int
|
||||
var type: String
|
||||
var tests: [AESCBCTest]
|
||||
}
|
||||
|
||||
struct AESCBCTest: Codable {
|
||||
var tcId: Int
|
||||
var comment: String
|
||||
var key: String
|
||||
var msg: String
|
||||
var iv: String
|
||||
var ct: String
|
||||
var result: String
|
||||
var flags: [String]
|
||||
|
||||
var computedKey: SymmetricKey {
|
||||
SymmetricKey(hexEncoded: self.key)
|
||||
}
|
||||
|
||||
var computedMsg: Data {
|
||||
try! Data(hexString: self.msg)
|
||||
}
|
||||
|
||||
var computedIv: AES._CBC.IV {
|
||||
try! AES._CBC.IV(ivBytes: Array(hexString: self.iv))
|
||||
}
|
||||
|
||||
var computedCt: Data {
|
||||
try! Data(hexString: self.ct)
|
||||
}
|
||||
}
|
||||
|
||||
extension SymmetricKey {
|
||||
init(hexEncoded: String) {
|
||||
let keyBytes = try! Array(hexString: hexEncoded)
|
||||
self = SymmetricKey(data: keyBytes)
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,21 +0,0 @@
|
||||
version: "3"
|
||||
|
||||
services:
|
||||
|
||||
runtime-setup:
|
||||
image: swift-crypto:20.04-5.6
|
||||
build:
|
||||
args:
|
||||
ubuntu_version: "focal"
|
||||
swift_version: "5.6"
|
||||
|
||||
test:
|
||||
image: swift-crypto:20.04-5.6
|
||||
environment: []
|
||||
#- SANITIZER_ARG=--sanitize=thread
|
||||
|
||||
cmake:
|
||||
image: swift-crypto:20.04-5.6
|
||||
|
||||
shell:
|
||||
image: swift-crypto:20.04-5.6
|
||||
@@ -0,0 +1,21 @@
|
||||
version: "3"
|
||||
|
||||
services:
|
||||
|
||||
runtime-setup:
|
||||
image: swift-crypto:22.04-5.10
|
||||
build:
|
||||
args:
|
||||
base_image: "swiftlang/swift:nightly-5.10-jammy"
|
||||
|
||||
test:
|
||||
image: swift-crypto:22.04-5.10
|
||||
environment:
|
||||
- IMPORT_CHECK_ARG=--explicit-target-dependency-import-check error
|
||||
#- SANITIZER_ARG=--sanitize=thread
|
||||
|
||||
cmake:
|
||||
image: swift-crypto:22.04-5.10
|
||||
|
||||
shell:
|
||||
image: swift-crypto:22.04-5.10
|
||||
@@ -6,7 +6,8 @@ services:
|
||||
image: swift-crypto:22.04-5.9
|
||||
build:
|
||||
args:
|
||||
base_image: "swiftlang/swift:nightly-5.9-jammy"
|
||||
ubuntu_version: "jammy"
|
||||
swift_version: "5.9"
|
||||
|
||||
test:
|
||||
image: swift-crypto:22.04-5.9
|
||||
|
||||
Reference in new issue
Block a user