由于缺少一些信息,例如忘记转换为base64,初始化向量,字符集等信息,包括我在内的很多人在进行这项工作时都面临很多问题。因此,我想到了编写功能全面的代码。
希望这对大家有用:要进行编译,你需要其他Apache Commons Codec jar,可从以下位置获得:http : //commons.apache.org/proper/commons-prec/download_prec.cgi
import javax.crypto.Cipher;import javax.crypto.spec.IvParameterSpec;import javax.crypto.spec.SecretKeySpec;import org.apache.commons.prec.binary.base64;public class Encryptor { public static String encrypt(String key, String initVector, String value) { try { IvParameterSpec iv = new IvParameterSpec(initVector.getBytes("UTF-8")); SecretKeySpec skeySpec = new SecretKeySpec(key.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.enprebase64String(encrypted)); return base64.enprebase64String(encrypted); } catch (Exception ex) { ex.printStackTrace(); } return null; } public static String decrypt(String key, String initVector, String encrypted) { try { IvParameterSpec iv = new IvParameterSpec(initVector.getBytes("UTF-8")); SecretKeySpec skeySpec = new SecretKeySpec(key.getBytes("UTF-8"), "AES"); Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING"); cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv); byte[] original = cipher.doFinal(base64.deprebase64(encrypted)); return new String(original); } catch (Exception ex) { ex.printStackTrace(); } return null; } public static void main(String[] args) { String key = "Bar12345Bar12345"; // 128 bit key String initVector = "RandomInitVector"; // 16 bytes IV System.out.println(decrypt(key, initVector, encrypt(key, initVector, "Hello World"))); }}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)