Git Product home page Git Product logo

swcrypt's Introduction

Carthage compatible

SwCrypt

Create public and private RSA keys in DER format

let (privateKey, publicKey) = try! CC.RSA.generateKeyPair(2048)

Convert them to PEM format

let privateKeyPEM = try SwKeyConvert.PrivateKey.derToPKCS1PEM(privateKey)
let publicKeyPEM = SwKeyConvert.PublicKey.derToPKCS8PEM(publicKey)

Or read them from strings with PEM data

let privateKeyDER = SwKeyConvert.PrivateKey.pemToPKCS1DER(privateKeyPEM)
let publicKeyDER = SwKeyConvert.PublicKey.pemToPKCS1DER(publicKeyPEM)

Or encrypt, decrypt the private key (OpenSSL compatible)

try SwKeyConvert.PrivateKey.encryptPEM(privateKeyPEM, passphrase: "longpassword", mode: .aes256CBC)
try SwKeyConvert.PrivateKey.decryptPEM(privEncrypted, passphrase: "longpassword")

Get public key from private keys in DER format

let publicKeyDER = try? CC.RSA.getPublicKeyFromPrivateKey(privateKeyDER!)

Encrypt, decrypt data with RSA

try CC.RSA.encrypt(data, derKey: publicKey, tag: tag, padding: .oaep, digest: .sha1)
try CC.RSA.decrypt(data, derKey: privateKey, tag: tag, padding: .oaep, digest: .sha1)

Sign, verify data with RSA

let sign = try? CC.RSA.sign(testMessage, derKey: privKey, padding: .pss, 
 digest: .sha256, saltLen: 16)
let verified = try? CC.RSA.verify(testMessage, derKey: pubKey, padding: .pss,
 digest: .sha256, saltLen: 16, signedData: sign!)

Elliptic curve functions

let keys = try? CC.EC.generateKeyPair(384)
let signed = try? CC.EC.signHash(keys!.0, hash: hash)
let verified = try? CC.EC.verifyHash(keys!.1, hash: hash, signedData: signed!)

let shared = try? CC.EC.computeSharedSecret(keys!.0, publicKey: partnerPubKey)

let privComponents = try? CC.EC.getPrivateKeyComponents(keys!.0)
let pubComponents = try? CC.EC.getPublicKeyComponents(keys!.1)

let pubKey = try? CC.EC.createFromData(keySize, x, y)
let pubKey = try? CC.EC.getPublicKeyFromPrivateKey(keys!.0)

Diffie-Hellman functions

let dh = try CC.DH.DH(dhParam: .rfc3526Group5)
let myPubKey = try dh.generateKey()
let commonKey = try dh.computeKey(partnerPubKey!)

Encrypt, decrypt data with symmetric ciphers

try CC.crypt(.encrypt, blockMode: .cbc, algorithm: .aes, padding: .pkcs7Padding, data: data, key: aesKey, iv: iv)
try CC.crypt(.decrypt, blockMode: .cfb, algorithm: .aes, padding: .pkcs7Padding, data: data, key: aesKey, iv: iv)

Encrypt, decrypt data with symmetric authenticating ciphers

try CC.cryptAuth(.encrypt, blockMode: .gcm, algorithm: .aes, data: data, aData: aData, key: aesKey, iv: iv, tagLength: tagLength)
try CC.cryptAuth(.decrypt, blockMode: .ccm, algorithm: .aes, data: data, aData: aData, key: aesKey, iv: iv, tagLength: tagLength)

Digest functions

CC.digest(data, alg: .md5)
CC.digest(data, alg: .sha256)
CC.digest(data, alg: .sha512)

HMAC function

CC.HMAC(data, alg: .sha512, key: key)

CMAC function

CC.CMAC.AESCMAC(input, key: key)

CRC function

let output = try? CC.CRC.crc(input, mode: .crc32)

KeyDerivation

CC.KeyDerivation.PBKDF2(password, salt: salt, prf: .sha256, rounds: 4096)

Symmetric Key Wrapping

try CC.KeyWrap.SymmetricKeyWrap(CC.KeyWrap.rfc3394IV, kek: kek, rawKey: rawKey)
try CC.KeyWrap.SymmetricKeyUnwrap(CC.KeyWrap.rfc3394IV, kek: kek, wrappedKey: wrappedKey)

Upsert, get, delete keys from KeyStore

try SwKeyStore.upsertKey(privateKeyPEM, keyTag: "priv", options: [kSecAttrAccessible:kSecAttrAccessibleWhenUnlockedThisDeviceOnly])
try SwKeyStore.getKey("priv")
try SwKeyStore.delKey("priv")

Check availability

SwCrypt uses dlopen and dlsym to load the CommonCrypto's functions, because not all of them are available in public header files. You have to check the availability before using them.

let digestAvailable : Bool = CC.digestAvailable()
let ramdomAvailable : Bool = CC.randomAvailable(()
let hmacAvailable : Bool = CC.hmacAvailable()
let cryptorAvailable : Bool = CC.cryptorAvailable
let keyDerivationAvailable : Bool = CC.KeyDerivation.available()
let keyWrapAvailable : Bool = CC.KeyWrap.available()
let rsaAvailable : Bool = CC.RSA.available()
let dhAvailable : Bool = CC.DH.available()
let ecAvailable : Bool = CC.EC.available()
let crcAvailable : Bool = CC.CRC.available()
let cmacAvailable : Bool = CC.CMAC.available()
let gcmAvailable : Bool = CC.GCM.available()
let ccmAvailable : Bool = CC.CCM.available()

or all in one turn:
let ccAvailable : Bool = CC.available()

Install

Just copy SwCrypt.swift to your project or use the Carthage dependency manager.

CocoaPods

CocoaPods is a dependency manager for Cocoa projects. To install SwCrypt with CocoaPods:

  1. Make sure CocoaPods is installed.

  2. Update your Podfile to include the following:

    pod 'SwCrypt'
  3. Run pod install.

Swift Package Manager

SPM is built into new versions of Xcode. To install SwCrypt with SPM:

  1. Open your project in Xcode

  2. Click "File" -> "Swift Packages" -> "Add Package Dependency..."

  3. Paste the following URL: https://github.com/soyersoyer/SwCrypt

  4. Click "Next" -> "Next" -> "Finish"

Inspired from

License

This project is copyrighted under the MIT license.

swcrypt's People

Contributors

j-mendes avatar lucieshuman avatar mattmaddux avatar nodepad avatar omargawish avatar pkarc avatar rbrignoni-j avatar soyersoyer avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

swcrypt's Issues

Incorrect documentation on sign/verify?

Hey there,

I've been using your swcrypt code in my app. Its very useful, so thank you very much. Its the only one that seems to include both pub key and symmetric algs together, without forcing me to use the keychain (like Heimdall does).

However I was signing some data and found that the signature kept failing.

Your doc says:

        let sign = try? CC.RSA.sign(testMessage, derKey: privKey, padding: .pss,  digest: .sha256, saltLen: 16)

         let verified = try? CC.RSA.verify(testMessage, derKey: pubKey, padding: .pss, digest: .sha256, saltLen: 16, signedData: sign!)

which kind of implies that you pass the message data in to the sign and verify function. But I found it fails with more than about 100 bytes. Looking at your code for sign, the first parameter is actually:

        func sign(hash: NSData, derKey: NSData...

It seems that the code is actually used to sign a hash rather than to sign raw data. Do your sample code probably should be something like this:(from my unit tests)

        let data = randomLargeData(10240)

        let hash = CC.digest(data, alg: .sha256)

        let sign = try? CC.RSA.sign(hash, derKey: privateKey, padding: .pkcs1,
                                    digest: .sha256)

        XCTAssertNotNil(sign, "Failed to sign")

        let verified = try? CC.RSA.verify(hash, derKey: publicKey, padding: .pkcs1, digest: .sha256, signedData: sign!)

        XCTAssertNotNil(verified, "Failed to calculate verification")

        XCTAssertTrue(verified!, "Failed to verify")

This raises a question... why are we passing a digest name to the signing function? Is it required? The call to CCRSACryptorSign does seem to require it, but why? Does the digest passed in to sign() need to be the same as the digest used to hash the message?

Also... note that your doc indicates "padding: .pss". That doesn't exist.
lastly the saltLen parameter is no longer used.

Again... thanks for the library.

Is this lib AppStore safe?

Upon inspection of the code I saw that quite some CommonCrypto-function are used that aren't in the official CommonCrypto-headers.

It is especially the Diffie-Hellmann stuff I am interested in.

Has somebody used these recently in AppStore released apps?

Compatible with Forge js

Hi there,

I'm preferring this lib for doing my RSA Private key encryption by calling this method:
SwKeyConvert.PrivateKey.encryptPEM(privateKeyPEM,...)
and share the result with web js which using forge js to decrypt and vice versa. But unfortunately, it always runs into an issue PKCS8.PrivateKey.hasCorrectHeader badPassphrase in swift and Only 8, 16, 24, or 32 bits supported: 200 in JS that causes decryption getting failed.
Note: The encrypted result format is the same between 2 sides:

-----BEGIN RSA PRIVATE KEY-----
Proc-Type: 4,ENCRYPTED
DEK-Info: AES-256-CBC,176B126DA24E0AF336D4C4753761DF17

3IeIljjYUL6qWWoFjGerepDPuZdN0WoMCm7smNXII2fy0xfMEXekrYvsz6KajQ7l
xxxxxxxxxxxxxx
UIdsADuuCrk2IFyDwBt3zCX4Zy12QqgbsNmaDcubo1DbwrWeKKjYka7Za85hb4Ua
-----END RSA PRIVATE KEY-----

Is there any idea to make this encryption working on both these sides?
Thanks.

Working with Server Side Swift - Vapor

I've been using the this package with great success under Vapor & Xcode producing Server Side services. Now that I am trying to move it to a docker container under linux I am getting a number of build errors that I never had before.

Has anyone got this running on swift under linux and a docker container? (Using Swift 4.2, Vapor 3.1)

how to use it

now,I have a two file (public.cer, private.p12), and private.p12 have a password.
How can I do with the Swcrypt?

Problem with CC.EC.computeSharedSecret

Hi @soyersoyer, first of all: great work, I really appreciate!
So happy to find you repo, I was wasting endless hours till I found you :)

My problem is getting the shared secret for a elliptic curve - diffie-hellman - key agreement
I have the public key from a server

let serverPublicKeyString = """
-----BEGIN PUBLIC KEY-----
MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEzgg42Iyyx+DZs4vql5tb/zmrF0zFnnfXOsBvmr+Q7MjXViCAiwgaxrNpGn3pN5f67qY3r7p+qUO6sVakjT82cg==
-----END PUBLIC KEY-----
"""

I created my own key pair in the app using:
let clientKeys = try! CC.EC.generateKeyPair(256)

I created a data object from the server public key string:
let serverKeyData = try! SwKeyConvert.PublicKey.pemToPKCS8DER(serverPublicKeyString)

But I can't figure why I don't get a shared secret through
let shared = try? CC.EC.computeSharedSecret(clientKeys.0, publicKey: serverKeyData)
Error: [generateKeyPair(_:)] SwCrypt.CC.CCError: paramError (-4300)

What I know about the server public key:

  • Created in Java ECGenParameterSpec("secp256r1")
  • Exported as base64. I added -----BEGIN PUBLIC KEY----- and -----END PUBLIC KEY----- myself in the iOS client

Am I missing a step? Looking forward to hear from you and once again: I really appreciate your great work!

Cheers
Nick

is it possible to get an objective-c version?

I have tried to use the way invoke swift code from object-c, but as RSA is an inner class, seems not easy to make it work. Does anyone has any idea?
What I really like is the function of RSA public/private key generation.

Converting the Data type from CC.HMAC to a string

Hi @soyersoyer,

The API i am working with wants a string of the hashed message.

So I am using let sign = CC.HMAC(data, alg: .sha512, key: key)
but then I need to convert sign which is of type Data, into a String.

But no matter how I do it, I can't get a string that works.

If I am using `let signString = String(describing: sign)', the string that comes to literally be the characters: "64 Bytes" (so it took the size of sign and made that the String).

When I try String(decoding: sign, as: UTF8.self) I get a string which is a row of unicodes (and not the characters they represent).

Any idea how I generate a string from the result of CC.HMAC? Is there another function I can or should be using?

Thanks

Length in DER should use minimum possible bytes

Hi ๐Ÿ‘‹

Firstly thanks for the work and the great library :)

Currently in your DER encoding you are not stripping any leading 0 value octets.

When generating a PKCS8 PEM from a 4096 bit rsa key using derToPKCS8PEM the top level sequence contains leading 0's in the value of its length.

So for example:

30 83 00 02 23 . . . . . . .

The same key using OpenSSL will produce:

30 82 02 22

If you look at the DER spec it specifies that these should be stripped during DER encoding:

10.1 Length forms
The definite form of length encoding shall be used, encoded in the minimum number of octets. [Contrast with 8.1.3.2 b).]

https://www.itu.int/ITU-T/studygroups/com17/languages/X.690-0207.pdf

AES key derivation is vulnerable to brute force attack

The getAES128Key and getAES256Key methods are prone to brute-force attacks.
Basically the key is computed as MD5(password + iv[0..7]). Given that the IV is a public info, the implementation can be reduced to MD5(password).

MD5 is a very fast hashing function and is also vulnerable to collisions. This means that an attacker can compute hashes fast and also needs to search a smaller space.

But even if the IV was not public, or if another hashing function would have been used (e.g. SHA2) the issue remains.

The key derivation should be based on a password based key derivation function such as bcrypt or PBKDF2 (with high number of iterations).

Can't encrypt long messages

Anything above 192 bytes fails to encrypt.

To replicate, try running testEncryptDecryptOAEPSHA256() in SwCryptTests.swift with longer testData, for example,

	let testData = "This is a test string and I am now making it even longer lke so long that you wo'nt eve nasdf asdjf asdkjf kasdjf kasdjf kasjdf kasjdfk ajsdkf ajskdf jaskdfj askldf jalkwej faowiejf aiw asdkfj aksdjf kasdjfk asjdkf jaskdf jkasdfj kasdjf kasdjf kasjdkf ajsdkf ajskdfj aksdjfkajfiwef wef wef we f".data(using: String.Encoding.utf8)!

How to use method crypt(_:algorithm:data:key:iv:aData:tagLength:) for GCM? Gettingg error [crypt(_:algorithm:data:key:iv:aData:tagLength:)] AppName.CC.CCError: paramError (-4300)

Hi,
I am using SwCrypt to implement GCM in my app.
Below is the list of Parameter values I pass:
opMode: .encrypt
algorithm: .aes
data: stringToEncrypt.data(using: .utf8)!
key: keyString.data(using: .utf8)!
iv: Random data of length 12 bytes
aData: Random data of length 20 bytes (I'm not sure what this parameter is for)
tagLength: 128

I get the error [crypt(_:algorithm:data:key:iv:aData:tagLength:)] AppName.CC.CCError: paramError (-4300)
I am unable to understand which parameter I am passing with wrong value

Apple Review

Is apple allowing projects that use the GCM to be approved? I see you are using the private API but accessing it with dlopen.

OAEP Padding with SHA-256 Digest

Hello, I'm trying to encrypt a string with the RSA algorithm RSA/ECB/OAEPWithSHA-256AndMGF1Padding.

The Java code to decrypt is as follows, which is done on server:

String rsaKeyAlgorithm = "RSA";
String rsaEncryptAlgorithm = "RSA/ECB/OAEPWithSHA-256AndMGF1Padding";

PrivateKey privateKey = (RSAPrivateKey) KeyFactory.getInstance(rsaKeyAlgorithm).generatePrivate(new PKCS8EncodedKeySpec(Base64.getDecoder().decode(rsaPrivateKey)));

byte[] bytes = Base64.getDecoder().decode(cipherText);

Cipher decriptCipher = Cipher.getInstance(rsaEncryptAlgorithm);
decriptCipher.init(Cipher.DECRYPT_MODE, privateKey);
return new String(decriptCipher.doFinal(bytes), charset);

I tried using the following function:
try CC.RSA.encrypt(data, derKey: publicKey, tag: tag, padding: .oaep, digest: .sha256)
But server caught the following exception:

Exception in thread "main" javax.crypto.BadPaddingException: Decryption error
	at java.base/sun.security.rsa.RSAPadding.unpadOAEP(RSAPadding.java:497)
	at java.base/sun.security.rsa.RSAPadding.unpad(RSAPadding.java:292)
	at java.base/com.sun.crypto.provider.RSACipher.doFinal(RSACipher.java:366)
	at java.base/com.sun.crypto.provider.RSACipher.engineDoFinal(RSACipher.java:392)
	at java.base/javax.crypto.Cipher.doFinal(Cipher.java:2202)

I tried to encrypt with digest .sha1, and decrypt on server using RSA algorithm RSA/ECB/OAEPWithSHA-1AndMGF1Padding and it worked fine. The issue seems to be related with SHA-256.

Can anyone help, please?

Question

How to decrypt (RSA) a message in NodeJS, encrypted under ios?

Thkx

How to use

Hello, everyone!
Can you please help me to use SwCrypt?

The task is to:

  1. Generate public and private keys
  2. Covert them to String format
  3. Encrypt some other string with a public key and receive another string as result of encryption
  4. Decrypt string received at the previous step with the private key

To be honest, I'm new in cryptography and know a little about it's principles. Are actions mentioned above possible?

I've read all the issues and still can't get how to use the library.

  1. I've generated public and private keys with.
    let (privateKey, publicKey) = try! CC.RSA.generateKeyPair(512)
    let privKeyStr = privateKey.base64EncodedString()
    let pubKeyStr = publicKey.base64EncodedString()

  2. I have a string which i want to encode and than decode
    let testString: String = "Test string"

  3. Trying to encode it:
    let testStringData = testString.data(using: .utf8)!
    let pubKeyData = pubKeyStr.data(using: .utf8)!
    let tagStr = "L" //still can't get what should I use there
    let tag = tagStr.data(using: .utf8)!
    let encryptedData = try! CC.RSA.encrypt(testStringData, derKey: pubKeyData, tag: tag, padding: .oaep, digest: .sha1)

  4. Get an error:

CCError: decodeError (-4304)

Can you please help me to use the library?
Thanks!

Can ECC encrypt and decrypt messages?

I want to use ECC to generate a key pairs and encrypt message with public key and decrypt message with private key. How can I do this? I can't find any implementation in this library.

Can SwCrypt load X.509 certificates?

Hi,

I wonder if SwCrypt has the ability to load X.509 certificates, extract public key from it and verify if a certificate was signed with a particular public key?

Thanks,

Import secp256k1 key

I'm trying this:

let privateKey = "my-own-secp256k1-key-in-hex".dataFromHexadecimalString()
let publicKey = "my-own-secp256k1-key-in-hex".dataFromHexadecimalString()

But then I get a CC.CCError.memoryFailure with:

let shared = try CC.EC.computeSharedSecret(privateKey, publicKey: publicKey)

It doesn't happen when I import keys that have been generated with:

let pair = try! CC.EC.generateKeyPair(256)
let privateKey = pair.0.hex.dataFromHexadecimalString()
let publicKey = pair.1.hex.dataFromHexadecimalString()
let shared = try CC.EC.computeSharedSecret(privateKey, publicKey: publicKey)

Instead of use CC.EC.generateKeyPair to get a keypair.

  • How can I import my own keypair? Is it supported?
  • What kind of EC keys are generated by default?

RSA decrypt failure on iOS 8.1,please help

Xcode: 9.3.1
Code:

let data = "Hello Test".data(using: .utf8)!
let (privateKey, publicKey) = try! CC.RSA.generateKeyPair(1024)
// encrypt
let encrypted = try! CC.RSA.encrypt(data, derKey: publicKey, tag: Data(), padding: .pkcs1, digest: .none)
// decrypt
do {
    let (decrypted,_) = try CC.RSA.decrypt(encrypted, derKey: privateKey, tag: Data(), padding: .pkcs1, digest: .none)
    print("decrypted:\(String(data:decrypted, encoding:.utf8)!)")
}catch{
    print("decrypt fail")
}

decypt failure on Simulator:iPhone 5s 8.1,but success on Simulator: iPhone SE 11.3.

CCCryptorStatus 
CCRSACryptorDecrypt(
    CCRSACryptorRef privateKey, 
    CCAsymetricPadding padding, 
    const void *cipherText, 
    size_t cipherTextLen,
    void *plainText, 
    size_t *plainTextLen, 
    const void *tagData, 
    size_t tagDataLen, 
    CCDigestAlgorithm digestType)
__OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_5_0);

It should be support iOS 5.0 and upper,But why decrypt failure on iOS 8.1?

Data type for CC.HMAC

Hi,

Forgive my ignorance, but CC.HMAC(data, alg: .sha512, key: key) is asking for data of type Data, but converting a dictionary to Data is not being accepted not matter how I try to format it. Usual error is Cannot convert value of type 'String' to expected argument type 'Data'.

Any idea what I need to do with my JSON/Dictionary to pass it to CC.HMAC as Data?

Thanks

Swift 4.1 compile warnings

since Apple just formally released Swift 4.1, I have found this library has some compile warnings.
SwCrypt.swift:742:18: Overlapping accesses to 'result', but modification requires exclusive access; consider copying to a local variable

Not clear that DH is not ECDH

I was confused from the brief documentation spec what is the difference between DH and Elliptic Curve code. I though these are two ways to do the same thing. It is only when I tried to get the x coordinate of the public key generated by generateKey() that I realized that this is not Elliptic Curve DH.

HKDF

Add HKDF wrapper in order to use it on the ECDH derived bits.

Is it possible use PEM key to decrypt?

Hi everyone,
the method: try CC.RSA.decrypt(data, derKey: privateKey, tag: tag, padding: .oaep, digest: .sha1) use a derKey to decrypt data. Is it possible to use a PEM key instead of the derKey?

How to use key in string format

Hi, could you help me? I have problem with using key in string format.

let publicKeyDER = try! SwKeyConvert.PublicKey.pemToPKCS1DER("MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA1UKYj/9uwlfTe4r6Cz9SaOinnfKVUbWCjA9zHcPm7QfAOZ51KeYsuBauALFyF4xJRrDCbYkzz5+AK5Bu78Nz5PAzP72l+VU/mZcV/krRfAkunW+sefh+CMjckALwzSTEI3dzlVVd+ufqsw7h+tNpoYuUk5HK0QaCx8qPzEeQq98zxNgdhXMwiEZTxSKfplEVqnZCcXwfNygP9ATT5rgLpJGlIyHEGv32kxoCqqVy2iwQ7XN1CdTIJu+X/QzFJ++ZqD0kNGmX/8HP1VA2kuW8VTsKOmXvg/fx2a3BH2SYDzEQH+QrpJFxPj/tKfCmVvufVGJakHLLuMODPtJBh2GptwIDAQAB")

I have exception Error.invalidKey. How to fix it?

CC.RSA.sign output cannot be verified openssl backed libraries

Hello, awesome work, thanks a lot!

Have found strange behaviour, I'm not a cryptographer and don't know where to dig to. A signature created with .pss padding and some salt false verified on backend with Python/Ruby but works vice verse.

iOS:

let signature = try CC.RSA.sign(dataSign, derKey: privateKey, padding: .pss, digest: .sha384, saltLen: 16)

Backend Python returns false for this signature

public_key.verify(signature, dataSign, padding.PSS(mgf=padding.MGF1(SHA384())), salt_length=16), SHA384())

The same verification tried on Ruby

public_key.verify_pss("SHA384", signature, dataSign, salt_length: 16, mgf1_hash: "SHA384")

also gives false result.

But when create signature on backend side

Python

signature = private_key.sign(dataSign, PSS(mgf=padding.MGF1(SHA384(), salt_length=16), SHA384())

Ruby

signature  = private_key.sign_pss("SHA384", dataSign, salt_length: 16, mgf1_hash: "SHA384")

Then on iOS side

try CC.RSA.verify(dataSign, derKey: publicKey, padding: .pss, digest: .sha384, saltLen: 16, signedData: signature)

It returns true.

Am I missing something ? Or CommonCrypto and OpenSSL work different for signature creation when using pss + salt ? As using padding pkcs15 all works as expected.

Thank you one more time for your great work !

podspec targets iOS 10+

any reason the podspec targets only iOS 10+ ? if I install SwCrypt manually or through carthage I can target ios 9.0 just fine and the stuff that I'm using (elliptic curve signing and key exchange) works fine

ssh-rsa format ?

It would have been really nice if there was an option to convert PEM or DER formats to ssh-rsa format.
Are there plans to include that function ?
Thanks, it is a great tool btw.

Maintainer needed

I don't have a Swift5, Xcode 10.2, OS X 10.14 compatible Mac, and I don't want to buy one only for this project.

If you want to be a SwCrypt maintainer, please apply here.

Responsibilities:

  • Review, test, accept pull requests
  • Release new versions, push them to cocoapods
  • If you want, you can write better documentation or you can add new features.

Rules:

  • My GitHub account (@soyersoyer) should continue to be one of the owners of the project, but you will have full control over its future direction.

How to compute shared secret using EC public key x and y values and private key d value

Hi

How to compute shared secret using EC public key x and y values and private key d value using the below function and i am getting back nil. I tried to decode and i can see the privateD which i am passing returns back nil from importKey method where the value of status is -4302.

Can you please help what format Data should i be passing into the computeSharedSecret for it to work in this case ?

var publicX = "2_v-MuNZccqwM7PXlakW9oHLP5XyrjMG1UVS8OxYrgA"
 var publicY = "rm1ktLmFIsP2R0YyJGXtsCbaTUesUK31Xc04tHJRolc"
 let privateD = "iyn--IbkBeNoPu8cN245L6pOQWt2lTH8V0Ds92jQmWA"
       
       let binaryPrivateData = privateDData(base64String: privateD)
       let publicKeyData = dataFromPublicXandY(x: publicX, y: publicY)
       
       let shared = try? CC.EC.computeSharedSecret(binaryPrivateData, publicKey: publicKeyData)
       print(shared) // is nil


func privateDData(base64String: String) -> Data {
       
       let base64Co = base64urlToBase64(base64url: base64String)
       //print(base64Q) // hJQWHABDBjoPHorYF5xghQ==
       let decodedDataCo = Data(base64Encoded: base64Co)
       return decodedDataCo!
   }

func dataFromPublicXandY(x: String, y:String) -> Data {
       
       var xStr = x
       var yStr = y
       
       xStr = xStr.replacingOccurrences(of: "-", with: "+").replacingOccurrences(of: "_", with: "/")
       if xStr.count % 4 == 2 {
           xStr.append("==")
       }
       if xStr.count % 4 == 3 {
           xStr.append("=")
       }
       
       yStr = yStr.replacingOccurrences(of: "-", with: "+").replacingOccurrences(of: "_", with: "/")
       if yStr.count % 4 == 2 {
           yStr.append("==")
       }
       if yStr.count % 4 == 3 {
           yStr.append("=")
       }
       
       
       let xBytes = Data(base64Encoded: xStr)
       /*Same with y and d*/
       let yBytes = Data(base64Encoded: yStr)
       
       //Now this bytes we have to append such that [0x04 , /* xBytes */, /* yBytes */, /* dBytes */]
       //Initial byte for uncompressed y as Key.
       let keyData = NSMutableData.init(bytes: [0x04], length: [0x04].count)
       keyData.append(xBytes!)
       keyData.append(yBytes!)
       return keyData as Data
   }

Private key decrypt

Hi there,

Do you know if iOS supports Public Key decryption?

My use case needs me to encrypt some data with the private key, and decrypt it with the public key. The opposite of normal operation

All the best!

Johnny

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.