Created
April 18, 2018 13:06
-
-
Save TheGeekPharaoh/213b4a840753defab79e203f3eac8a18 to your computer and use it in GitHub Desktop.
CMS Signature Creation/Validation with Swift and OpenSSL
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
let testBundle = Bundle(for: type(of: self)) | |
guard let textUrl = testBundle.url(forResource: "test_message", withExtension: "txt"), | |
let signingKeyUrl = testBundle.url(forResource: "key", withExtension: "pem"), | |
let signingCertUrl = testBundle.url(forResource: "cert", withExtension: "pem") else { | |
exit(1) | |
} | |
let certFileObject = signingCertUrl.path.withCString { filePtr in | |
return fopen(filePtr, "rb") | |
} | |
defer { | |
fclose(certFileObject) | |
} | |
let keyFileObject = signingKeyUrl.path.withCString { filePtr in | |
return fopen(filePtr, "rb") | |
} | |
defer { | |
fclose(keyFileObject) | |
} | |
guard let key = PEM_read_PrivateKey(keyFileObject, nil, nil, nil), | |
let cert = PEM_read_X509(certFileObject, nil, nil, nil) else { | |
exit(1) | |
} | |
OpenSSL_add_all_ciphers() | |
OpenSSL_add_all_digests() | |
OPENSSL_add_all_algorithms_conf() | |
guard let textData = FileManager.default.contents(atPath: textUrl.path) else { | |
print("Unable to read text file") | |
exit(1) | |
} | |
guard let textBIO = BIO_new(BIO_s_mem()) else { | |
print("Unable to create textBIO") | |
exit(1) | |
} | |
_ = textData.withUnsafeBytes({dataBytes in | |
BIO_write(textBIO, dataBytes, Int32(textData.count)) | |
}) | |
guard let cms = CMS_sign(cert, key, nil, textBIO, UInt32(CMS_BINARY)) else { | |
print("Unale to sign data") | |
exit(1) | |
} | |
print("cms : \(cms)") | |
let store = X509_STORE_new() | |
X509_STORE_add_cert(store, cert) | |
let outBIO = BIO_new(BIO_s_mem()) | |
let result = CMS_verify(cms, nil, store, nil, outBIO, 0) | |
print("result : \(result)") | |
if result != 1 { | |
ERR_print_errors(outBIO!) | |
// let errorCode: UInt = ERR_get_error() | |
// print("ERROR : \(String(format: "%2X", errorCode))") | |
} | |
var ptr = UnsafeRawPointer(bitPattern: 1)! | |
let cnt = BIO_ctrl(outBIO, BIO_CTRL_INFO, 1, &ptr) | |
// Create data from pointer and count: | |
let outBIOData = Data(bytes: ptr, count: cnt) | |
let outBIOStr = String(data: outBIOData, encoding: .utf8) | |
print("outBIOStr : \(String(describing: outBIOStr))") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment