Android uses KeyStore to encrypt data

Source: Internet
Author: User

When it comes to Android security, Android developers's official website provides many good tips and explanations covering everything from storing data, permissions, networks, processing credentials, input validation, processing user data, encryption, and more.

Key protection and network transport security should be the most critical content of mobile application security. Android offers a large number of cryptographic algorithms to protect data, such as the AES and RSA algorithms provided in the Cipher class, such as the secure random number generator SecureRandom provides keygenerator with more reliable initialization parameters to avoid offline attacks and so on.

If you need to store keys for reuse, Android provides a mechanism for long-term storage and retrieval of encryption keys, such as KeyStore, and the Android KeyStore system is ideal for storing encryption keys. "Androidkeystore" is a subset of the KeyStore, the key stored in the Androidkeystore will be signed protection, and these keys are present in the system, not in the APP's data directory, relying on the KeyChain of the hardware Storage, you can do the private key once the deposit cannot be removed, in short, each app created its own key, other applications are not accessible.

The KeyStore offers two capabilities:

With these two capabilities, our key protection becomes easy, and you only need to:

Generate a random key for the first run after the app is installed and deposit KeyStore
When you want to store a data, and then take out the random key generated from the KeyStore, encrypt your data, encrypt it, the finished encrypted data can be stored arbitrarily anywhere, such as sharepreferences, even if it is read by others, You can't decrypt your original data, because someone can't get your key.
When you need to get your original data, only need to read your encrypted data from sharepreferences, and remove the encryption key from KeyStore, use the encryption key to decrypt "encrypted data"
The encryption algorithm can use Cipher AES to ensure security, do not use the encryption algorithm created by itself.

This is a complete set of processes using KeyStore, and KeyStore can also be used for data signing and signature verification, just like a black box, which can be found on its own.

KeyStore is suitable for storing data obtained by runtime production, such as runtime, user-entered password, or token passed down by the service, but cannot be used to store the API Key/secret that we need to preset in the App, and for this kind of fixed key that needs to be preset, I will introduce a very safe and difficult to crack protection methods.

Encryption:

public string encryptstring (string Needencryptword, string alias) {if (!"". Equals(alias) &&!"". Equals(Needencryptword)) {if (Build. VERSION. SDK_int >= Build. VERSION_codes. JELLY_BEAN_MR2) {Initkeystore (alias);} String encryptstr="";byte [] Vals=null;try {KeyStore. PrivatekeyentryPrivatekeyentry = (KeyStore. Privatekeyentry) KeyStore. Getentry(Alias, NULL);Rsapublickey PublicKey = (rsapublickey) privatekeyentry. GetCertificate(). Getpublickey();if (Needencryptword. IsEmpty()) {//Toast. Maketext(This,"Enter text in the ' Initial text ' widget", Toast. LENGTH_long). Show();Return ENCRYPTSTR;}//Cipher incipher = Cipher. getinstance("Rsa/ecb/pkcs1padding","Androidopenssl");Cipher Incipher = Cipher. getinstance("Rsa/ecb/pkcs1padding");Incipher. Init(Cipher. ENCRYPT_mode, PublicKey);Incipher. Init(Cipher. ENCRYPT_mode, Privatekeyentry. GetCertificate(). Getpublickey());Bytearrayoutputstream outputstream = new Bytearrayoutputstream ();CipherOutputStream CipherOutputStream = new CipherOutputStream (OutputStream, Incipher);CipherOutputStream. Write(Needencryptword. GetBytes("UTF-8"));CipherOutputStream. Close();Vals = OutputStream. Tobytearray();} catch (Exception e) {E. Printstacktrace();} return Base64. encodetostring(Vals, Base64. DEFAULT);} return"";}

Decrypt:

public string decryptstring (string Needdecryptword, string alias) {if (!"". Equals(alias) &&!"". Equals(Needdecryptword)) {if (Build. VERSION. SDK_int >= Build. VERSION_codes. JELLY_BEAN_MR2) {Initkeystore (alias);} String decryptstr="";try {KeyStore. PrivatekeyentryPrivatekeyentry = (KeyStore. Privatekeyentry) KeyStore. Getentry(Alias, NULL);Rsaprivatekey Privatekey = (rsaprivatekey) privatekeyentry. Getprivatekey();Cipher output = Cipher. getinstance("Rsa/ecb/pkcs1padding","Androidopenssl");Cipher output = Cipher. getinstance("Rsa/ecb/pkcs1padding");Output. Init(Cipher. DECRYPT_mode, Privatekey);Output. Init(Cipher. DECRYPT_mode, Privatekeyentry. Getprivatekey());CipherInputStream CipherInputStream = new CipherInputStream (New Bytearrayinputstream (Base64. Decode(Needdecryptword, Base64. DEFAULT)), output);arraylist<byte> values = new arraylist<> ();int Nextbyte;while ((Nextbyte = CipherInputStream. Read()) != -1) {values. Add((byte) nextbyte);} byte[] bytes = new Byte[values. Size()];for (int i =0; i < bytes.length; i++) {Bytes[i] = values. Get(i). Bytevalue();} decryptstr = new String (bytes,0, bytes. Length,"UTF-8");} catch (Exception e) {E. Printstacktrace();} return Decryptstr;} return"";}

Source, I have put the encryption and sealing into the tool class, and the compatibility of Android 7.0 also processed

Android uses KeyStore to encrypt data

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.