我试着按照SO上的一个例子来加密和解密一个字符串。加密和解密一个字符串
这是我到目前为止有:
public static String encrypt(String value) {
byte[] encrypted = null;
String encrypted_string = null;
try {
byte[] raw = new byte[]{'T', 'h', 'i', 's', 'I', 's', 'A', 'S', 'e', 'c', 'r', 'e', 't', 'K', 'e', 'y'};
Key skeySpec = new SecretKeySpec(raw, "AES");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
byte[] iv = new byte[cipher.getBlockSize()];
IvParameterSpec ivParams = new IvParameterSpec(iv);
cipher.init(Cipher.ENCRYPT_MODE, skeySpec,ivParams);
encrypted = cipher.doFinal(value.getBytes());
System.out.println("encrypted string:" + encrypted.length);
//Encrypted byte array
System.out.println("encrypted byte array:" + encrypted);
//Encrypted string
encrypted_string = new String(encrypted);
System.out.println("encrypted string: " + encrypted_string);
} catch (Exception ex) {
ex.printStackTrace();
}
return encrypted_string;
}
public static String decrypt(String encrypted_string) {
byte[] original = null;
Cipher cipher = null;
String decrypted_string = null;
try {
byte[] raw = new byte[]{'T', 'h', 'i', 's', 'I', 's', 'A', 'S', 'e', 'c', 'r', 'e', 't', 'K', 'e', 'y'};
Key key = new SecretKeySpec(raw, "AES");
cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
//the block size (in bytes), or 0 if the underlying algorithm is not a block cipher
byte[] ivByte = new byte[cipher.getBlockSize()];
//This class specifies an initialization vector (IV). Examples which use
//IVs are ciphers in feedback mode, e.g., DES in CBC mode and RSA ciphers with OAEP encoding operation.
IvParameterSpec ivParamsSpec = new IvParameterSpec(ivByte);
cipher.init(Cipher.DECRYPT_MODE, key, ivParamsSpec);
original= cipher.doFinal(encrypted_string.getBytes());
//Converts byte array to String
decrypted_string = new String(original);
System.out.println("Text Decrypted : " + decrypted_string);
} catch (Exception ex) {
ex.printStackTrace();
}
return decrypted_string;
}
我希望能够加密字符串,然后返回一个加密的字符串。然后采取该加密的字符串,并将其传递给我的解密方法,该方法也会返回原始解密的字符串。
我跟着一个使用Byte []数组的例子,但我不想使用Byte数组,我只想使用字符串。
的问题与上述是我在这条线得到一个错误:
original= cipher.doFinal(encrypted_string.getBytes());
它说,“错最后块长度:IllegalBlockSizeException”。这让我想我不能简单地将我的字符串转换为一个字节数组并将其传递给final()方法。但是,我能做些什么来以上面我想要的格式解决这个问题?
几乎所有的加密算法要对字节,而不是字符串的工作。接受你需要来回转换。也就是说,您可以使用'string.getBytes(StandardCharsets.UTF_8)'和'new String(bytes,StandardCharsets.UTF_8)'在字符串及其字节数组表示之间进行有效转换。 – 2014-10-16 19:27:46
如果您更喜欢将字符串作为字符串而不是字节来处理,您可能还想使用Base-64。 – rossum 2014-10-16 22:26:43