|
| 1 | +//===----------------------------------------------------------------------===// |
| 2 | +// |
| 3 | +// This source file is part of the SwiftContainerPlugin open source project |
| 4 | +// |
| 5 | +// Copyright (c) 2025 Apple Inc. and the SwiftContainerPlugin project authors |
| 6 | +// Licensed under Apache License v2.0 |
| 7 | +// |
| 8 | +// See LICENSE.txt for license information |
| 9 | +// See CONTRIBUTORS.txt for the list of SwiftContainerPlugin project authors |
| 10 | +// |
| 11 | +// SPDX-License-Identifier: Apache-2.0 |
| 12 | +// |
| 13 | +//===----------------------------------------------------------------------===// |
| 14 | + |
| 15 | +import Foundation |
| 16 | +import HTTPTypes |
| 17 | +import struct Crypto.SHA256 |
| 18 | +import struct Crypto.SHA512 |
| 19 | + |
| 20 | +// The distribution spec says that Docker- prefix headers are no longer to be used, |
| 21 | +// but also specifies that the registry digest is returned in this header. |
| 22 | +// https://github.com/opencontainers/distribution-spec/blob/main/spec.md#pulling-manifests |
| 23 | +extension HTTPField.Name { |
| 24 | + static let dockerContentDigest = Self("Docker-Content-Digest")! |
| 25 | +} |
| 26 | + |
| 27 | +extension ImageReference.Digest { |
| 28 | + /// Calculate the digest of a blob of data. |
| 29 | + /// - Parameters: |
| 30 | + /// - data: Blob of data to digest. |
| 31 | + /// - algorithm: Digest algorithm to use. |
| 32 | + public init( |
| 33 | + of data: any DataProtocol, |
| 34 | + algorithm: ImageReference.Digest.Algorithm = .sha256 |
| 35 | + ) { |
| 36 | + // SHA256 is required; some registries might also support SHA512 |
| 37 | + switch algorithm { |
| 38 | + case .sha256: |
| 39 | + let hash = SHA256.hash(data: data) |
| 40 | + let digest = hash.compactMap { String(format: "%02x", $0) }.joined() |
| 41 | + try! self.init("sha256:" + digest) |
| 42 | + |
| 43 | + case .sha512: |
| 44 | + let hash = SHA512.hash(data: data) |
| 45 | + let digest = hash.compactMap { String(format: "%02x", $0) }.joined() |
| 46 | + try! self.init("sha512:" + digest) |
| 47 | + } |
| 48 | + } |
| 49 | +} |
0 commit comments