SPB Git

Repository Public MIT

RegistryHash.swift 4.9 KB 111 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project          : SP GlassKit7// File             : Sources/SPGlassRegistry/RegistryHash.swift8// Module           : SPGlassRegistry9// Repository       : https://git.spboucher.ai/sp-glasskit10// Project Website  : https://glass.spboucher.ai11// Created          : 2026-12-0212// Last Modified    : 2026-12-0213//14// Author           : Simon-Pierre Boucher15// Position         : Professor of Finance16// Institution      : Université du Québec en Outaouais (UQO)17// Organization     : SP Boucher18// Website          : https://spboucher.ai19// Git              : https://git.spboucher.ai20//21// Preferred Contact: contact@spboucher.ai22// Development      : dev@spboucher.ai23// Support          : support@spboucher.ai24// Security/Admin   : admin@spboucher.ai25//26// Copyright (c) 202627// Simon-Pierre Boucher28// All rights reserved where applicable. This file is governed by the29// applicable project license, copyright notices and relevant law.30// Existing third-party rights and notices remain unaffected.31//32// License          : MIT33//34// Do not embed credentials, private keys, access tokens,35// certificates or confidential personal information.36//37// =============================================================================38// END OF SP BOUCHER SOURCE HEADER39// =============================================================================4041import CryptoKit42import Foundation4344public enum RegistryHash {45    /// Lower-case hexadecimal SHA-256 of `data`.46    public static func sha256(_ data: Data) -> String {47        SHA256.hash(data: data).map { String(format: "%02x", $0) }.joined()48    }4950    public static func isSHA256(_ text: String) -> Bool {51        text.utf8.count == 64 && text.utf8.allSatisfy { ($0 >= 48 && $0 <= 57) || ($0 >= 97 && $0 <= 102) }52    }5354    /// Digest of a file list: SHA-256 over `path<TAB>sha256<LF>` lines sorted by path.55    public static func contentDigest(of files: [ManifestFile]) -> String {56        let lines = files.sorted { $0.path < $1.path }.map { "\($0.path)\t\($0.sha256)\n" }.joined()57        return sha256(Data(lines.utf8))58    }5960    /// Checks downloaded bytes against a manifest entry: size first, then checksum.61    public static func verify(_ data: Data, against file: ManifestFile) throws(RegistryError) {62        guard data.count == file.bytes else { throw .sizeMismatch(path: file.path, expected: file.bytes, actual: data.count) }63        let actual = sha256(data)64        guard actual == file.sha256 else { throw .hashMismatch(path: file.path, expected: file.sha256, actual: actual) }65    }66}6768/// Ed25519 signature of the registry index.69///70/// A checksum proves that a file was not altered after the manifest was written; it says nothing about who71/// wrote the manifest. The index lists the checksum of every manifest, and every manifest lists the checksum72/// of its files, so one signature over the index covers the whole registry. The public key must reach the73/// user by another channel than the registry itself.74public enum RegistrySignature {75    public static func generatePrivateKey() -> String {76        Curve25519.Signing.PrivateKey().rawRepresentation.base64EncodedString()77    }7879    public static func publicKey(forPrivateKey privateKey: String) throws(RegistryError) -> String {80        try key(privateKey).publicKey.rawRepresentation.base64EncodedString()81    }8283    public static func sign(_ data: Data, privateKey: String) throws(RegistryError) -> String {84        do {85            return try key(privateKey).signature(for: data).base64EncodedString()86        } catch {87            throw .invalidKey("the private key could not sign.")88        }89    }9091    /// Verifies a base64 signature. Throws `.signatureInvalid` when it does not match.92    public static func verify(_ data: Data, signature: String, publicKey: String) throws(RegistryError) {93        guard let keyData = Data(base64Encoded: publicKey.trimmingCharacters(in: .whitespacesAndNewlines)),94              let key = try? Curve25519.Signing.PublicKey(rawRepresentation: keyData) else {95            throw .invalidKey("the public key is not a base64 Ed25519 key.")96        }97        guard let signatureData = Data(base64Encoded: signature.trimmingCharacters(in: .whitespacesAndNewlines)),98              key.isValidSignature(signatureData, for: data) else {99            throw .signatureInvalid100        }101    }102103    private static func key(_ privateKey: String) throws(RegistryError) -> Curve25519.Signing.PrivateKey {104        guard let data = Data(base64Encoded: privateKey.trimmingCharacters(in: .whitespacesAndNewlines)),105              let key = try? Curve25519.Signing.PrivateKey(rawRepresentation: data) else {106            throw .invalidKey("the private key is not a base64 Ed25519 key.")107        }108        return key109    }110}111
Files main
Menu

Theme