http://www.hanewin.net/encrypt/aes/aes-test.htm
如果您访问此网站并输入以下内容:
"Key In Hex": 00000000000000000000000000123456
"Plain Text in Hex": 00000000000000000000000000000000
然后点击“加密”按钮,你会看到十六进制的密文是:
3fa9f2a6e4c2b440fb6f676076a8ba04
是否有Java程序可以执行此操作(即是否有一个AES库,它将在上面输入“Hex In Hex”,上面的“Hex Text”,并在上面生成十六进制的密文?) ?
我很感激任何有关这样做的Java示例代码的建议或链接。
答案 0 :(得分:9)
请参阅下面的代码,了解使用JCE类执行此操作的标准方法。
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import javax.xml.bind.DatatypeConverter;
public class EncryptionExample {
public static void main(String[] args) throws Exception {
final String keyHex = "00000000000000000000000000123456";
final String plaintextHex = "00000000000000000000000000000000";
SecretKey key = new SecretKeySpec(DatatypeConverter
.parseHexBinary(keyHex), "AES");
Cipher cipher = Cipher.getInstance("AES/ECB/NoPadding");
cipher.init(Cipher.ENCRYPT_MODE, key);
byte[] result = cipher.doFinal(DatatypeConverter
.parseHexBinary(plaintextHex));
System.out.println(DatatypeConverter.printHexBinary(result));
}
}
打印:
3FA9F2A6E4C2B440FB6F676076A8BA04
答案 1 :(得分:0)
而不是将字节转换为HEX,您也可以转换为Base64。我喜欢使用Apache Commons。这是一个例子。
要编译,您需要额外的Apache Commons Codec jar,可在此处获取:
http://commons.apache.org/proper/commons-codec/download_codec.cgi
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import org.apache.commons.codec.binary.Base64;
public class Encryptor {
public static String encrypt(String key1, String key2, String value) {
try {
IvParameterSpec iv = new IvParameterSpec(key2.getBytes("UTF-8"));
SecretKeySpec skeySpec = new SecretKeySpec(key1.getBytes("UTF-8"),
"AES");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING");
cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv);
byte[] encrypted = cipher.doFinal(value.getBytes());
System.out.println("encrypted string:"
+ Base64.encodeBase64String(encrypted));
return Base64.encodeBase64String(encrypted);
} catch (Exception ex) {
ex.printStackTrace();
}
return null;
}
public static String decrypt(String key1, String key2, String encrypted) {
try {
IvParameterSpec iv = new IvParameterSpec(key2.getBytes("UTF-8"));
SecretKeySpec skeySpec = new SecretKeySpec(key1.getBytes("UTF-8"),
"AES");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING");
cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv);
byte[] original = cipher.doFinal(Base64.decodeBase64(encrypted));
return new String(original);
} catch (Exception ex) {
ex.printStackTrace();
}
return null;
}
public static void main(String[] args) {
String key1 = "Bar12345Bar12345"; // 128 bit key
String key2 = "ThisIsASecretKet";
System.out.println(decrypt(key1, key2,
encrypt(key1, key2, "Hello World")));
}
}