如何在java中解密加密的String

Joe*_*Joe -2 java encryption

我有String s="abc"; 加密字符串显示:ðá£ÅÉûË¿~?‰+×µÚ 和解密相同的值.

但是现在我有相同的加密字符串ðá£ÅÉûË¿~?‰+×µÚ,我可以获得/解密它吗?下面我正在使用的代码.

String key = "Bar12345Bar12345"; // 128 bit key
// Create key and cipher
Key aesKey = new SecretKeySpec(key.getBytes(), "AES");
Cipher cipher = Cipher.getInstance("AES");
// encrypt the text
cipher.init(Cipher.ENCRYPT_MODE, aesKey);
byte[] encrypted = cipher.doFinal(text.getBytes());
String e=new String(encrypted);
byte[] encrypted1 = cipher.doFinal(e.getBytes());
System.out.println(encrypted.length+" "+encrypted1.length);
System.out.println(e);
// decrypt the text
cipher.init(Cipher.DECRYPT_MODE, aesKey);
String decrypted = new String(cipher.doFinal(encrypted));
System.out.println(decrypted);
Run Code Online (Sandbox Code Playgroud)

Ole*_*kiy 7

您不应该尝试从随机字节流创建字符串.

如果需要加密文本的字符串表示形式 - 请使用一些二进制安全编码,例如java.util.Base64.

因此,如果不修复文本的加密部分(由其他人评论),您需要做的是:

  1. 编码:

    String text = "abc";
    String key = "Bar12345Bar12345";
    Key aesKey = new SecretKeySpec(key.getBytes(), "AES");
    Cipher cipher = Cipher.getInstance("AES");
    cipher.init(Cipher.ENCRYPT_MODE, aesKey);
    byte[] encrypted = cipher.doFinal(text.getBytes());
    Base64.Encoder encoder = Base64.getEncoder();
    String encryptedString = encoder.encodeToString(encrypted);
    System.out.println(encryptedString);
    
    Run Code Online (Sandbox Code Playgroud)
  2. 要解码:

    Base64.Decoder decoder = Base64.getDecoder();
    cipher.init(Cipher.DECRYPT_MODE, aesKey);
    String decrypted = new String(cipher.doFinal(decoder.decode(encryptedString)));
    System.out.println(decrypted);
    
    Run Code Online (Sandbox Code Playgroud)