I have a requirement to implement in Java a method which takes a encrypts a String using AES128. (I am not interested in decrypting the output.) In order to implement this I have modified the example given here. Java AES 256 encryption
Here is my current implementation.
package com.test.demo;
import java.security.InvalidKeyException;
import java.security.Key;
import java.security.NoSuchAlgorithmException;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.SecretKeySpec;
import javax.xml.bind.DatatypeConverter;
import org.apache.commons.codec.binary.Base64;
import org.apache.log4j.Logger;
public class StringEncryptor {
private static final Logger LOGGER = Logger.getLogger(StringEncryptor.class);
public static String getEncryptedString(String input){
if(input == null){
return null;
}
String keyString = "C0BAE23DF8B51807B3E17D21925FADF2";//32 byte string
byte[] keyValue = DatatypeConverter.parseHexBinary(keyString);
Key key = new SecretKeySpec(keyValue, "AES");
Cipher c1 = null;
try {
c1 = Cipher.getInstance("AES");
} catch (NoSuchAlgorithmException | NoSuchPaddingException e) {
LOGGER.error("error getting cypher", e);
return null;
}
try {
c1.init(Cipher.ENCRYPT_MODE, key);
} catch (InvalidKeyException e) {
LOGGER.error("error initalising cypher", e);
return null;
}
byte[] encVal = null;
try {
encVal = c1.doFinal(input.getBytes());
} catch (IllegalBlockSizeException | BadPaddingException e) {
LOGGER.error("error performing encryption", e);
return null;
}
String encryptedValue = Base64.encodeBase64String(encVal);
return encryptedValue;
}
}
The problem is, on examining test output, the String only contains characters [a-zA-Z+/]. I want my encrypted String to contain the full range of the first 128 ASCII characters.
I would be grateful for any suggestions. Many thanks.
答案 0 :(得分:1)
您正在使用Base64对文本进行编码,该文本仅使用64个ASCII字符。
我不知道使用前128个字符的任何流行编码,因为这意味着使用ASCII NUL字符和各种其他控制字符。如果你只使用普通的二进制字符串就可以了,你只需删除行
即可String encryptedValue = Base64.encodeBase64String(encVal);