使用Java加密字符串

时间:2018-01-05 17:11:17

标签: java encryption aes

我正在尝试使用Java和AES Cipher.getInstance(“AES / CBC / PKCS5PADDING”)加密和解密String。

当我加密数据并尝试将其打印到控制台时,我得到的字符是这样的:

0 J 9U\ 6N . ͋«D <( H( G jַ % u ^ “BT / 050 + u)的bς{的Gd /:〜اٴĴ%〜__〜 WS +] 9 {YNJ {钇Ä

这是对的吗?可以说“它是加密的”吗?我的期望是获得像“WERWERWERWER”这样的文字字符串

2 个答案:

答案 0 :(得分:4)

这是因为加密消息以字节为单位(0-255)。要获得您想要的字符串,您需要使用base 64编码输出。

基于此answer,您可以在Java 8中执行此操作,而无需使用任何库。

import java.util.Base64;

//base64 encoding
byte[] encodedBytes = Base64.getEncoder().encode("Test".getBytes("UTF-8"));
System.out.println("encodedBytes " + new String(encodedBytes));
//base64 decoding
byte[] decodedBytes = Base64.getDecoder().decode(encodedBytes);
System.out.println("decodedBytes " + new String(decodedBytes));

"Test".getBytes("UTF-8")替换为AES

的输出

答案 1 :(得分:-1)

只需使用UTF-8编码,您的值应该是正确的。

我刚刚做了一个小例子,所以我认为很清楚要明白。

请点击此处:

package com.nicolas.cli;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.security.GeneralSecurityException;
import java.security.Key;
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

public class TestCrypt {

  public static void main(String args[]) {

    TestCrypt testCrypt = new TestCrypt(keyValue);
    String encrypted = testCrypt.encrypt("someValue");
    System.out.println(encrypted);
    String decrypted = testCrypt.decrypt(encrypted);
    System.out.println(decrypted);

  }

  private static final String CRYPTO_ALGORITHM = "AES";
  private static final Logger LOGGER = LoggerFactory.getLogger(TestCrypt.class);
  private static final byte[] keyValue =
      new byte[]{'T', 'h', 'e', 'B', 'e', 's', 't', 'S', 'e', 'c', 'r', 'e', 't', 'K', 'e', 'y'};


  private final Key key;
  private final Cipher cipher = getCipherInstance();

  public TestCrypt(byte [] key) {
    this.key = new SecretKeySpec(key, CRYPTO_ALGORITHM);
  }

  private Cipher getCipherInstance() {
    try {
      return Cipher.getInstance(CRYPTO_ALGORITHM);
    } catch (GeneralSecurityException e) {
      LOGGER.error("Crypto error: Unable to get cipher instance");
      throw new RuntimeException(e);
    }
  }

  public String encrypt(String password) {
    try {
      cipher.init(Cipher.ENCRYPT_MODE, key);
      byte[] encVal = cipher.doFinal(password.getBytes());
      return new BASE64Encoder().encode(encVal);
    } catch (GeneralSecurityException e) {
      LOGGER.error("Crypto error: Unable to encrypt password");
      throw new RuntimeException(e);
    }
  }

  public String decrypt(String encryptedPassword) {
    try {
      cipher.init(Cipher.DECRYPT_MODE, key);
      byte[] decodedValue = new BASE64Decoder().decodeBuffer(encryptedPassword);
      return new String(cipher.doFinal(decodedValue), StandardCharsets.UTF_8);
    } catch (GeneralSecurityException | IOException e) {
      LOGGER.error("Crypto error: Unable to encrypt password");
      throw new RuntimeException(e);
    }
  }

}