Created
December 4, 2017 16:09
-
-
Save yakivmospan/4e0a08bcc6f15efd8e3f433ff1991cca to your computer and use it in GitHub Desktop.
This file contains hidden or 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
// Creates Cipher with asymmetric transformation and provides wrap and unwrap functions | |
val cipherForWrapping = CipherWrapper("RSA/ECB/PKCS1Padding") | |
// Creates Cipher with symmetric transformation and provides encrypt and decrypt functions | |
val cipherForEncryption = CipherWrapper("AES/CBC/PKCS7Padding") | |
// ---------------- Create Keys | |
// Create AES BC provider key | |
val symmetricKey = keyStoreWrapper.generateDefaultSymmetricKey() | |
// Create RSA AndroidKeyStore Provider key and save it into keystore | |
val masterKey = keyStoreWrapper.createAndroidKeyStoreAsymmetricKey(MASTER_KEY) | |
// Wrap AES Secret key with RSA Public key | |
val encryptedSymmetricKey = cipherForWrapping.wrapKey(symmetricKey, masterKey.public) | |
// And save it to Shared Preferences | |
storage.saveEncryptionKey(encryptedSymmetricKey) | |
//----------------- Encrypt / Decrypt with keys | |
// Get RSA master key from Android Key Store | |
masterKey = keyStoreWrapper.getAndroidKeyStoreAsymmetricKeyPair("MASTER_KEY") | |
// Get AES wrapped raw data from preferences | |
val encryptionKey = storage.getEncryptionKey() | |
// Unwrap AES key data with RSA Private key | |
symmetricKey = cipherForWrapping.unWrapKey(encryptionKey, ALGORITHM_AES, Cipher.SECRET_KEY, masterKey?.private) as SecretKey | |
// Encrypt message with AES Secret key | |
val encryptedMessage = cipherForEncryption.encrypt(message, symmetricKey) | |
// Encrypt message with AES Secret key | |
val decryptedMessage = cipherForEncryption.decrypt(encryptedMessage, symmetricKey) | |
// Ooops, InvalidKeyException: no IV set when one expected |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment