SoFunction
Updated on 2025-04-07

Sample code for Android using KeyStore to encrypt data

Speaking of Android security topics, the official Android Developers website has given many good suggestions and explanations, covering all aspects such as storing data, permissions, networking, processing credentials, input verification, processing user data, encryption, etc.

Key protection and network transmission security should be the most critical content of mobile application security. Android provides a large number of encryption algorithms used to protect data. For example, the Cipher class provides AES and RSA algorithms, and for example, SecureRandom, a secure random number generator, provides KeyGenerator with more reliable initialization parameters to avoid offline attacks, etc.

If you need to store keys for reuse, Android provides a mechanism such as KeyStore that can store and retrieve encryption keys for a long time. Android KeyStore systems are particularly suitable for storing encryption keys. "AndroidKeyStore" is a subset of KeyStore. The keys stored in AndroidKeyStore will be protected by signatures, and these keys exist in the system, rather than in the App's data directory. Relying on the hardware KeyChain storage, private keys cannot be retrieved once stored. In short, other applications cannot access the keys created by each App.

KeyStore provides two capabilities:

With these two capabilities, our key protection becomes easy, you just need:

When the application is first run after installation, a random key is generated and stored in the KeyStore

When you want to store a data, you can take out the previously generated random key from the KeyStore and encrypt your data. After the encryption is completed, the encrypted data can be stored anywhere, such as SharePreferences. At this time, even if it is read by others, your original data cannot be decrypted because others cannot get your key.

When you need to get your original data, you just need to read your encrypted data from SharePreferences, and remove the encryption key from KeyStore, and use the encryption key to decrypt the "encrypted data"

Among them, the encryption algorithm can be used to ensure security by using Cipher AES, and do not use the encryption algorithm you created yourself.

This is a complete process of using KeyStore. In addition, KeyStore can also be used for data signature and signature verification, just like a black box, you can search and understand the details by yourself.

KeyStore is suitable for storing data obtained during runtime production, such as passwords entered by users during runtime, or tokens passed down by the server, but it cannot be used to store API keys/secrets that we need to preset in the App. For such fixed keys that need to be preset, I will introduce a very safe and difficult to crack protection method.

encryption:

public String encryptString(String needEncryptWord, String alias) {
    if(!"".equals(alias)&&!"".equals(needEncryptWord)){
      if (.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
        initKeyStore(alias);
      }
      String encryptStr="";
      byte [] vals=null;
      try {
         privateKeyEntry = ()(alias, null);
//      RSAPublicKey publicKey = (RSAPublicKey) ().getPublicKey();
        if(()) {
//        (this, "Enter text in the 'Initial Text' widget", Toast.LENGTH_LONG).show();
          return encryptStr;
        }

//      Cipher inCipher = ("RSA/ECB/PKCS1Padding", "AndroidOpenSSL");
        Cipher inCipher = ("RSA/ECB/PKCS1Padding");
//      (Cipher.ENCRYPT_MODE, publicKey);
        (Cipher.ENCRYPT_MODE, ().getPublicKey());

        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        CipherOutputStream cipherOutputStream = new CipherOutputStream(
            outputStream, inCipher);
        (("UTF-8"));
        ();

        vals = ();
      } catch (Exception e) {
        ();
      }
      return (vals, );
    }
    return "";
  }

Decryption:

public String decryptString(String needDecryptWord, String alias) {
    if(!"".equals(alias)&&!"".equals(needDecryptWord)){
      if (.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
        initKeyStore(alias);
      }
      String decryptStr="";
      try {
         privateKeyEntry = ()(alias, null);
//      RSAPrivateKey privateKey = (RSAPrivateKey) ();

//      Cipher output = ("RSA/ECB/PKCS1Padding", "AndroidOpenSSL");
        Cipher output = ("RSA/ECB/PKCS1Padding");
//      (Cipher.DECRYPT_MODE, privateKey);
        (Cipher.DECRYPT_MODE, ());
        CipherInputStream cipherInputStream = new CipherInputStream(
            new ByteArrayInputStream((needDecryptWord, )), output);
        ArrayList<Byte> values = new ArrayList<>();
        int nextByte;
        while ((nextByte = ()) != -1) {
          ((byte)nextByte);
        }

        byte[] bytes = new byte[()];
        for(int i = 0; i < ; i++) {
          bytes[i] = (i).byteValue();
        }

        decryptStr = new String(bytes, 0, , "UTF-8");
      } catch (Exception e) {
        ();
      }
      return decryptStr;
    }
    return "";
  }

Source code download address, I have encrypted decryption into the tool class and also handled compatibility with Android 7.0

The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.