88 lines
2.7 KiB
Swift
88 lines
2.7 KiB
Swift
|
//
|
||
|
// SHA512.swift
|
||
|
// Befund
|
||
|
//
|
||
|
// Created by Irakli Abetschkhrischwili on 29.04.22.
|
||
|
// Copyright © 2022 MVZ Dr. Stein und Kollegen. All rights reserved.
|
||
|
//
|
||
|
|
||
|
import Foundation
|
||
|
import CryptoKit
|
||
|
|
||
|
extension Core.Security
|
||
|
{
|
||
|
public class SHA512
|
||
|
{
|
||
|
public static let VerificatorHashingValue = "U{u)DT~!CV@y9P8U4#,T%KY~D>YRj388"
|
||
|
|
||
|
/**
|
||
|
* Encrypts a string value in SHA512 hash
|
||
|
*
|
||
|
* @param value - string value that should be encrypted in SHA512 hash
|
||
|
* @return - Returns SHA512 hash
|
||
|
*/
|
||
|
static func Encrypt(value: String) -> String
|
||
|
{
|
||
|
let digest = CryptoKit.SHA512.hash(data: value.data(using: .utf8) ?? Data())
|
||
|
|
||
|
return digest.map {
|
||
|
String(format: "%02hhx", $0)
|
||
|
}.joined()
|
||
|
}
|
||
|
|
||
|
/**
|
||
|
* Encrypts a byte array in SHA512 hash
|
||
|
*
|
||
|
* @param value - byte array that should be encrypted in SHA512 hash
|
||
|
* @return - Returns SHA512 hash
|
||
|
*/
|
||
|
static func Encrypt(data: Data) -> String
|
||
|
{
|
||
|
let digest = CryptoKit.SHA512.hash(data: data)
|
||
|
|
||
|
return digest.map {
|
||
|
String(format: "%02hhx", $0)
|
||
|
}.joined()
|
||
|
}
|
||
|
|
||
|
/**
|
||
|
* Generates SHA512 HMAC Hash with key
|
||
|
*
|
||
|
* @param message - message that should be signed by sha512 hmac
|
||
|
* @param key - key that should be used for signing
|
||
|
* @return returns SHA512 HMAC
|
||
|
*/
|
||
|
static func HMAC(message: Data, key: SymmetricKey) -> String
|
||
|
{
|
||
|
let signature = CryptoKit.HMAC<CryptoKit.SHA512>.authenticationCode(for: message, using: key)
|
||
|
return Data(signature).map { String(format: "%02hhx", $0) }.joined()
|
||
|
}
|
||
|
|
||
|
/**
|
||
|
* Generates SHA512 HMAC Hash with key
|
||
|
*
|
||
|
* @param message - message that should be signed by sha512 hmac
|
||
|
* @param key - key that should be used for signing
|
||
|
* @return returns SHA512 HMAC
|
||
|
*/
|
||
|
static func HMAC(message: Data, key: String) -> String
|
||
|
{
|
||
|
let symmetricKey = CryptoKit.SymmetricKey(data: key.data(using: .utf8)!)
|
||
|
return SHA512.HMAC(message: message, key: symmetricKey)
|
||
|
}
|
||
|
|
||
|
/**
|
||
|
* Validates HMAC with message and key
|
||
|
*
|
||
|
* @param hmac - HMAC from the partner
|
||
|
* @param message - message that should be signed by sha512 hmac
|
||
|
* @param key - key that should be used for signing
|
||
|
* @return returns true if success
|
||
|
*/
|
||
|
static func isValidAuthenticationCode(hmac: String, message: Data, key: SymmetricKey) -> Bool
|
||
|
{
|
||
|
return (hmac == self.HMAC(message: message, key: key))
|
||
|
}
|
||
|
}
|
||
|
}
|