I am currently generating and saving a key pair of RSA keys inside a Java REST Server using the following block of code:
keyPairGenerator = KeyPairGenerator.getInstance("RSA");
keyPairGenerator.initialize(2048);
KeyPair keyPair = keyPairGenerator.genKeyPair();
publicKey=keyPair.getPublic();
publicKeyBase64 = Base64.encodeBase64String(publicKey.getEncoded()) ;
PrivateKey privateKey = keyPair.getPrivate();
privateKeyBase64 = Base64.encodeBase64String(privateKey.getEncoded());
Now I want to use this same private key to decrypt another information returned from the server using an iOS client. As far as I know, the iOS does not provide great native support for RSA encryption. How can I decrypt information using this private key, supposing that I currently have the key encoded as a PKCS#8 Base64 string (like inside the variable privateKeyBase64)?
Thank you!
Related
Backend uses this java implementation for encrypting the data using public key(generated from iOS App in swift),
Cipher iesCipher = Cipher.getInstance("ECIESwithAES-CBC");
byte[] derivation = Hex.decode(derivationString);
byte[] encoding = Hex.decode(encodingString);
byte[] nonce = Hex.decode(nonceString);
IESParameterSpec params = new IESParameterSpec(derivation, encoding, 128, 128, nonce, true);
iesCipher.init(Cipher.ENCRYPT_MODE, publicKey, params);
byte[] ciphertext = iesCipher.doFinal(data.getBytes());
But in swift I could not find any equivalent library to decrypt it. I am using the SwiftECC for generating the EC key-pair and sending the public key to server. Then server encrypts the data using that public key as mentioned in above implementation code. But SwiftECC has no any decrypt function which accepts the arguments like derivation, encoding, nonce. And I could not find anything similar to above java implementation in swift.
ECIES is using ephemeral static-ECDH + key derivation + encryption, where the public key of the ephemeral key pair is stored with the ciphertext. So if you find ECDH + the right key derivation + AES-CBC encryption (probably using PKCS#7 padding) then you'd be in business. Apparently BC uses KDF2 with SHA-1 for key derivation. I've asked and answered what KDF2 is here.
I’ve implemented ECIES in EllipticCurveKit, feel free to use it as inspiration. Should be straightening enough to port it to SwiftECC if you don’t want to use EllipticCurveKits EC implementation.
I've hard coded the curve to be Secp256k1 (aka "the bitcoin curve"), but you could easily make it generic, by passing in a generic Curve type, just change:
func seal<Plaintext>(
_ message: Plaintext,
whitePublicKey: PublicKey<Secp256k1>,
blackPrivateKey: PrivateKey<Secp256k1>,
nonce: SealedBox.Nonce? = nil
) -> Result<SealedBox, EncryptionError> where Plaintext: DataProtocol
into (which should work in EllipticCurveKit, and should be possible in other EC libs too):
func seal<Plaintext, Curve>(
_ message: Plaintext,
whitePublicKey: PublicKey<Curve>,
blackPrivateKey: PrivateKey<Curve>,
nonce: SealedBox.Nonce? = nil
) -> Result<SealedBox, EncryptionError> where Plaintext: DataProtocol, Curve: EllipticCurve
I want to the pin the public key of my server so that any request made to the server has to have that public key (this is to prevent proxies like Charles sniffing the data).
I had done something similar in Android with Volley.
How can I do the same with Flutter?
Create your client with a SecurityContext with no trusted roots to force the bad certificate callback, even for a good certificate.
SecurityContext(withTrustedRoots: false);
In the bad certificate callback, parse the DER encoded certificate using the asn1lib package. For example:
ASN1Parser p = ASN1Parser(der);
ASN1Sequence signedCert = p.nextObject() as ASN1Sequence;
ASN1Sequence cert = signedCert.elements[0] as ASN1Sequence;
ASN1Sequence pubKeyElement = cert.elements[6] as ASN1Sequence;
ASN1BitString pubKeyBits = pubKeyElement.elements[1] as ASN1BitString;
List<int> encodedPubKey = pubKeyBits.stringValue;
// could stop here and compare the encoded key parts, or...
// parse them into their modulus/exponent parts, and test those
// (assumes RSA public key)
ASN1Parser rsaParser = ASN1Parser(encodedPubKey);
ASN1Sequence keySeq = rsaParser.nextObject() as ASN1Sequence;
ASN1Integer modulus = keySeq.elements[0] as ASN1Integer;
ASN1Integer exponent = keySeq.elements[1] as ASN1Integer;
print(modulus.valueAsBigInteger);
print(exponent);
Key rotation reduces risk. When an attacker obtains an old server hard drive or backup file and gets an old server private key from it, they cannot impersonate the current server if the key has been rotated. Therefore always generate a new key when updating certificates. Configure the client to trust the old key and the new key. Wait for your users to update to the new version of the client. Then deploy the new key to your servers. Then you can remove the old key from the client.
Server key pinning is only needed if you're not rotating keys. That's bad security practice.
You should do certificate pinning with rotation. I have added example code in How to do SSL pinning via self generated signed certificates in flutter?
I'm struggling to generate a symmetric key in iOS using the security framework. There is a method SecKeyGenerateSymmetric() in SecKey.h but its for macOS only. The only thing I see available is SecKeyGeneratePair() which is for asymmetric encryption.
Also from reading this documentation it looks the only way to do symmetric encryption is by generating an asymmetric key pair and calling SecKeyCreateEncryptedData() with the public key and behind the scenes a symmetric key is generated but you don't have access to it. I need to have access to the symmetric key.
If anyone has experience doing symmetric encryption on iOS I would be grateful of some guidance.
With CryptoKit's introduction this can be done using the following code:
import CryptoKit
//generate Symmetric key
let key = SymmetricKey(size: .bits256)
Here is an example using AES-GCM method for encrypting and decrypting using the 32 byte symmetric key:
//generate Symmetric key
let key = SymmetricKey(size: .bits256)
//encrypt plaintext
let encryptedData = try! AES.GCM.seal("plain-text".data(using: .utf8)!, using: key)
print("Encrypted data using symmetric key:\(encryptedData)")
//decrypt data
let sealedBoxRestored = try! AES.GCM.SealedBox(nonce: encryptedData.nonce, ciphertext: encryptedData.ciphertext, tag: encryptedData.tag)
let decryptedData = try! AES.GCM.open(sealedBoxRestored, using: key)
print("Decrypted:\n\(String(data: decryptedData, encoding: .utf8)!)")
I write an iOS app to communicate with an existing server. The server generates RSA key pair(public key and private key), and sends public key to the client.
The client(the iOS app) have to encrypt with ONLY the public key, and sends the encrypted data to server.
So, I need a Objective-C function to do RSA encryption.
Input:
Plain text: hello world!
The public key:
-----BEGIN PUBLIC KEY-----
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDEChqe80lJLTTkJD3X3Lyd7Fj+
zuOhDZkjuLNPog3YR20e5JcrdqI9IFzNbACY/GQVhbnbvBqYgyql8DfPCGXpn0+X
NSxELIUw9Vh32QuhGNr3/TBpechrVeVpFPLwyaYNEk1CawgHCeQqf5uaqiaoBDOT
qeox88Lc1ld7MsfggQIDAQAB
-----END PUBLIC KEY-----
Process:
+ (NSString *)encryptString:(NSString *)str publicKey:(NSString *)pubKey;
Output:
uwGuSdCgDxAAN3M5THMrNcec3Fm/Kn+uUk7ty1s70oH0FNTAWz/7FMnEjWZYOtHe37G3D4DjqiWijyUCbRFaz43oVDUfkenj70NWm3tPZcpH8nsWYevc9a1M9GbnNF2jRlami8LLUTZiogypSVUuhcJvBZBOfea9cOonX6BG+vw=
Question:
How to implement this function?
+ (NSString *)encryptString:(NSString *)str publicKey:(NSString *)pubKey;
I have had digg for a long time, on SO and google and Apple's document. I found out Apple need a .der file to do encryption, not only the public key.
I will answer my qustion:
1. create SecKeyRef with public key string
I am helped by this post: http://blog.flirble.org/2011/01/05/rsa-public-key-openssl-ios/#its-all-in-the-format
It led to my code: https://github.com/ideawu/Objective-C-RSA/blob/master/RSA.m#L34
2. use the SecKeyRef to encrypt input data
Use Apple's SecKeyEncrypt(https://developer.apple.com/library/ios/documentation/Security/Reference/certifkeytrustservices/index.html)
3. the full code on github
https://github.com/ideawu/Objective-C-RSA
If you are using your public and private keys then use SecKeyRef
to generate both keys else use keys provided by backend guys to communicate with server.
These are some third party sdks that can help for this purpose, i've used one of them that helped me a lot to encrypt and decrypt.
[1]: https://github.com/Kitura/Swift-JWT [2]: https://github.com/TakeScoop/SwiftyRSA [3]: https://github.com/soyersoyer/SwCrypt [4]: https://github.com/Kitura/BlueRSA
For further info visit below Apple link for official documentation
https://developer.apple.com/documentation/security
AIR allows to inject code using Loader.LoadBytes()
this allows to download remote plugins as swf files which will have full access to everything that the AIR application has access to. This imposes a security risk, so it would be desirable to digitally sign the swf's.
What's the best way to do this and to verify the code signature?
I know the as3corelib has some encryption functionality and also for X.509 certificate - but I didn't find a ressource explaining how to use it. Also, maybe there's some 'official' way to codesign SWF's?
One robust method is using public key encryption, which goes something like this:
You will need an asymmetric encryption algorithm (eg, RSA), and a hash algorithm (eg, SHA, MD5).
Generate a public-private key pair.
Generate and checksum of the data using the hash algorithm.
Encrypt the checksum with the private key using the encryption algorithm. This becomes the "signature".
Send the data to the client along with the signature.
Decrypt the signature on the client with the public key to obtain the original checksum.
Generate a checksum from the data on the client.
Compare the checksums. If they match, then you know that the data came from you without alterations. If they do not match then you know the data was altered after it was sent from you, or it came from someone else.
See http://en.wikipedia.org/wiki/Public-key_cryptography
An attacker can bypass this security if they are able to intercept the connection and modify the original client SWF file and either change the public key, or remove the security mechanism entirely. Use TLS or SSL to prevent attackers intercepting the data.
An x.509 certificate is little more than a public key bundled with some meta-data. The standard also specifies a mechanism for validating the certificate, by relying on a certificate authority (CA) (see http://en.wikipedia.org/wiki/X.509).
The AS3Crypto library provides (amongst other things), an implementation of RSA, MD5, and an x.509 parser (see http://code.google.com/p/as3crypto/).
Here is some code. The signing process entails computing the hash of the data, then signing it with the private key to produce a signature, eg:
var rsa:RSAKey;
var md5:MD5;
var data:ByteArray = getSWFBytes();
var signature:ByteArray = new ByteArray();
var originalHash:ByteArray;
// read private key
rsa = PEM.readRSAPrivateKey(private_key);
// create the checksum of the original data
md5 = new MD5();
originalHash = md5.hash(original);
// encrypt the data using the private key
rsa.sign(data, signature, original.length);
The data and signature are sent to the client. The client decrypts the signature using the public key stored in the cert and compare it to the computed hash of the data, eg:
var rsa:RSAKey;
var md5:MD5;
var data:ByteArray = getSWFBytes();
var signature:ByteArray = new ByteArray();
var decryptedHash:ByteArray = new ByteArray();
var clientHash:ByteArray;
// load the certificate
var cert:X509Certificate = new X509Certificate(public_cert);
// get the public key from the cert
rsa = cert.getPublicKey();
// decrypt the signature with the public key
rsa.verify(signature, decryptedHash, encrypted.length);
// create a hash of the data
md5 = new MD5();
clientHash = md5.hash(data);
// compare the hashes
// isEqual compares the bytes in the input byte arrays, it returns true only of all bytes in both arrays match
if (isEqual(clientHash, decryptedHash))
trace("signature valid");
else
trace("signature invalid")
You can check if the certificate is signed like this:
var store:X509CertificateCollection = new MozillaRootCertificates();
var cert:X509Certificate = new X509Certificate(public_cert);
var isValid:Boolean = cert.isSigned(store, store);
You can load the raw SWF bytes like this:
var loader:URLLoader = new URLLoader();
loader.dataFormat = URLLoaderDataFormat.BINARY;
loader.addEventListener(Event.COMPLETE, completeHandler);
loader.load(new URLRequest(url_of_swf_to_load));
Example x.509 private key (usually created when you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