我是Android中文本文件加密的新手。并尝试了这么多的文本加密的例子,但我很困惑如何应用。我有来自json响应的5条字符串记录,我希望将它们保存在文本文件(外部存储中)和“加密格式”中。我尝试过cipher_text_encoding的代码,但实际上与其中的许多类混淆了。请建议我或者是好的文本加密教程,或者给我提示如何编码。提前谢谢。
发布于 2017-10-12 08:21:58
基于AES密钥算法的加解密算法
生成AES密钥:
public static byte[] generateAesSecretKey(){
String SALT2 = "strong_salt_value";
String username = "user_name";
String password = "strong_password";
byte[] key = (SALT2 + username + password).getBytes();
SecretKey secretKeySpec = null;
try {
MessageDigest sha = MessageDigest.getInstance("SHA-1");
key = sha.digest(key);
key = Arrays.copyOf(key, 16);
secretKeySpec = new SecretKeySpec(key, "AES");
} catch (Exception e) {
e.printStackTrace();
}
return secretKeySpec.getEncoded();
}加密:
public static byte[] encodeFile(byte[] secretKey, byte[] fileData) {
SecretKeySpec skeySpec = new SecretKeySpec(secretKey, "AES");
byte[] encrypted = null;
try {
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
encrypted = cipher.doFinal(fileData);
// Now write your logic to save encrypted data to sdcard here
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (NoSuchPaddingException e) {
e.printStackTrace();
} catch (InvalidKeyException e) {
e.printStackTrace();
} catch (IllegalBlockSizeException e) {
e.printStackTrace();
} catch (BadPaddingException e) {
e.printStackTrace();
} catch (Exception e){
e.printStackTrace();
}
return encrypted;
}解密:
public static byte[] decodeFile(byte[] key, byte[] fileData) {
SecretKeySpec skeySpec = new SecretKeySpec(key, "AES");
byte[] decrypted = null;
try {
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.DECRYPT_MODE, skeySpec);
decrypted = cipher.doFinal(fileData);
} catch (NoSuchAlgorithmException | NoSuchPaddingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvalidKeyException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalBlockSizeException | BadPaddingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch(Exception e){
// for all other exception
e.printStackTrace();
}
return decrypted;
}希望以上方法对您有帮助!
发布于 2017-10-12 08:44:38
对于每一个初学者来说,困惑是很正常的,而不是自己去做,而是学会利用代码重用或编写的共享库。这将利用代码抽象,因为您只对JSON/Sting的加密和解密感兴趣。
关于完整的文件:
对于可重用(Java/Android)库:
简单用法:
String plainText = "Your String";
String encryptionKey = "Your Encryption Key";
String IV = "Your Initial Vector";
// To Encrypt
String cipherText = AES.encrypt(plainText, encryptionKey, IV);
// To Decrypt returned value same as plainText
String originalText = AES.decrypt(cipherText, encryptionKey, IV);干杯。
https://stackoverflow.com/questions/46704304
复制相似问题