V0.6.0 Arroyo Toad
Added the capability to sign and verify P521 Signature
This commit is contained in:
58
Sources/MessageUtils/Utils/CryptoUtils/Security.swift
Normal file
58
Sources/MessageUtils/Utils/CryptoUtils/Security.swift
Normal file
@@ -0,0 +1,58 @@
|
||||
import Crypto // Equivalent to CryptoKit (more or less)
|
||||
import Foundation
|
||||
|
||||
|
||||
// ------------------
|
||||
// --- Sign ---------
|
||||
// ------------------
|
||||
public func signP521(object: Data, key: P521.Signing.PrivateKey)throws -> Data {
|
||||
return try key.signature<Data>(for: object).rawRepresentation
|
||||
|
||||
}
|
||||
/*
|
||||
public func sign<T>(object: T, key: P521.Signing.PrivateKey) throws -> String {
|
||||
|
||||
var _object = object
|
||||
let data: Data = Data(bytes: &_object, count: MemoryLayout<T>.stride)
|
||||
|
||||
} */
|
||||
|
||||
|
||||
|
||||
// ------------------
|
||||
// --- Decrypt ------
|
||||
// ------------------
|
||||
public func verifySignatureP521(signature: Data, object: Data, key: P521.Signing.PublicKey) throws -> Bool {
|
||||
|
||||
let ecdsa: P521.Signing.ECDSASignature
|
||||
|
||||
do {
|
||||
ecdsa = try P521.Signing.ECDSASignature(rawRepresentation: signature)
|
||||
} catch {
|
||||
throw SecurityError.NotDecodableError
|
||||
}
|
||||
|
||||
return key.isValidSignature<Data>(ecdsa, for: object)
|
||||
}
|
||||
|
||||
|
||||
|
||||
// ------------------
|
||||
// --- PEM 2 Key ----
|
||||
// ------------------
|
||||
public func pem2key(filePath: String) throws -> P521.Signing.PrivateKey {
|
||||
|
||||
let pemURL: URL = URL(filePath: filePath)
|
||||
|
||||
return try pem2key(filePem: pemURL)
|
||||
}
|
||||
|
||||
public func pem2key(filePem: URL) throws -> P521.Signing.PrivateKey {
|
||||
|
||||
let fileString: String = try String(contentsOf: filePem, encoding: String.Encoding.utf8)
|
||||
return try pem2key(pemString: fileString)
|
||||
}
|
||||
|
||||
public func pem2key(pemString: String) throws -> P521.Signing.PrivateKey {
|
||||
return try P521.Signing.PrivateKey(pemRepresentation: pemString)
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
enum SecurityError: Error {
|
||||
case NotEncodableError
|
||||
case NotDecodableError
|
||||
}
|
||||
Reference in New Issue
Block a user