takescoop / swiftyrsa Goto Github PK
View Code? Open in Web Editor NEWRSA public/private key encryption in Swift
License: MIT License
RSA public/private key encryption in Swift
License: MIT License
Carthage installation fails because of a directory not found error.
ld: warning: directory not found for option '-F/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS9.3.sdk/Developer/Library/Frameworks'
ld: warning: directory not found for option '-F/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS9.3.sdk/Developer/Library/Frameworks'
ld: warning: directory not found for option '-F/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator9.3.sdk/Developer/Library/Frameworks'
ld: warning: directory not found for option '-F/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator9.3.sdk/Developer/Library/Frameworks'
Any plans for Swift 3.0?
I just upgraded SwiftyRSA and now I'm using the code from the master branch. I'm trying to get the public key from a .der file that existis on the main bundle. Here's what I'm trying to do:
PublicKey *pubKey = [[PublicKey alloc] initWithDerNamed:@"certfile443" in:[NSBundle mainBundle] error:&error];
NSLog(@"key: %@ - %@", pubKey, error);
pubKey is always null. What am I doing wrong?
The only framework that shows up to add as an embedded binary is for tvOS
As suggested by @rsaarloos in #47 (comment)
We are getting 7 warning against the swift 3.0 release update. Please update as per the latest syntax.
Hello,
I have been using your library in production for the past 6 months or so, but after upgrading to Swift 3, I can no longer verify signatures for messages signed on our CentOS server. I am using the exact same server-side script & keys to sign the messages as I did before upgrading to Swift 3.
Here is how the server keys were generated:
ssh-keygen -t rsa -f serverkey -N '' -b 2048
mv serverkey serverkey-priv.pem
ssh-keygen -f serverkey.pub -e -m pem > serverkey-pub.pem ; rm -f serverkey.pub
I sign the message like this:
cat message | openssl dgst -sha256 -sign serverkey-priv.pem -out signature.bin
Then I base64-encode signature.bin and send the message along with the base64-encoded signature to the iOS device where I try to verify the signature like this:
set verificationResult = SwiftyRSA.verifySignatureString(stringToVerify, signature: signature, publicKeyPEM: serverKey, digestMethod: .SHA256)
The problem is that verificationResult.isSuccessful returns false. The error property is:
Error Domain=com.takescoop.SwiftyRSA Code=500 "Couldn't decode PEM key data (base64)" UserInfo={NSLocalizedDescription=Couldn't decode PEM key data (base64)}
Here is the message:
Raw message, 1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ, very sensitive information!!
The signature (base64-encoded hash):
p9+ID34iW9+ff+2S25GY0fViWzdQgCwZIwFRZAPEk6/onODvmq3wa1471btGuez+0dtUZ3f2z3Mii7x0mmPcn0cZEvjFWVQrI0+woDd3/hcOkpIdYUHAQmaRVOARx5PZgHF0LosPf6aP1ePhHUmrJHwyTmfok+tjcZwtCaeJCQYaSFqTE3F6c78guMEaq83vg/zsBBceBlAhQSCZb3lhIJZqu8Y2AHyDpuCfrANURx8XkYwcxu5ark+/YGIdkNqrrkeg5X2daph+Qfefn8ikq/kL9wTnleJ9miKDKQVc5YqKhwhhv5Y6nZ86wVeS9+uv/Yz6HS7wwxbwRJJ28w28ZQ==
Attached is a zip file with the actual message, hash and key pair used.
Help with this would be much appreciated!
Hello,
This project has been very helpful. I recently upgraded to Swift 3, and I encountered an interesting issue. I found out that there is a slight difference in behavior due to no longer specifying to ignore unknown characters in the dataFromPEMKey function. I was able to get my app to work by adding the .ignoreUnknownCharacters option:
let keyData = Data(base64Encoded: base64EncodedKey, options: [.ignoreUnknownCharacters])
Thank you.
As the title reads. Currently in Master branch there are improvements with regards to SHA2, but if you 'just' pull the latest known CocoaPods version (0.3.0) you will not get these improvements.
I am trying to decrypt a string encrypted by node crypto .
Error:
fatal error: 'try!' expression unexpectedly raised an error: Error Domain=com.takescoop.SwiftyRSA Code=500 "Couldn't convert decrypted data to UTF8 string" UserInfo={NSLocalizedDescription=Couldn't convert decrypted data to UTF8 string}: file /Library/Caches/com.apple.xbs/Sources/swiftlang/swiftlang-703.0.18.8/src/swift/stdlib/public/core/ErrorType.swift, line 54
==================Code ====================
/-------Able to get decryptedData bytes but utf-8 conversion fails------/
let decryptedData = try decryptData(data, privateKey: privateKey, padding: padding)
guard let decryptedString = NSString(data: decryptedData, encoding: NSUTF8StringEncoding) else {
throw SwiftyRSAError(message: "Couldn't convert decrypted data to UTF8 string")
}
Current pod 0.5.0 doesn't build under ios10/xcode8
-- Im not talking about swift 3 support :D I mean: it fails in legacy mode
Is it possible to get the public key in PEM String format with SwiftyRSA, or is using the CryptoExportImportManager still the best option?
Because i can't get the Manager to work in Swift 3.0.
I have a .cer file on my bundle.
NSString *pass = [SwiftyRSA encryptString:password publicKeyDER:publicKeyData padding:kSecPaddingPKCS1 error:nil];
How to extract the publicKey from a .cer file and use it?
Hi @ldiqual, thanks for this library. Very cool.
Is there an issue with the latest commit and publicKeyFromPEMString(pubString)?
In my Swift playground, I found the following:
privateKeyFromPEMString works.
publicKeyFromDERData works.
publicKeyFromPEMString fails.
Example to show you the error:
let rsa = SwiftyRSA()
let pubPath: String = NSBundle.mainBundle().pathForResource("public", ofType: "pem")!
if NSFileManager().fileExistsAtPath(pubPath) {
do {
let pubString = try NSString(contentsOfFile: pubPath, encoding: NSUTF8StringEncoding) as String
print(pubString)
// let pubKey = try rsa.publicKeyFromPEMString(pubString)
} catch let error as NSError {
print(error.code)
print(error.description)
}
}
Hey, I am trying to integrate with an API which uses BouncyCastle encryption, so the server is not able to decrypt the data which i am encrypting using SwiftyRSA.
Am i doing something wrong or it won't work because it is using Bouncy Castle?
Kindly Help.
What could I possibly be doing wrong here? I added pod 'SwiftyRSA', '~> 0.5'
to my Podfile, installed Pods... no issues. I open up XCode, add import SwiftyRSA
to the top of my Swift file, now when I add let publicKey = try PublicKey(pemEncoded: pemString)
I get a compiler error:
Use of Unresolved Identifier 'PublicKey'
Currently we can instantiate, e.g., a PublicKey with Data or a PEM string, but we cannot get these representations back if we already have a PublicKey.
It would be very useful if it were possible to at least get the raw data back.
See SecKeyEncrypt SecPaddingNone iOS
I am basically doing encryption with two keys. The first step, using key A, uses SecPaddingPKCS1 and gives me an output of 256 bytes. After that, using Key B, I use SecPaddingNone. I assume that my output will remain 256 bytes, but it becomes 512 bytes. I am not sure what I am doing wrong, does anyone know? Am I thinking about this wrong?
Need to generate a public and private key for the lifetime of the device. Gone several paths before finally ending up in SwiftyRSA. Initial device is iOS 8.3 (target 8.0) in XCODE8.
// Public key (PEM)
if let pubPath = bundle.path(forResource: "public", ofType: "pem") {
let pubString = try String(contentsOfFile: pubPath, encoding: String.Encoding.utf8)
self.PublicKey = try rsa.publicKeyFromPEMString(pubString)
} else {
print("Unable to generate Public Key")
}
pubPath always returns nil
How can I use this on my Objective-C project?
Hi there,
I would like to use your lib because it perfectly fits my needs.
Nevertheless I am encountering an issue.
I installed it through cocoapod (v 0.5.0)
When used :
let clear = try ClearMessage(string: "Clear Text", using: .utf8) let encrypted = try clear.encrypted(with: publicKey, padding: .PKCS1)
I get this error:
Use of unresolved identifier ‘ClearMessage’
I have cleaned my project, restarted xcode but nothing works.
Any idea regarding this matter?
Thanks for your time
I am unable to verify signatures generated on a CentOS server on the iOS device using SwiftyRSA.
The server keys are generated like this (note that I have also tried with "-m pkcs8" instead of "-m pem" for the last command, but it did not help):
ssh-keygen -t rsa -f serverkey -N '' -b 2048
mv serverkey serverkey-priv.pem
ssh-keygen -f serverkey.pub -e -m pem > serverkey-pub.pem ; rm -f serverkey.pub
I can encrypt on the iOS device using the server's public key and then decrypt on the CentOS server just fine.
But I also need to sign messages on the server and verify the signature on the iOS device. I am using SHA1 for the initial testing (will switch to SHA2 after that, thanks!).
Here is what I do:
Then I try to verify with:
let verificationResult = try SwiftyRSA.verifySignatureString(message, signature: base64EncodedSignatureFromServer, publicKeyPEM: serverKey)
No exception is thrown, but verificationResult.boolValue is false.
Here is some sample data that I tested with:
Hash:
7de293556cdd9cef2bc4fa497ac7a0df157d7292
Base64 encoded signature (of the encrypted above hash):
wxeuaqOJ3+y1GLumOeSW9M7Jars21EswqtYSc2ujbJciGTwk6Bcn3PXJ4jFBW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7F0kCgYEAwEwG5VEJn6DUix8xT+dKdauu+AxZZeVgfMWFvhSA9ss9ApCCvh93
OoyfxjagKhwg837Tx3NcjmP3ZNVUNHrOflbjwbz1QZ6u71rML/4zZBjU4PY/3qJV
XFoFC9ZoEebOZBluokIIdL1Hw5kEHpaYTW5nDHuoVYH5yRjvCqOJ0Oo=
-----END RSA PRIVATE KEY-----
If you could let me know what I am doing wrong, it would be great!
Thanks!
Hi, im using your hub to encrypt and everything works like charm, but decrypt doesn't work, throws me this error : Error Domain=com.takescoop.SwiftyRSA Code=500 "Couldn't get key reference from the keychain" UserInfo={NSLocalizedDescription=Couldn't get key reference from the keychain}: file /Library/Caches/com.apple.xbs/Sources/swiftlang/swiftlang-703.0.18.8/src/swift/stdlib/public/core/ErrorType.swift, line 54, can you help me ?
...
// String
let signatureString = try! SwitfyRSA.signString(str, privateKeyPEM: pemString)
...
->
let signatureString = try! SwitfyRSA.signString(str, privateKeyPEM: pemString)
In SwiftyRSA.addKey
let sizeInBits = keyData.count * MemoryLayout<UInt8>.size
let keyDict: [CFString: Any] = [
kSecAttrKeyType: kSecAttrKeyTypeRSA,
kSecAttrKeyClass: keyClass,
kSecAttrKeySizeInBits: NSNumber(value: sizeInBits)
]
keyData.count
returns count of bytes
.
MemoryLayout<UInt8>.size
returns count of bytes
per UInt8 object ( 8 bits = 1 byte ). So, it returns 1 byte.
keyData.count * MemoryLayout<UInt8>.size = (count of bytes in keyData) * (bytes per UInt8) = count * 1 byte = count of bytes in whole keyData object.
So,
sizeOfBits != count of bits in keyData.
Is it correct?
// ios 9 and below.
var secStatus = SecItemAdd(keyAddDict as CFDictionary, persistKey)
if secStatus != noErr && secStatus != errSecDuplicateItem {
throw SwiftyRSAError(message: "Provided key couldn't be added to the keychain")
}
let keyCopyDict: [CFString: Any] = [
kSecClass: kSecClassKey,
kSecAttrApplicationTag: tagData,
kSecAttrKeyType: kSecAttrKeyTypeRSA,
kSecAttrKeyClass: keyClass,
kSecAttrAccessible: kSecAttrAccessibleWhenUnlocked,
kSecReturnRef: NSNumber(value: true),
]
// Now fetch the SecKeyRef version of the key
var keyRef: AnyObject? = nil
secStatus = SecItemCopyMatching(keyCopyDict as CFDictionary, &keyRef)
guard let unwrappedKeyRef = keyRef else {
throw SwiftyRSAError(message: "Couldn't get key reference from the keychain")
}
return unwrappedKeyRef as! SecKey
I thought that noErr
could be changed to errSecSuccess
.
And you don't use secStatus
in copy section.
After cleanup:
let addItemStatus = SecItemAdd(keyAddDict as CFDictionary, persistKey)
if addItemStatus != errSecSuccess && addItemStatus != errSecDuplicateItem {
throw SwiftyRSAError(message: "Provided key couldn't be added to the keychain")
}
let keyCopyDict: [CFString: Any] = [
kSecClass: kSecClassKey,
kSecAttrApplicationTag: tagData,
kSecAttrKeyType: kSecAttrKeyTypeRSA,
kSecAttrKeyClass: keyClass,
kSecAttrAccessible: kSecAttrAccessibleWhenUnlocked,
kSecReturnRef: NSNumber(value: true),
]
// Now fetch the SecKeyRef version of the key
var keyRef: AnyObject? = nil
_ = SecItemCopyMatching(keyCopyDict as CFDictionary, &keyRef)
guard let unwrappedKeyRef = keyRef else {
throw SwiftyRSAError(message: "Couldn't get key reference from the keychain")
}
return unwrappedKeyRef as! SecKey
Thanks for your library!
Thanks for writing this useful library!
Can this library be used to generate an RSA key pair on the iOS device (as opposed to generating the keys on a server)? If not, any suggestion on another library that will generate PEM keys that are compatible with this library?
Any plans to add support for SHA2 for message digests / signatures?
Compilation error in Xcode 8.2.1 (on Mac OS Sierra 10.12.3):
wiftyRSA Group
Swift Compiler Error Group
//Pods/SwiftyRSA/SwiftyRSA/SwiftyRSA.swift:507:46: Expected ',' joining parts of a multi-clause condition
//Pods/SwiftyRSA/SwiftyRSA/SwiftyRSA.swift:31:44: 'BooleanType' has been renamed to 'Bool'
//Pods/SwiftyRSA/SwiftyRSA/SwiftyRSA.swift:269:55: 'SecKeyRef' has been renamed to 'SecKey'
//Pods/SwiftyRSA/SwiftyRSA/SwiftyRSA.swift:277:56: 'SecKeyRef' has been renamed to 'SecKey'
//Pods/SwiftyRSA/SwiftyRSA/SwiftyRSA.swift:208:54: 'SecKeyRef' has been renamed to 'SecKey'
//Pods/SwiftyRSA/SwiftyRSA/SwiftyRSA.swift:240:64: 'SecKeyRef' has been renamed to 'SecKey'
//Pods/SwiftyRSA/SwiftyRSA/SwiftyRSA.swift:305:53: 'SecKeyRef' has been renamed to 'SecKey'
//Pods/SwiftyRSA/SwiftyRSA/SwiftyRSA.swift:323:52: 'SecKeyRef' has been renamed to 'SecKey'
//Pods/SwiftyRSA/SwiftyRSA/SwiftyRSA.swift:378:82: 'SecKeyRef' has been renamed to 'SecKey'
//Pods/SwiftyRSA/SwiftyRSA/SwiftyRSA.swift:404:85: 'SecKeyRef' has been renamed to 'SecKey'
//Pods/SwiftyRSA/SwiftyRSA/SwiftyRSA.swift:193:65: 'SecKeyRef' has been renamed to 'SecKey'
//Pods/SwiftyRSA/SwiftyRSA/SwiftyRSA.swift:197:63: 'SecKeyRef' has been renamed to 'SecKey'
//Pods/SwiftyRSA/SwiftyRSA/SwiftyRSA.swift:202:64: 'SecKeyRef' has been renamed to 'SecKey'
//Pods/SwiftyRSA/SwiftyRSA/SwiftyRSA.swift:339:60: 'SecKeyRef' has been renamed to 'SecKey'
//Pods/SwiftyRSA/SwiftyRSA/SwiftyRSA.swift:422:89: 'SecKeyRef' has been renamed to 'SecKey'
//Pods/SwiftyRSA/SwiftyRSA/SwiftyRSA.swift:444:68: 'SecKeyRef' has been renamed to 'SecKey'
/SwiftyRSA/SwiftyRSA/SwiftyRSA.swift:212:80: Argument 'repeatedValue' must precede argument 'count'
//Pods/SwiftyRSA/SwiftyRSA/SwiftyRSA.swift:215:47: Argument 'repeatedValue' must precede argument 'count'
//Pods/SwiftyRSA/SwiftyRSA/SwiftyRSA.swift:243:89: Argument 'repeatedValue' must precede argument 'count'
//Pods/SwiftyRSA/SwiftyRSA/SwiftyRSA.swift:246:47: Argument 'repeatedValue' must precede argument 'count'
//Pods/SwiftyRSA/SwiftyRSA/SwiftyRSA.swift:270:30: 'dataUsingEncoding(:allowLossyConversion:)' has been renamed to 'data(usingEncoding:allowLossyConversion:)'
//Pods/SwiftyRSA/SwiftyRSA/SwiftyRSA.swift:270:48: 'NSUTF8StringEncoding' has been renamed to 'String.Encoding.utf8'
//Pods/SwiftyRSA/SwiftyRSA/SwiftyRSA.swift:278:27: 'init(base64EncodedString:options:)' has been renamed to 'init(base64Encoded:options:)'
//Pods/SwiftyRSA/SwiftyRSA/SwiftyRSA.swift:306:28: 'dataUsingEncoding(:allowLossyConversion:)' has been renamed to 'data(usingEncoding:allowLossyConversion:)'
//Pods/SwiftyRSA/SwiftyRSA/SwiftyRSA.swift:306:46: 'NSUTF8StringEncoding' has been renamed to 'String.Encoding.utf8'
//Pods/SwiftyRSA/SwiftyRSA/SwiftyRSA.swift:325:25: 'SHA1()' has been renamed to 'sha1()'
//Pods/SwiftyRSA/SwiftyRSA/SwiftyRSA.swift:348:77: Argument 'repeatedValue' must precede argument 'count'
//Pods/SwiftyRSA/SwiftyRSA/SwiftyRSA.swift:381:28: 'dataUsingEncoding(_:allowLossyConversion:)' has been renamed to 'data(usingEncoding:allowLossyConversion:)'
//Pods/SwiftyRSA/SwiftyRSA/SwiftyRSA.swift:381:46: 'NSUTF8StringEncoding' has been renamed to 'String.Encoding.utf8'
//Pods/SwiftyRSA/SwiftyRSA/SwiftyRSA.swift:385:35: 'init(base64EncodedString:options:)' has been renamed to 'init(base64Encoded:options:)'
//Pods/SwiftyRSA/SwiftyRSA/SwiftyRSA.swift:406:25: 'SHA1()' has been renamed to 'sha1()'
//Pods/SwiftyRSA/SwiftyRSA/SwiftyRSA.swift:424:81: Argument 'repeatedValue' must precede argument 'count'
//Pods/SwiftyRSA/SwiftyRSA/SwiftyRSA.swift:427:85: Argument 'repeatedValue' must precede argument 'count'
//Pods/SwiftyRSA/SwiftyRSA/SwiftyRSA.swift:453:28: 'UUIDString' has been renamed to 'uuidString'
//Pods/SwiftyRSA/SwiftyRSA/SwiftyRSA.swift:454:54: 'lengthOfBytesUsingEncoding' has been renamed to 'lengthOfBytes(using:)'
//Pods/SwiftyRSA/SwiftyRSA/SwiftyRSA.swift:454:81: 'NSUTF8StringEncoding' has been renamed to 'String.Encoding.utf8'
//Pods/SwiftyRSA/SwiftyRSA/SwiftyRSA.swift:455:30: Missing argument label 'tagData:' in call
//Pods/SwiftyRSA/SwiftyRSA/SwiftyRSA.swift:458:26: Ambiguous use of 'init'
//Pods/SwiftyRSA/SwiftyRSA/SwiftyRSA.swift:468:27: 'init(bool:)' has been renamed to 'init(value:)'
//Pods/SwiftyRSA/SwiftyRSA/SwiftyRSA.swift:480:17: 'removeObjectForKey' has been renamed to 'removeObject(forKey:)'
//Pods/SwiftyRSA/SwiftyRSA/SwiftyRSA.swift:481:17: 'removeObjectForKey' has been renamed to 'removeObject(forKey:)'
//Pods/SwiftyRSA/SwiftyRSA/SwiftyRSA.swift:482:27: 'init(bool:)' has been renamed to 'init(value:)'
//Pods/SwiftyRSA/SwiftyRSA/SwiftyRSA.swift:495:21: Value of type 'String' has no member 'componentsSeparatedByString'
//Pods/SwiftyRSA/SwiftyRSA/SwiftyRSA.swift:542:38: 'sizeof' is unavailable: use MemoryLayout.size instead.
//Pods/SwiftyRSA/SwiftyRSA/SwiftyRSA.swift:548:47: Argument 'repeatedValue' must precede argument 'count'
//Pods/SwiftyRSA/SwiftyRSA/SwiftyRSA.swift:607:36: 'CFDictionaryRef' has been renamed to 'CFDictionary'
//Pods/SwiftyRSA/SwiftyRSA/SwiftyRSA.swift:612:34: Missing argument label 'tagData:' in call
//Pods/SwiftyRSA/SwiftyRSA/SwiftyRSA.swift:496:50: Operator can throw but expression is not marked with 'try'
How to resolve?
Hi,
I'm not familiar with RSA, would you explain why my code will cause 'Provided key couldn't be added to the keychain' once in a while.
func encryptStringUseRsa(str:String)->String?{
let bundle = NSBundle.mainBundle()
let pubPath = bundle.pathForResource("rsa_public_key", ofType: "pem")!
let pubString = (try! NSString(contentsOfFile: pubPath, encoding: NSUTF8StringEncoding)) as String
let encrypted = try! SwiftyRSA.encryptString(str, publicKeyPEM: pubString,padding: SecPadding.PKCS1)
return encrypted
}
The cocoa pod repository need to be updated from 0.2.0 to 0.2.1.
encryptString(str, privateKeyPEM: pemString)
decryptString(str, publicKeyPEM: pemString)
Dear all,
I have successfully generated the signature value (pkcs7 data) with swiftRSA. Now i want to embed that signature into pdf can one please tell me how to achive this in ios or share me if you have any demo code.
I am student of jagans engineering college, working on my sem project...
Thanks & Regards,
Naresh.
Currently, the APIs which this framework expose are using calls/constants/features in the Security framework which are only available on iOS/tvOS/watchOS but not macOS.
To wit, adding a macOS Target set up the same as the existing iOS one generates these initial issues:
/Users/mhughes5/Repos/SwiftyRSA/SwiftyRSA/SwiftyRSA.swift:244:26: Use of unresolved identifier 'SecKeyEncrypt'
/Users/mhughes5/Repos/SwiftyRSA/SwiftyRSA/SwiftyRSA.swift:275:26: Use of unresolved identifier 'SecKeyDecrypt'
/Users/mhughes5/Repos/SwiftyRSA/SwiftyRSA/SwiftyRSA.swift:651:22: Use of unresolved identifier 'SecKeyRawSign'
/Users/mhughes5/Repos/SwiftyRSA/SwiftyRSA/SwiftyRSA.swift:737:22: Use of unresolved identifier 'SecKeyRawVerify'
/Users/mhughes5/Repos/SwiftyRSA/SwiftyRSA/SwiftyRSA.swift:759:24: Type 'SecPadding' has no member 'PKCS1SHA224'
/Users/mhughes5/Repos/SwiftyRSA/SwiftyRSA/SwiftyRSA.swift:762:24: Type 'SecPadding' has no member 'PKCS1SHA256'
/Users/mhughes5/Repos/SwiftyRSA/SwiftyRSA/SwiftyRSA.swift:765:24: Type 'SecPadding' has no member 'PKCS1SHA384'
/Users/mhughes5/Repos/SwiftyRSA/SwiftyRSA/SwiftyRSA.swift:768:24: Type 'SecPadding' has no member 'PKCS1SHA512'
While many of these methods seem like they should be available on macOS from the documentation, they aren't. 👎
What is available, though, are a series of macOS-only APIs that do the same, even richer, operations but just using a different API set. I have a set of code I am maintaining for an internal project that does many of the same ops as SwiftyRSA but whose source code only works on macOS.
So, the crux of the issue:
So what I'd like to propose is two-fold:
Consider the following as an example of how this would be implemented, allowing for a unified front-end, but a composable backend:
@objc public protocol SwiftyRSABackendProtocol {
// …
}
#if os(OSX)
public class SecTransformBackend : NSObject, SwiftyRSABackendProtocol {}
#elseif os(iOS) || os(watchOS) || os(tvOS)
public class SecurityFrameworkBackend : NSObject, SwiftyRSABackendProtocol {}
#elseif os(Linux) || os(FreeBSD)
public class OpenSSLBackend : NSObject, SwiftyRSABackendProtocol {}
public class PolarSSLBackend : NSObject, SwiftyRSABackendProtocol {}
#endif
@objc public class SwiftyRSA : NSObject {
/// Default instance for new SwiftyRSA instances
/// TODO: This would be a swell Factory class/methods thing
private static var defaultDriverInstance : SwiftyRSABackendProtocol {
#if os(OSX)
return SecTransformBackend()
#elseif os(iOS) || os(watchOS) || os(tvOS)
return SecurityFrameworkBackend()
#elseif os(Linux) || os(FreeBSD)
// Default to something…
return OpenSSLBackend()
#endif
}
/// Concrete instance to use for our purposes
private var driverInstance : SwiftyRSABackendProtocol
/// Initializes a new object with an instance of the default driver for this platform
override init(){
driverInstance = SwiftyRSA.defaultDriverInstance
}
/// Initializes a new object with the driver instance provided by the user
@objc init(driver:SwiftyRSABackendProtocol){
driverInstance = driver
}
}
let rsa = SwiftyRSA() // Let the constructor use the `defaultDriverInstance` to initialize our `driverInstance` ivar
// -or-
let rsa2 = SwiftyRSA(driver: SecTransformBackend())
let rsa3 = SwiftyRSA(driver: PolarSSLBackend())
The purpose for the public initializer is so that as additional drivers are created by the community/project, they can be composed easily - as an example, if someone wrote a backend for, say, GnuTLS - without having to update the core SwiftyRSA
project to support it.
I strongly suggest a thorough test suite such that each class that implements SwiftyRSABackendProtocol
would have to adhere to do be "valid" to be sure that a set of inputs always deliver a set of outputs, such as:
abc
always yields exactly ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad
This will allow both driver implementors to know the outcome bar, but also allow consumers of both SwiftyRSA
and those add-on drivers to have trust that the values that come out are deterministic regardless of platform or backend.
What do you think?
I have generate a .der file with openssl, but it raise an error when I do unit test(the .pem file which generate this .der file can work well). This is the error information:
fatal error: 'try!' expression unexpectedly raised an error: Error Domain=com.takescoop.SwiftyRSA Code=500 "Invalid byte at index 18 (22) for public key header" UserInfo={NSLocalizedDescription=Invalid byte at index 18 (22) for public key header}: file /Library/Caches/com.apple.xbs/Sources/swiftlang/swiftlang-703.0.18.8/src/swift/stdlib/public/core/ErrorType.swift, line 54
I have thought I generate a wrong .der file,but it works well when I tested with another framework(https://github.com/adow/SecrecySwift) which can only use .der file and PKCS1Padding, it passed. So if I generate the .der file with incorrectly way, or there is some issues when use .der file to get public key?
PS: My English isn't well, if I describe something as ambiguous, I will be sorry.
I am interested in the new SHA2 digests and I just did a Carthage update to try it out, but I do not see the new overloads for verifySignatureString (with the optional DigestType argument).
In my Cartfile, I only have this (no version restriction):
github "TakeScoop/SwiftyRSA"
My Cartfile.resolved shows that it is still using version 0.3.0 (same as the version I already had from a week ago).
Thanks.
My project is compatible to iOS 8.0. After building the framework with Carthage and embed into my project, Xcode told me that this framework was set to work with iOS 8.3 above.
After much search, I found that downgrading the Deployment Target of the framework would fix it. Please provide the support. Thank you.
Is there a reason that the same code wouldn't support macOS / OSX?
I have a public/private key pair stored permanently in the Keychain. It is easy to retrieve these in Swift as SecKey
objects (or as String
s). How would I use these keys in SwiftyRSA (e.g. for signing)?
I am currently trying to create a PrivateKey from a base64 encoded key via base64Encoded and pemEncoded. Since I always received the Couldn't create key reference from key data
SwiftyRSAError
, I decided to check for more meaningful errors and found that no matter the key I pass in, I always get the error listed in the title.
The change to see this error is found in SwiftyRSA.addKey
within the iOS 10.0 if block.
Change
guard let key = SecKeyCreateWithData(keyData as CFData, keyDict as CFDictionary, nil)
to
var error:Unmanaged<CFError>? = nil
guard let key = SecKeyCreateWithData(keyData as CFData, keyDict as CFDictionary, &error) else {
print(error)
...
}
I have tested this with about 20 different RSA private keys as well as those found in the test key folder. I am not sure if I am going on the wrong track or not.
After upgrading my project to Swift 3.0 and Xcode 8, I also update SwiftyRSA from 0.3.0 to 0.5.0. Now when verifying my signature using the public key (SecKey) I get isSuccessful returned false and a nil error.
On closer inspection it seems that the internal verify function calls SecKeyRawVerify at some point, which returns -9809.
I'm using the following function:
public func verifySignatureString(_ str: String, signature: String, publicKey: SecKey, digestMethod: DigestType = defaultDigest) -> VerificationResult
Any idea how to resolve this?
@rsaarloos You mentioned in #47 (comment) that you were creating your keys from certificates, mind sharing the code you're using? What do your certificates contain exactly?
It's will be great to add Carthage support
You can follow this tutorial: Making Carthage-compatible Frameworks with Swift
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.