我正在使用这种加密方法来加密和解密某个字符串:-
package encryption;
import java.security.Key;
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
public class AES {
private static final String ALGO = "AES";
private static final byte[] keyValue =
new byte[] { 'T', 'h', 'e', 'B', 'e', 's', 't',
'S', 'e', 'c', 'r','e', 't', 'K', 'e', 'y' };
public static String encrypt(String Data) throws Exception {
Key key = generateKey();
Cipher c = Cipher.getInstance(ALGO);
c.init(Cipher.ENCRYPT_MODE, key);
byte[] encVal = c.doFinal(Data.getBytes());
String encryptedValue = new BASE64Encoder().encode(encVal);
return encryptedValue;
}
public static String decrypt(String encryptedData) throws Exception {
Key key = generateKey();
Cipher c = Cipher.getInstance(ALGO);
c.init(Cipher.DECRYPT_MODE, key);
byte[] decordedValue = new BASE64Decoder().decodeBuffer(encryptedData);
byte[] decValue = c.doFinal(decordedValue);
String decryptedValue = new String(decValue);
return decryptedValue;
}
private static Key generateKey() throws Exception {
Key key = new SecretKeySpec(keyValue, ALGO);
return key;
}
}
Run Code Online (Sandbox Code Playgroud)
效果很好。
问题是我如何知道要解密的字符串是否已加密?
我的意思是我可以将一个长的“未加密”字符串传递给解密方法,它仍然可以工作。
有什么建议。
没有明确的方法可以判断;你唯一能做的就是查看一个字符串,看看它是否看起来像是可以理解的东西(粗略地说,它file会返回比“数据”更具体的东西)。除非你有一些可以用来识别“纯文本”的特征(也许一切都是 ASCII,或者 $LANGUAGE 的所有 Unicode 代码点),否则密文和任意二进制数据之间没有固有的区别。
| 归档时间: |
|
| 查看次数: |
32165 次 |
| 最近记录: |