Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@yakivmospan
Created December 4, 2017 16:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yakivmospan/4e0a08bcc6f15efd8e3f433ff1991cca to your computer and use it in GitHub Desktop.
Save yakivmospan/4e0a08bcc6f15efd8e3f433ff1991cca to your computer and use it in GitHub Desktop.
// 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