我使用以下代码加密我的数据:
public static String encrypt(String clearData, String password)
throws UnsupportedEncodingException {
byte[] bytes = encrypt(clearData.getBytes("UTF-8"), password);
return Base64.encodeBytes(bytes);
}
public static byte[] encrypt(byte[] clearData, String password)
throws UnsupportedEncodingException {
byte[] passwordKey = encodeDigest(password);
try {
aesCipher = Cipher.getInstance(CIPHER_TRANSFORMATION);
} catch (NoSuchAlgorithmException e) {
Log.e(TAG, "No such algorithm " + CIPHER_ALGORITHM, e);
} catch (NoSuchPaddingException e) {
Log.e(TAG, "No such padding PKCS5", e);
}
secretKey = new SecretKeySpec(passwordKey, CIPHER_ALGORITHM);
try {
aesCipher.init(Cipher.ENCRYPT_MODE, secretKey, ivParameterSpec);
} catch (InvalidKeyException e) {
Log.e(TAG, "Invalid key", e);
return null;
} catch (InvalidAlgorithmParameterException e) {
Log.e(TAG, "Invalid algorithm " + CIPHER_ALGORITHM, e);
return null;
}
byte[] encryptedData;
try {
encryptedData = aesCipher.doFinal(clearData);
} catch (IllegalBlockSizeException e) {
Log.e(TAG, "Illegal block size", e);
return null;
} catch (BadPaddingException e) {
Log.e(TAG, "Bad padding", e);
return null;
}
return encryptedData;
}
Run Code Online (Sandbox Code Playgroud)
如何在不使用的情况下检查输入字符串数据是否已加密try-catch?
更新:
例如,用户给了我一个字符串.如果它是加密的,我将它存储在数据库中,如果不是我加密然后存储.
好吧,使用您编写的代码,您可以非常自信地通过简单地检查它是否是有效的Base64编码来获得加密字符串.
然而,从广义上讲,如果你只是通过查看就可以确定字符串是加密的,那就意味着加密非常弱.正确加密的数据从随机噪声中难以辨认.
如果用户可以向您发送任意加密或明文数据,他们需要告诉您它是什么.