编写一段代码,实现移动应用中对用户敏感数据的加密存储和解密访问功能。
在移动应用中,对用户敏感数据进行加密存储和解密访问是保护用户信息安全的重要措施。下面我将提供一个基于Java语言的示例,演示如何使用Android平台的加密库来实现这一点。这里我们将使用Cipher类来进行加解密操作,使用SecretKeySpec来指定加密算法的密钥,使用Base64来处理加密后的字节数组,以便于存储和显示。
首先是加密敏感数据的方法:
import android.util.Base64;
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.security.Key;
public class DataSecurity {
private static final String ALGORITHM = "AES";
private static final byte[] keyValue =
new byte[] { 'T', 'h', 'i', 's', 'I', 's', 'A', 'S', 'e', 'c', 'r', 'e', 't', 'K', 'e', 'y' };
public static String encrypt(String valueToEnc) throws Exception {
Key key = generateKey();
Cipher c = Cipher.getInstance(ALGORITHM);
c.init(Cipher.ENCRYPT_MODE, key);
byte[] encValue = c.doFinal(valueToEnc.getBytes());
String encryptedValue = Base64.encodeToString(encValue, Base64.DEFAULT);
return encryptedValue;
}
private static Key generateKey() throws Exception {
Key key = new SecretKeySpec(keyValue, ALGORITHM);
return key;
}
}
然后是解密敏感数据的方法:
public static String decrypt(String encryptedValue) throws Exception {
Key key = generateKey();
Cipher c = Cipher.getInstance(ALGORITHM);
c.init(Cipher.DECRYPT_MODE, key);
byte[] decordedValue = Base64.decode(encryptedValue, Base64.DEFAULT);
byte[] decValue = c.doFinal(decordedValue);
String decryptedValue = new String(decValue);
return decryptedValue;
}
使用这两个方法,你可以在保存用户数据之前调用encrypt方法对数据进行加密,然后将加密后的字符串保存到本地的SQLite数据库或SharedPreferences中。当需要读取并使用这些数据时,可以先从存储中读取加密的数据,然后调用decrypt方法进行解密。
例如,在保存用户的银行卡号时,可以这样做:
String cardNumber = "4012888888881881";
String encryptedCardNumber = DataSecurity.encrypt(cardNumber);
// 将encryptedCardNumber保存到数据库或SharedPreferences
在需要使用该银行卡号时,可以这样做:
String retrievedEncryptedCardNumber = /* 从数据库或SharedPreferences中获取 */;
String decryptedCardNumber = DataSecurity.decrypt(retrievedEncNumber);
// 使用decryptedCardNumber
注意,在实际应用中,密钥管理是非常重要的。这里使用了固定的密钥,但在真正的生产环境中,建议使用更安全的方式来管理密钥,比如使用Android Keystore System。