How to Properly Use Cryptography in Mobile Application Development

foreword

First of all, let's take a look at the security risks caused by improper use or unencrypted encryption technology that have occurred in the past few years.

KRACK attack

Time: October 2017

Description: The KRACK attack exploits vulnerabilities in the Wi-Fi encryption standard WPA2, allowing attackers to steal sensitive information such as passwords and other private data on Wi-Fi networks.

Reference article link: https://www.krackattacks.com/

Vulnerability fix article link: https://www.zdnet.com/article/krack-attack-patches-heres-where-the-bugs-are-lurking/

WhatsApp Remote Code Execution Vulnerability

Time: May 2019

Description: There is a remote code execution vulnerability in WhatsApp. An attacker can execute arbitrary code on the victim's device by sending a specially crafted video file. The bug affected about 150 million users.

Reference article link: https://thehackernews.com/2019/05/hacking-whatsapp-account.html

Vulnerability fix article link: https://www.whatsapp.com/security/advisories/2019-07-15

Zoom encryption vulnerability

Time: April 2020

Description: An encryption vulnerability exists in the video conferencing application Zoom, allowing attackers to easily steal sensitive information in meetings. This vulnerability was widely exploited and caused a lot of attention and concern.

Reference article link: https://thehackernews.com/2020/04/zoom-cybersecurity-hacking.html

Vulnerability fix article link: https://blog.zoom.us/wordpress/2020/04/09/zoom-rolling-out-security-enhancements-to-address-concerns/

Cyber ​​Attacks Related to the COVID-19 Outbreak

Time: 2020

Description: COVID-19-related cyberattacks are a series of methods that use the new coronavirus epidemic to carry out cyberattacks. These attacks include phishing emails, malware, fake websites, etc., aiming to steal users' personal information, financial information, etc.

Reference article link: https://www.zdnet.com/article/coronavirus-themed-attacks-now-the-crowd-favorite-among-cybercriminals/

Freak vulnerability

Time: March 2020

Description: The Freak vulnerability is a method of exploiting vulnerabilities in encryption algorithms. The vulnerability allows attackers to break the encryption in TLS/SSL connections, thereby stealing sensitive information transmitted.

Reference article link: https://freakattack.com/

Vulnerability fix article link: https://www.us-cert.gov/ncas/alerts/TA15-086A

So how do we properly use encryption during mobile app development?

The role of passwords

Cryptography is the most effective, reliable, and economical means to ensure network and information security, and it plays an important role in information security, ensuring information confidentiality, authenticity, data integrity, and behavioral non-repudiation.

Guaranteed confidentiality of information

The confidentiality of information is one of the main attributes of network and information security, which refers to the property of ensuring that information will not be disclosed to unauthorized individuals, computers and other entities.

Information is the most valuable asset information in cyberspace. Once leaked, it may bring huge harm and influence to the country, society, industry, group, and individual.

In the real world, to ensure the confidentiality of information, such as keeping or transmitting a document secretly, it is generally possible to install protective facilities, increase guards, hide or camouflage and other means. While these methods are not convenient to operate, they require a lot of manpower and material resources, and there are many human risk factors.

In the information age, after paper documents, materials, books and other information are encoded into computer electronic files, although the ability of file processing, transmission and storage has been greatly improved, it brings new challenges to ensure the confidentiality of information. Many acts such as electronic files being copied, intercepted and disseminated are difficult to detect.

Encryption protection technology in cryptography ensures the confidentiality of information. Use computer programs that implement encryption to encrypt electronic files to generate ciphertexts with garbled shapes. With sufficiently strong encryption algorithm protection, even if attackers intercept the ciphertexts, they cannot obtain useful information from the ciphertexts. And someone who has the key can use a computer program that implements decryption to recover the original file from the garbled characters and obtain the correct information.

Access control technology in information security uses password technology to prevent illegal users from entering the database of an application system, which ensures the confidentiality of information to a certain extent. However, this technology is only equivalent to adding a "guard" at the gate of the database, while the data itself is still in plain text. Once the attacker bypasses the "guard" or the "guard" fails, the database has no confidentiality at all.

Guarantee the authenticity of the information

The authenticity of information is also one of the main attributes of network and information security, which refers to the nature of ensuring that the source of information is reliable and has not been forged or tampered with.

How to identify the legitimacy of the information? How to confirm the real identity information? These are very important tasks in the field of network and information security. They directly affect all aspects of social order, production and living order.

In real life, the identity of a person can be confirmed through physical characteristics such as appearance, voice, and posture, and the reliability of the source of information can be guaranteed through measures such as stamping, signature, and fingerprints.

In the information age, in an open network environment, identity information and news sources can be forged, and electronic information and documents can be copied, intercepted and reused.

Security authentication technology in cryptography solves problems such as the authenticity of information. Security authentication technologies include digital signatures, message authentication codes, and identity authentication protocols. Authenticity of information. Illegal users without corresponding "secret information" cannot forge "seals".

Other technologies that can guarantee authenticity, such as biometric technology, use fingerprints, irises, etc. for identity authentication, but if they are not combined with cryptography for remote authentication, they will be very insecure.

Guaranteed Data Integrity

Data integrity is another important attribute of network and information security, indicating whether data has been tampered with or destroyed without authorization.

The information age has brought about an unprecedented amount of data, information, and files. All walks of life have a large amount of publicly disseminated and stored data. The task of ensuring that data is not tampered with during transmission and storage is arduous, especially when maintaining a large number of It is even more difficult when it comes to databases and file libraries.

In real life, signatures, seals and other means can be used to ensure data integrity.

In the information age, electronic documents can use watermarking technology to protect files from tampering, but the integrity of electronic documents is not easy to detect, and it is difficult to find out after they have been modified.

For a large number of electronic file protection tasks, hashing algorithms can easily achieve data integrity, and through a mathematical process called digest, the characteristic information that uniquely identifies the file is calculated from the file. As long as a short summary like this is attached to an electronic file, the integrity of the file can be verified. To check whether a file has been modified, just use a hash algorithm to calculate a new digest, and compare this new digest with the original attached digest. If the two digests are the same, otherwise, it proves that it has been modified.

Guaranteed non-repudiation of actions

Non-repudiation is also an important attribute of network and information security.

Actions that occur in real life leave evidence or "clusters" as undeniable evidence. If one party refuses to sign the contract when signing the contract, his signature can be used as evidence of the non-repudiation of his refusal.

In the information age, how to prevent the non-repudiation of electronic contracts and electronic statements that have been verified on the network is one of the important tasks to achieve network and information security.

Digital signature technology based on public key encryption algorithm can effectively solve the non-repudiation problem of behavior. Once a user has signed a digital signature they cannot be rejected or rejected. Digital signature is an essential tool for resolving disputes on the Internet and electronic commerce. Although the logs of computers, networks and information systems can prove the user's operational behavior to a certain extent, since the logs are easy to be forged and tampered with, the non-repudiation of the behavior cannot be guaranteed.

Security risks caused by improper use of encryption algorithms

1. Insecure storage: Mobile clients may store sensitive data (such as passwords and user credentials) in clear text or in insecure formats, such as plain text files or unencrypted databases.

2. Improper use of encryption algorithms: There may be security holes in the implementation of encryption algorithms, such as using weak encryption algorithms or incorrectly configuring encryption parameters. Also, using fixed or hardcoded keys can lead to security breaches.

3. Not using HTTPS: Not using the HTTPS protocol to encrypt the communication between the mobile app and the server may expose sensitive data to attackers during transmission.

4. Certificates are not properly validated: Client applications may be subject to man-in-the-middle attacks, where attackers may trick the application over the communication link to obtain sensitive data. To fix this, the application needs to properly validate the server certificate.

5. Reverse engineering attack: The attacker may reverse engineer the application to discover the loopholes in the application and use them to attack the application.

6. Not updated software: Mobile clients may run outdated software versions that may contain known security holes and weaknesses that attackers can exploit to carry out their attacks.

7. Insecure authentication: Using insecure authentication methods, such as transmitting passwords in clear text or using simple authentication methods (such as cookie-based authentication), may allow attackers to easily steal user credentials.

8. Bad code practice: In the process of code implementation, there may be logic errors and security holes, such as buffer overflow, SQL injection, cross-site scripting, etc.

9. Failure to properly clear user data: Apps may leave sensitive data on the local device, such as user credentials or private chat records, which may lead to security risks.

10. Malware attacks: Malware may attack mobile clients through malicious code implanted in mobile applications or through malicious applications owned by attackers to obtain sensitive data or control devices.

Security Threats in Communications

Generally, the data we transmit on the network can be considered to have this potential risk. To sum it up in one sentence: "Any plaintext data transmitted in the network has a security threat."

Here are four threats we face in our communications:

First, interrupt . An attack on usability occurs when an attacker intentionally disrupts and cuts off the communications of others on the network.
-Second  , interception . It is a passive attack, in which the attacker eavesdrops on other people's communication content from the network and destroys the confidentiality of information.
Third, tampering . Attackers intentionally tamper with packets transmitted on the network, which is an attack on integrity.
Fourth, forgery . An attacker forges information transmitted over the network, which is an attack on authenticity.

file

Key hardcoded risk case

Android

public static String encrypt(String data){
    
    
	try {
    
     
		SecretKeySpec secretKeySpec = new SecretKeySpec("49u5gh249gh24985ghf429gh4ch8f23f".getBytes(),"AES"); 
		Cipher instance = Cipher.getInstance("AES"); 
		instance.init(1, secretKeySpec); 
		return Base64.encodeToString(instance.doFinal(data.getBytes())0); 
	catch(Exception e){
    
     
		return "";

iOS

import Foundation
import CommonCrypto


fileprivate let aesKey = "gEKC8gte1FvR3oJV"
fileprivate let iv = "MF00KFtxfibUyDWo"

class Crypto {
    
    
    private static let aesInstance = AESCrypto(key: aesKey, iv: iv)
    private init(){
    
    
    }
    static func encrypt(_ string: String) -> String {
    
    
            return aesInstance.encrypt(string: string).base64EncodedString()
    }

    static func decrypt(_ data: String) -> String {
    
    
        return aesInstance.decrypt(data: Data(base64Encoded:data)!)
    }
}

fileprivate class AESCrypto {
    
    
    private let key: Data
    private let iv: Data

    init(key: String,iv:String){
    
    
        guard kevcount=kccKeySizeAEs128. let kevData = kev.datalusina: .utf8) else {
    
    

            preconditionFailure("Error: Failed to set a key")

            guard iv.count = kcCBlockSizeAES128,let ivData = iv.data(using: .utf8) else {
    
    
                preconditionFailure("Error: Failed to set an initial vector")
            }
                self.key = kevData
                self.iv = ivData
            }

        func encrypt(string: String) -> Data {
    
    }



        let status = cryptData.withUnsafeMutableBytes {
    
     cryptBytes in
            data.withUnsafeBytes {
    
     dataBytes in
                iv.withunsafeBytes {
    
     ivBytes in
                    key.withunsafeBytes {
    
     keyBytes in
                        CCCrypt(option,CCAlgorithm(kCCAlgorithmAES),options,keyBytes.baseAddress, keyLength, ivBytes.baseAddress
                        }
                }
            }

Encryption-related APIs provided by the Android SDK

The API used by the Android SDK is basically similar to that provided by JAVA, and consists of the following parts:

  • Java Cryptography Architecture: JCA, java encryption architecture;
  • Java Cryptography Extension: JCE, Java Cryptography Extension Pack);
  • Java Secure Sockets Extension: JSSE, Java Secure Sockets Extension Package;
  • Java Authentication and Authentication Service: JAAS, Java Authentication and Security Service.

JCA provides basic encryption frameworks, such as certificates, digital signatures, message digests, and key pair generators, corresponding to the following packages in the Android API:

java.security
java.security.acl
java.security.cert
java.security.interfaces
java.security.spec

JCE extends JCA to provide various encryption algorithms, digest algorithms, key management and other functions, corresponding to the following packages in the Android API:

javax.crypto
javax.crypto.interfaces
javax.crypto.spec

JSSE provides the encryption function of SSL (based on Secure Sockets Layer), which is used for encrypted transmission using HTTPS. The corresponding Android API is mainly in the java.net.ssl ​​package.

JAAS provides the function of user identity authentication on the Java platform. The corresponding Android API is mainly in the following packages:

javax.security.auth
javax.security.auth.login
javax.security.auth.callback
javax.security.auth.x500

They are actually just a set of interfaces. The actual algorithms can be provided by different Providers. The default Providers of the Android API are mainly Bouncy Castle and OpenSSL. In addition, the Android API also provides android.security and android.security.keystore (new in API 23) to manage keychain and keystore.

Commonly used algorithms: Base64 encoding

The Base64 encoding algorithm is a method to represent arbitrary binary data with 64 characters (ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/). In the early days of computer network development, due to "historical reasons", emails did not support non-ASCII characters. If the email to be sent contained non-ASCII characters (such as Chinese) or pictures, the email received by the user would be A bunch of garbled characters, so the Base64 encoding algorithm was invented. As for why it is garbled? Please Google yourself. In the encryption and decryption algorithm, the original data and the encrypted data are generally binary data. In order to avoid transmission errors and facilitate saving or debugging code, it is generally necessary to base64 encode the encrypted data.

Android provides the tool class android.util.Base64 of Base64 encoding, which can be used directly without implementing the algorithm of base64 encoding. like:

byte[] output = sha.digest();
String result = Base64.encodeToString(output, Base64.DEFAULT); 

developer advice

base64 is just an encoding method, not an encryption algorithm. Do not use base64 to encrypt data.

Commonly used algorithms: random number generator

When random numbers are needed in the Android encryption algorithm, SecureRandom is used to obtain random numbers. like:

SecureRandom sr = new SecureRandom();
byte[] output = new byte[16]; 
sr.nextBytes(output); 

Be careful not to seed SecureRandom. It is not safe to call the seeded constructor or setSeed(byte[]). SecureRandom() uses dev/urandom as the seed generator by default, and this seed is unpredictable.

developer advice

  • Do not use the Random class to obtain random numbers.
  • When using SecureRandom, do not set a seed. It is risky to use any of the following functions to set the seed:
SecureRandom.SecureRandom(byte[] seed) 
SecureRandom.setSeed(long seed)
SecureRandom.setSeed(byte[] seed) 

Commonly used algorithms: Hash algorithm

The Hash algorithm refers to a string input of any length. This algorithm can give a fixed n-bit string output. The output string is generally called a Hash value.

features

  • Collision resistance: Finding two different inputs to get the same output value is computationally infeasible, and it takes a lot of time to find two input strings with the same output.
  • Irreversible: Its initial state cannot be deduced from the result.

Anti-collision makes the Hash algorithm change any point of the original input, resulting in a different Hash value, so the Hash algorithm can be used to check the integrity of the data. We often see that when some websites download a file, the website also provides the hash value of the file for us to check whether the file has been tampered with after downloading the file. The irreversible feature makes the Hash algorithm a one-way cryptographic system, which can only encrypt but not decrypt, and can be used to encrypt credentials such as user login passwords.

developer advice

1. It is recommended to use the SHA-256 and SHA-3 algorithms:
For example, use the SHA-256 algorithm to hash the message string:

byte[] input = message.getBytes();
MessageDigest sha = MessageDigest.getInstance("SHA-256");
sha.update(input);
byte[] output = sha.digest();
String result = Base64.encodeToString(output, Base64.DEFFAULT); 

2. It is not recommended to use MD2, MD4, MD5, SHA-1, and RIPEMD algorithms to encrypt sensitive information such as user passwords: There are
many ways to crack this type of algorithm, such as the md5 algorithm. There are many dictionary databases on the Internet, and md5 is given Value, you can check the data before encryption.

MessageDigest md = MessageDigest.getInstance("MD5");
byte[] md5Bytes = md.digest(str.getBytes()); 
String result = Base64.encodeToString(md5Bytes,Base64.DEFAULT); 

3. Do not use the hash function as the signature of the symmetric encryption algorithm.

4. Note: When multiple strings are concatenated and then hashed, be very careful:
such as: string S, string T, concatenated to do hash, recorded as H (S||T). But it is possible for the following to happen. For example, the hash values ​​of "builtin||securely" and "builtin||insecurely" are exactly the same. How to modify to avoid the above problems? Change to H(length(S) || S || T) or H(H(S)||H(T)) or H(H(S)||T).

In the actual development process, each parameter of the url is often sorted in the dictionary, and then the parameter name and value are concatenated and then a SECRET string is added to calculate the hash value as the signature of the URL, such as foo=1, bar= 2, baz=3 After sorting, it is bar=2, baz=3, foo=1, the hash string is: SECRETbar2baz3foo1, there is no separator between the parameter and the value, then "foo=bar" and "foob=ar The hash value of "foo=bar&fooble=baz" is the same as "foo=barfooblebaz", so carefully constructed malicious parameters may have the same hash value as normal parameters, thus deceiving the server's signature verification.

message authentication algorithm

To ensure that the encrypted message is not forged by others, a message authentication code (MAC, Message authentication code) needs to be provided. The message authentication code is a hash function with a key, based on the key and the hash function. Both parties agree in advance that the key cannot be known to a third party.

The message sender uses the MAC algorithm to calculate the MAC value of the message, appends it to the message and sends it to the receiver. After receiving the message, the receiver uses the same MAC algorithm to calculate the MAC value of the received message, and compares it with the received MAC value to see if it is the same.

developer advice

It is recommended to use the HMAC-SHA256 algorithm and avoid using CBC-MAC. An example of HMAC-SHA256 is as follows:

//初始化.KeyGenerator
KeyGenerator keyGenerator = KeyGenerator.getInstance("HmacSHA256");
//产生密钥
SecretKey secretKey = keyGenerator.generateKey();
//获取密钥
byte[] key = secretKey.getEncoded();
Log.d(Base64.encodeToString(key,Base64.DEFAULT));

//还原密钥
SecretKey restoreSecretKey = new SecretKeySpec(key,"HmacSHA256");
//实例化MAC
Mac mac = Mac.getInstance(restoreSecretKey.getAlgorithm());
//初始化MAC
mac.init(restoreSecretKey);
//执行摘要
byte[] hmacSHA256Bytes = mac.doFinal(message.getBytes()); 
result = Base64.encodeToString(hmacSHA256Bytes,Base64.DEFAULT):

Symmetric encryption algorithm

In the symmetric encryption algorithm, the data sender processes the plaintext (original data) and the encryption key together with a special encryption algorithm, turning it into complex encrypted ciphertext and sending it out. After the recipient receives the ciphertext, if he wants to interpret the original text, he needs to use the encrypted key and the inverse algorithm of the same algorithm to decrypt the ciphertext to restore it to readable plaintext. In the symmetric encryption algorithm, only one key is used, and both the sender and receiver use this key to encrypt and decrypt the data, which requires the decryption party to know the encryption key in advance.
The disadvantage of this algorithm is that once the key is leaked, the encrypted content will not be trusted.

developer advice

1. It is recommended to use the AES algorithm.
2. DES defaults to a 56-bit encryption key, which is already insecure and is not recommended.
3. Note that the encryption mode does not use ECB mode. The ECB mode is not safe, and the classic three pictures that illustrate the problem are as follows:
The plain text is:
file

After using ECB encryption mode:
file

After using CBC encryption mode:
file

4. The AES encryption algorithm API provided by Android uses the ECB mode by default, so it is necessary to explicitly specify the encryption algorithm as: CBC or CFB mode, which can be filled with PKCS5Padding. The AES key length is at least 128 bits, and 256 bits is recommended.

//生成KEY
KeyGenerator keyGenerator = KeyGenerator.getInstance("AES"); 
keyGenerator.init(256);
//产生密钥
SecretKey secretKey = keyGenerator.generateKey();
//获取密钥
byte[] keyBytes = secretKey.getEncoded();
Log.d("AES KEY", Base64.encodeToString(keyBytes,0));

//还原密钥
SecretKey key = new SecretKeySpec(keyBytes, "AES");

//加密
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); 
cipher.init(Cipher.ENCRYPT_MODE, key);
byte[] encodeResult = cipher.doFinal(plainText.getBytes());
Log.d("AESencode", Base64.encodeToString(encodeResult, Base64.DEFAULT));

asymmetric encryption

An asymmetric encryption algorithm requires two keys: a public key (publickey) and a private key (privatekey). The public key and the private key are a pair. If the data is encrypted with the public key, only the corresponding private key can be used to decrypt it; if the data is encrypted with the private key, only the corresponding public key can be used to decrypt the data. Decryption (this process can be digitally signed).
Asymmetric encryption mainly uses the RSA algorithm.

developer advice

1. Note that the key length should not be lower than 512 bits. It is recommended to use a key length of 2048 bits. Algorithms for digital signatures using RSA, such as:

//生成密钥
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA"); 
keyPairGenerator.initialize(2048);
KeyPair keyPair = keyPairGenerator.generateKeyPair();
RSAPublicKeyrsaPublicKey=(RSAPublicKey)keyPair.getPublic();
RSAPrivateKeyrsaPrivateKey =(RSAPrivateKey)keyPair.getPrivate()

//签名
PKCS8EncodedKeySpec pkcs8EncodedKeySpec = newPKCS8EncodedKeySpec(rsaPrivateKey.getEncoded()) 
KeyFactory keyFactory = KeyFactory getInstance("RSA");
PrivateKey privateKey = keyFactory.generatePrivate(pkcs8EncodedKeySpec); 
signature signature = Signature.getInstance("SHA256withRSA"); 
signature.initSign(privateKey);
signature.update(src.getBytes());
byte[] result = signature.sign();

2. Use the RSA algorithm for encryption. The RSA encryption algorithm should use Cipher.getInstance(RSA/ECB/OAEPWithSHA256AndMGF1Padding), otherwise there will be a risk of replay attacks. like:

KeyPairGenerator keyPairGenerator =
KeyPairGenerator.getInstance("RSA");
keyPairGenerator.initialize(2048);
KeyPair keyPair = keyPairGenerator.generateKeyPair();
RSAPublicKeyrsaPublicKey=(RSAPublicKey)keyPair.getPublic();
RSAPrivateKey rsaPrivateKey=(RSAPrivateKey)keyPair.getPrivate();

//公钥加密
X509EncodedKeySpec x509EncodedKeySpec = newX509EncodedKeySpec(rsaPublicKey.getEncoded()): 
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
PublicKey publicKey = keyFactory.generatePublic(x509EncodedKeySpec);
Cipher cipher = Cipher.getInstance("RSA/ECB/OAEPWithSHA256AndMGF1Padding"); 
cipher.init(Cipher.ENCRYPT_MODE,publicKey); 
byte[] result =cipher.doFinal(src.getBytes());

...
//私钥解密
PKCS8EncodedKeySpec pkcs8EncodedKeySpec = newPKCS8EncodedKeySpec(rsaPrivateKey.getEncoded());
KeyFactory keyFactory2 = KeyFactory.getInstance("RSA");
PrivateKey privateKey = keyFactory2.generatePrivate(pkcs8EncodedKeySpec); 
Cipher cipher = Cipher.getInstance("RSA/ECB/OAEPWithSHA256AndMGF1Padding"); 
cipher.init(Cipher.DECRYPT_MODE,privateKey);
byte[] result2 = cipher.doFinal(result); 

Encryption Algorithm PBE

PBE is a password-based encryption algorithm, which is characterized in that the password is used instead of the key, and the password is controlled by the user himself, and random number hashing and multiple encryption are used to ensure data security.

Developer suggestion:
When using the password-based encryption algorithm PBE, add salt when generating the key. The value of the salt should preferably come from SecureRandom, and specify the number of iterations. like:

//初始化盐
mSalt = new byte[SALT_LENGTH_BYTES]; 
SecureRandom sr = new SecureRandom(); 
sr.nextBytes(mSalt);

SecretKeyFactory secretKeyFactory = SecretKeyFactory.getInstance(KEY_GENERATOR_MODE);
keySpec = new PBEKeySpec(password, salt, KEY_GEN_ITERATION_COUNT, KEY_LENGTH_BITS); 
secretKey = secretKeyFactory.generateSecret(keySpec); 

Summarize

several principles

1. Do not design encryption algorithms and protocols by yourself, use industry-standard algorithms.
2. Do not use the ECB mode for the symmetric encryption algorithm, and it is not recommended to use the DES algorithm.
3. Choose a key of appropriate length.
4. Make sure that the seed of the random number generator has enough information entropy.
5. Do not use an encryption algorithm without message authentication to encrypt messages, which cannot prevent replay.
6. Be very careful when doing hash after concatenating multiple strings.
7. When adding salt to the algorithm, don't be too short and don't repeat.
8. When using the IV of the initialization vector, CBC, CFB, GCM, etc. with constant IV can be replayed like ECB, that is, it is not safe to use the last piece of ciphertext of the previous message as the IV of the next message.
9. The key should follow the principles:

  • (1) The key cannot be constant, but should be random and replaced regularly. If the key used to encrypt data is constant, the same plaintext encryption will result in the same ciphertext, and it is difficult to prevent dictionary attacks.
  • (2) Developers should guard against hard-coded keys.

Key storage security from high to low

  • Keys are stored in the hardware-backed Android KeyStore
  • All keys are stored on the server and available after strong authentication
  • The master key is stored on the server and is used to encrypt other keys stored in Android SharedPreferences
  • Keys are stored in a software implementation of the Android KeyStore
  • The master key is stored in the software implementation of the Android keystore and is used to encrypt other keys stored in SharedPreferences
  • All keys are stored in SharedPreferences (not recommended)
  • Hardcode encryption keys in source code (not recommended)
  • Predictable obfuscation function or key generation function based on stable properties (not recommended)
  • Store generated keys on external storage (like /sdcard/) (not recommended)

Reference article:

https://blog.oversecured.com/Use-cryptography-in-mobile-apps-the-right-way/

http://www.52im.net/thread-216-1-1.html

Recommended reading:
Risks of face recognition in mobile applications and the industry chain analysis of a pornographic APP
detected by a certain reinforced Frida

Guess you like

Origin blog.csdn.net/u010671061/article/details/132524550