Encrypt Json Payload using public Key (.cer) - swift

Hi I want to encrypt Json Payload using public key that is .cer file. Please suggest how to do this?
let path = Bundle.main.path(forResource: "Keys123_1", ofType: "cer")
//get the data asociated to this file
let urlStt = URL(fileURLWithPath: path!)
if let base64String = try? Data(contentsOf: urlStt).base64EncodedString() {
print(base64String)
let data2 = Data.init(base64Encoded: base64String)
let keyDict:[NSObject:NSObject] = [
kSecAttrKeyType: kSecAttrKeyTypeRSA,
kSecAttrKeyClass: kSecAttrKeyClassPublic,
kSecAttrKeySizeInBits: NSNumber(value: 2048),
kSecReturnPersistentRef: true as NSObject
]
var error:Unmanaged<CFError>? = nil
guard let key = SecKeyCreateWithData(data2 as! CFData, keyDict as CFDictionary, &error) else {
print(error)
return
}
I am getting this error :
Optional(Swift.Unmanaged<__ObjC.CFError>(_value: Error Domain=NSOSStatusErrorDomain Code=-50 "RSA public key creation from data failed" UserInfo={NSDescription=RSA public key creation from data failed}))

Try this code and encrypt with public key and verify data by decrypt with private key on server side. I followed this link.
May be this work for you.
func getPublicKey() -> SecKey? {
let certificateData = try! Data(contentsOf: Bundle.main.url(forResource: "public", withExtension: "cer")!)
let certificate = SecCertificateCreateWithData(nil, certificateData as CFData)
var trust: SecTrust?
let policy = SecPolicyCreateBasicX509()
let status = SecTrustCreateWithCertificates(certificate!, policy, &trust)
if status == errSecSuccess {
let publicKey = SecTrustCopyPublicKey(trust!)!
return publicKey
}
return nil
}

Related

How to decrypt data with Security.framework on macOS?

I need to decrypt data with a RSA public key on macOS, by googling I know we can use method SecKeyCreateDecryptedData of Security.framework to achieve that, but it leads to two problems:
SecKeyCreateDecryptedData accepts a private key to execute decryption, but in my situation, the data is encrypted with private key in the server-end, and needs to be decrypted with public key in the client-end.
I tried to create SecKey from a RSA public key string, but failed.
My code:
import Foundation
func getPublicKey(from data: Data) throws -> SecKey {
var error: Unmanaged<CFError>? = nil
let publicKeyMaybe = SecKeyCreateWithData(
data as NSData,
[
kSecAttrKeyType: kSecAttrKeyTypeRSA,
kSecAttrKeyClass: kSecAttrKeyClassPublic
] as NSDictionary,
&error)
guard let publicKey = publicKeyMaybe else {
throw error!.takeRetainedValue() as Error
}
return publicKey
}
func decrypt(key: SecKey, data cipherTextData: Data) -> Data? {
let algorithm: SecKeyAlgorithm = .eciesEncryptionCofactorVariableIVX963SHA256AESGCM
guard SecKeyIsAlgorithmSupported(key, .decrypt, algorithm) else {
print("Can't decrypt. Algorithm not supported.")
return nil
}
var error: Unmanaged<CFError>? = nil
let clearTextData = SecKeyCreateDecryptedData(key,
algorithm,
cipherTextData as CFData,
&error) as Data?
if let error = error {
print("Can't decrypt. %#", (error.takeRetainedValue() as Error).localizedDescription)
return nil
}
guard clearTextData != nil else {
print("Can't decrypt. No resulting cleartextData.")
return nil
}
print("Decrypted data.")
return clearTextData
}
func testDecrypt() {
let rawString = "0ed3a2c57f5dEJgqXT9760269b8cc5cd76f3afcf"
let decodedData = Data.init(base64Encoded: rawString, options: [])!
let pubKey = try! getPublicKey(from: kPubKey.data(using: .utf8)!) // Error: RSA public key creation from data failed
let decryptedData = decrypt(key: pubKey, data: decodedData)!
let decrypted = String.init(data: decryptedData, encoding: .utf8)!
print(">>>>>>> decrypted string: \(decrypted)")
}
testDecrypt()
With method of Kazunori Takaishi, I tested all the algorithm, none of them is supported:
func decrypt(key: SecKey, data cipherTextData: Data) -> Data? {
let algorithms: [SecKeyAlgorithm] = [
.rsaSignatureRaw,
.rsaSignatureDigestPKCS1v15Raw,
.rsaSignatureDigestPKCS1v15SHA1,
.rsaSignatureDigestPKCS1v15SHA224,
.rsaSignatureDigestPKCS1v15SHA256,
.rsaSignatureDigestPKCS1v15SHA384,
.rsaSignatureDigestPKCS1v15SHA512,
.rsaSignatureMessagePKCS1v15SHA1,
.rsaSignatureMessagePKCS1v15SHA224,
.rsaSignatureMessagePKCS1v15SHA256,
.rsaSignatureMessagePKCS1v15SHA384,
.rsaSignatureMessagePKCS1v15SHA512,
.rsaSignatureDigestPSSSHA1,
.rsaSignatureDigestPSSSHA224,
.rsaSignatureDigestPSSSHA256,
.rsaSignatureDigestPSSSHA384,
.rsaSignatureDigestPSSSHA512,
.rsaSignatureMessagePSSSHA1,
.rsaSignatureMessagePSSSHA224,
.rsaSignatureMessagePSSSHA256,
.rsaSignatureMessagePSSSHA384,
.rsaSignatureMessagePSSSHA512,
.ecdsaSignatureRFC4754,
.ecdsaSignatureDigestX962,
.ecdsaSignatureDigestX962SHA1,
.ecdsaSignatureDigestX962SHA224,
.ecdsaSignatureDigestX962SHA256,
.ecdsaSignatureDigestX962SHA384,
.ecdsaSignatureDigestX962SHA512,
.ecdsaSignatureMessageX962SHA1,
.ecdsaSignatureMessageX962SHA224,
.ecdsaSignatureMessageX962SHA256,
.ecdsaSignatureMessageX962SHA384,
.ecdsaSignatureMessageX962SHA512,
.rsaEncryptionRaw,
.rsaEncryptionPKCS1,
.rsaEncryptionOAEPSHA1,
.rsaEncryptionOAEPSHA224,
.rsaEncryptionOAEPSHA256,
.rsaEncryptionOAEPSHA384,
.rsaEncryptionOAEPSHA512,
.rsaEncryptionOAEPSHA1AESGCM,
.rsaEncryptionOAEPSHA224AESGCM,
.rsaEncryptionOAEPSHA256AESGCM,
.rsaEncryptionOAEPSHA384AESGCM,
.rsaEncryptionOAEPSHA512AESGCM,
.eciesEncryptionStandardX963SHA1AESGCM,
.eciesEncryptionStandardX963SHA224AESGCM,
.eciesEncryptionStandardX963SHA256AESGCM,
.eciesEncryptionStandardX963SHA384AESGCM,
.eciesEncryptionStandardX963SHA512AESGCM,
.eciesEncryptionCofactorX963SHA1AESGCM,
.eciesEncryptionCofactorX963SHA224AESGCM,
.eciesEncryptionCofactorX963SHA256AESGCM,
.eciesEncryptionCofactorX963SHA384AESGCM,
.eciesEncryptionCofactorX963SHA512AESGCM,
.eciesEncryptionStandardVariableIVX963SHA224AESGCM,
.eciesEncryptionStandardVariableIVX963SHA256AESGCM,
.eciesEncryptionStandardVariableIVX963SHA384AESGCM,
.eciesEncryptionStandardVariableIVX963SHA512AESGCM,
.eciesEncryptionCofactorVariableIVX963SHA224AESGCM,
.eciesEncryptionCofactorVariableIVX963SHA256AESGCM,
.eciesEncryptionCofactorVariableIVX963SHA384AESGCM,
.eciesEncryptionCofactorVariableIVX963SHA512AESGCM,
.ecdhKeyExchangeStandard,
.ecdhKeyExchangeStandardX963SHA1,
.ecdhKeyExchangeStandardX963SHA224,
.ecdhKeyExchangeStandardX963SHA256,
.ecdhKeyExchangeStandardX963SHA384,
.ecdhKeyExchangeStandardX963SHA512,
.ecdhKeyExchangeCofactor,
.ecdhKeyExchangeCofactorX963SHA1,
.ecdhKeyExchangeCofactorX963SHA224,
.ecdhKeyExchangeCofactorX963SHA256,
.ecdhKeyExchangeCofactorX963SHA384,
.ecdhKeyExchangeCofactorX963SHA512
]
for a in algorithms {
if SecKeyIsAlgorithmSupported(key, .decrypt, a) {
print(">>>>>>>>>>>>> supported algorithm: \(a)")
}
}
//==================
let algorithm: SecKeyAlgorithm = .rsaEncryptionPKCS1 // .rsaSignatureMessagePKCS1v15SHA256 // .rsaSignatureDigestPKCS1v15SHA1 // .rsaSignatureDigestPKCS1v15Raw // .rsaSignatureDigestPKCS1v15SHA256 //.rsaEncryptionPKCS1
// guard SecKeyIsAlgorithmSupported(key, .decrypt, algorithm) else {
// print("Can't decrypt. Algorithm not supported.")
// return nil
// }
var error: Unmanaged<CFError>? = nil
let clearTextData = SecKeyCreateDecryptedData(key,
algorithm,
cipherTextData as CFData,
&error) as Data?
if let error = error {
print("Can't decrypt. \((error.takeRetainedValue() as Error).localizedDescription)")
return nil
}
guard clearTextData != nil else {
print("Can't decrypt. No resulting cleartextData.")
return nil
}
print("Decrypted data.")
return clearTextData
}
If your code only works on Mac OS, you may be able to create a Seckey by using the SecKeyCreateFromData method instead of the SecKeyCreateWithData method.
Here is Sample Code:
func getPublicKey(from data: Data?) throws -> SecKey {
var error: Unmanaged<CFError>? = nil
guard let data = data else { throw error!.takeRetainedValue() as Error }
let publicKeyMaybe = SecKeyCreateFromData([:] as CFDictionary, data as NSData, &error)
guard let publicKey = publicKeyMaybe else {
throw error!.takeRetainedValue() as Error
}
return publicKey
}
And You should convert RSA public key string to data using ASCII encoding.
let pubKey = try! getPublicKey(from: kPubKey.data(using: .ascii))

I can't Unwrap a value from a plist key value

I'm new to swift and I'm trying to load a property from a nsDictionary to vTitle
var nsDictionary: NSDictionary?
if let path = Bundle.main.path(forResource: "AppData", ofType: "plist") {
nsDictionary = NSDictionary(contentsOfFile: path)
}
let vTitle:String = nsDictionary["LbVacationsTitle"]
When I debug I see the right keys in nsDictionary but I can't unwrap the value of just one key
The type of LbVacationsTitle is a string
Depending on your style preference...
var nsDictionary: NSDictionary?
if let path = Bundle.main.path(forResource: "AppData", ofType: "plist") {
nsDictionary = NSDictionary(contentsOfFile: path)
}
if let dict = nsDictionary {
let vTitle = dict["LbVacationsTitle"] as? String
if let vt = vTitle {
// ...
}
}
...or...
var nsDictionary: NSDictionary?
if let path = Bundle.main.path(forResource: "AppData", ofType: "plist") {
nsDictionary = NSDictionary(contentsOfFile: path)
}
guard let dict = nsDictionary else {
print("Couldn't get a valid dictionary")
return
}
let vTitle = dict["LbVacationsTitle"] as? String
guard let vt = vTitle else {
print("Couldn't find a string matching LbVacationsTitle")
return
}
// ...
Please don't use the NSDictionary API in Swift to read a property list.
There is PropertyListSerialization (or even PropertyListDecoder)
let url = Bundle.main.url(forResource: "AppData", withExtension: "plist")!
let data = try! Data(contentsOf: url)
let dictionary = try! PropertyListSerialization.propertyList(from: data, format: nil) as! [String:Any]
let vTitle = dictionary["LbVacationsTitle"] as! String
As the file is immutable in the application bundle any crash reveals a design mistake

Encryption in swift using Security framework

I've been trying to encrypt and decrypt a string in swift using a Diffie Hellman key exchange and an elliptic curve encryption. But after the key exchange I can't restore a private key from a CFData shared1/shared2 variable for decryption. All i get is nil value.
let attributes: [String: Any] = [kSecAttrKeySizeInBits as String: 256,
kSecAttrKeyType as String: kSecAttrKeyTypeEC,
kSecPrivateKeyAttrs as String: [kSecAttrIsPermanent as String: false]]
var error: Unmanaged<CFError>?
if #available(iOS 10.0, *) {
guard let privateKey1 = SecKeyCreateRandomKey(attributes as CFDictionary, &error) else {return}
let publicKey1 = SecKeyCopyPublicKey(privateKey1)
guard let privateKey2 = SecKeyCreateRandomKey(attributes as CFDictionary, &error) else {return}
let publicKey2 = SecKeyCopyPublicKey(privateKey2)
let dict: [String: Any] = [:]
guard let shared1 = SecKeyCopyKeyExchangeResult(privateKey1, SecKeyAlgorithm.ecdhKeyExchangeStandardX963SHA256, publicKey2!, dict as CFDictionary, &error) else {return}
guard let shared2 = SecKeyCopyKeyExchangeResult(privateKey2, SecKeyAlgorithm.ecdhKeyExchangeStandardX963SHA256, publicKey1!, dict as CFDictionary, &error) else {return}
print(shared1==shared2)
let options: [String: Any] = [kSecAttrKeyType as String: kSecAttrKeyTypeEC,
kSecAttrKeyClass as String: kSecAttrKeyClassPrivate,
kSecAttrKeySizeInBits as String : 256]
guard let key = SecKeyCreateWithData(shared1 as CFData,
options as CFDictionary,
&error) else {return}
print(key)
let str = "Hello"
let byteStr: [UInt8] = Array(str.utf8)
let cfData = CFDataCreate(nil, byteStr, byteStr.count)
guard let encrypted = SecKeyCreateEncryptedData(publicKey1!,
SecKeyAlgorithm.eciesEncryptionStandardX963SHA256AESGCM,
cfData!,
&error) else {return}
guard let decrypted = SecKeyCreateDecryptedData(key,
SecKeyAlgorithm.eciesEncryptionStandardX963SHA256AESGCM,
encrypted,
&error) else {return}
print(decrypted)
} else {
print("unsupported")
}
SecKeyFromData Restores a key from an external representation of that key. The value you're passing to it is not an external representation of a key, it's a shared secret(CFData) just some bytes. You have to derive a key using some KDF on the shared secret then you can use it for encryption and decryption.
And the keys you're using for encryption and decryption are wrong, you have to choose if you want to do asymmetric or symmetric encryption.
SecKeyFromData:
https://developer.apple.com/documentation/security/1643701-seckeycreatewithdata

Encoded JWT using PKCS8 RSA256 algorithm on jwt.io but not in application

I has a problem when I try to implementing JWT in swift 4.
I use JWT library from jwt.io.
I am trying to encrypt the payload with the PKCS8 pem filetype and RSA256 algorithm certificate.
but always error with message "The operation could not be completed. (OSStatus error -50 - RSA private key creation from data failed)"
can someone help me?
code:
let payload: [AnyHashable:Any] = ["payload":"hiden_information"]
let algorithmName = "RS256"
let path = Bundle.main.path(forResource: "priv", ofType: "pem")
let privateKeySecretData = try? Data(contentsOf: URL(fileURLWithPath: path!))
let privateKey = String(data: privateKeySecretData!, encoding: .utf8)!
let signDataHolder: JWTAlgorithmRSFamilyDataHolder = JWTAlgorithmRSFamilyDataHolder()
_ = signDataHolder.keyExtractorType(JWTCryptoKeyExtractor.privateKeyWithPEMBase64().type)
_ = signDataHolder.algorithmName(algorithmName)
_ = signDataHolder.secret(privateKey)
let signBuilder : JWTEncodingBuilder = JWTEncodingBuilder.encodePayload(payload)
_ = signBuilder.addHolder(signDataHolder)
let signResult = signBuilder.result
if ((signResult?.successResult) != nil) {
print(signResult!.successResult.encoded)
} else {
print(signResult?.errorResult.error.localizedDescription ?? "Unknown")
}
JWT version 3.0.0.-beta7 not suported PKCS8.
i use PKCS1 with RSA256 and it worked!
func encryptPayload(payload:[AnyHashable:Any])->String?
{
var resultStr: String?
var publicKeyCrypto: JWTCryptoKeyProtocol? = nil
do {
publicKeyCrypto = try JWTCryptoKeyPublic(pemEncoded: AppConstant.Scurity.publicKey, parameters: nil)
}
catch {
NSLog("error: \(error)")
}
guard let theCrypto = publicKeyCrypto else {
return nil
}
do {
let privateKeyCrypto = try JWTCryptoKeyPrivate(pemEncoded: privateKey, parameters: nil)
guard let holder = JWTAlgorithmRSFamilyDataHolder().signKey(privateKeyCrypto)?.secretData(AppConstant.Scurity.privateKey.data(using: .utf8))?.algorithmName(JWTAlgorithmNameRS256) else {return nil}
let headers : [AnyHashable:Any] = ["alg": "RS256","typ": "JWT"]
guard let encoding = JWTEncodingBuilder.encodePayload(payload).headers(headers)?.addHolder(holder) else {return nil}
let result = encoding.result
print(result?.successResult?.encoded ?? "Encoding failed")
print(result?.errorResult?.error ?? "No encoding error")
let verifyDataHolder = JWTAlgorithmRSFamilyDataHolder().signKey(theCrypto)?.secretData(publicKey.data(using: .utf8)!)?.algorithmName(JWTAlgorithmNameRS256)
let verifyResult = JWTDecodingBuilder.decodeMessage(result?.successResult?.encoded).addHolder(verifyDataHolder)?.result
if verifyResult?.successResult != nil, let result = verifyResult?.successResult.encoded {
print("Verification successful, result: \(result)")
} else {
print("Verification error: \(verifyResult!.errorResult.error)")
}
resultStr = result?.successResult.encoded
} catch {
print(error)
}
return resultStr
}

Swift sign string with digital signature

I have project where I need to sign string(raw or base64 encoded) with private digital signature (that has password). I searched on internet and found that private digital certificate is x.509 format(RSA). In xcode I set UIFileSharingEnabled to Enabled and uploaded that rsa.p12 certificate using Itunes. Next I get the certificate from document directory in (data or string) format. My question is how can I encrypt any text using digital signature?
I tried to use this lib https://github.com/TakeScoop/SwiftyRSA/issues but this lib does not support x.509 certificate.
I just found the code which encodes string text and it works
func signRequestorId(requestorID: String) -> String? {
let name = "RSA256_4f1826090c554a439c419043270d40f7d.p12"
guard let certificateData = CustomFileManager.getFile(by: name) else {
return nil
}
var status: OSStatus
let certificateKey = "123456"
let options = [kSecImportExportPassphrase as String : certificateKey]
var optItems: CFArray?
status = SecPKCS12Import(certificateData as CFData, options as CFDictionary, &optItems)
if status != errSecSuccess {
print("Cannot sign the device id info: failed importing keystore.")
return nil
}
guard let items = optItems else {
return nil
}
// Cast CFArrayRef to Swift Array
let itemsArray = items as [AnyObject]
// Cast CFDictionaryRef as Swift Dictionary
guard let myIdentityAndTrust = itemsArray.first as? [String : AnyObject] else {
return nil
}
// Get our SecIdentityRef from the PKCS #12 blob
let outIdentity = myIdentityAndTrust[kSecImportItemIdentity as String] as! SecIdentity
var myReturnedCertificate: SecCertificate?
status = SecIdentityCopyCertificate(outIdentity, &myReturnedCertificate)
if status != errSecSuccess {
print("Failed to retrieve the certificate associated with the requested identity.")
return nil
}
// Get the private key associated with our identity
var optPrivateKey: SecKey?
status = SecIdentityCopyPrivateKey(outIdentity, &optPrivateKey)
if status != errSecSuccess {
print("Failed to extract the private key from the keystore.")
return nil
}
// Unwrap privateKey from optional SecKeyRef
guard let privateKey = optPrivateKey else {
return nil
}
// Retrieve the digital signature and sign the requestor
// Get the maximum size of the digital signature
var signedBytesSize: size_t = SecKeyGetBlockSize(privateKey)
var signedBytes: UnsafeMutablePointer<UInt8>
// alloc a buffer to hold the signature
signedBytes = UnsafeMutablePointer<UInt8>.allocate(capacity: signedBytesSize)
memset(signedBytes, 0x0, signedBytesSize)
// We're calling alloc here, so we need to destroy and deinit
defer {
signedBytes.deinitialize()
signedBytes.deallocate(capacity: signedBytesSize)
}
// Sign data
let requestorData = requestorID.data(using: String.Encoding.utf8)!
// Generate a digital signature for our requestor from our cert
let buffer = UnsafeMutablePointer<UInt8>.allocate(capacity: requestorData.count)
let stream = OutputStream(toBuffer: buffer, capacity: requestorData.count)
stream.open()
requestorData.withUnsafeBytes({ (p: UnsafePointer<UInt8>) -> Void in
stream.write(p, maxLength: requestorData.count)
})
stream.close()
let weidformat = UnsafePointer<UInt8>(buffer)
status = SecKeyRawSign(privateKey, .PKCS1, weidformat,
requestorData.count, signedBytes, &signedBytesSize)
if status != errSecSuccess {
print("Cannot sign the device id info: failed obtaining the signed bytes.")
return nil
}
let encryptedBytes = NSData(bytes: signedBytes, length: signedBytesSize)
let signedRequestorId = encryptedBytes.base64EncodedString(options: [])
print(signedRequestorId)
return signedRequestorId
}
U also need function get document by name
static func getFile(by name: String)-> Data?{
let documentsUrl = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first
let destinationUrl = documentsUrl!.appendingPathComponent("\(name)")
let isFileFound = FileManager.default.fileExists(atPath: destinationUrl.path)
if isFileFound {
let documentContent = FileManager.default.contents(atPath: destinationUrl.path)
return documentContent
}
return nil
}
enter code here