public static byte[] encrypt() throws Exception { String seed = "SuperSecretPassword"; String plaintext = "This is insecure data!"; //API for generating symmetric cryptographic keys KeyGenerator keygen = KeyGenerator.getInstance("AES"); //Returns a new instance of SecureRandom that utilizes the //SHA1 algorithm. SecureRandom secrand = SecureRandom.getInstance("SHA1PRNG"); //Reseeds this SecureRandom instance with the specified seed. secrand.setSeed(seed.getBytes()); //Initializes this KeyGenerator instance for the specified //key size (in bits) using the specified randomness source. keygen.init(128, secrand); //Generates a secret key. SecretKey seckey = keygen.generateKey(); //Returns the encoded form of the key. byte[] rawKey = seckey.getEncoded(); //Create a new SecretKeySpec for the key data and AES algorithm. SecretKeySpec skeySpec = new SecretKeySpec(rawKey, "AES"); //Creates a new Cipher for the specified transformation. //The installed providers are searched in order for an //implementation of the specified transformation. //The first found provider providing the transformation //is used to create the cipher. Cipher cipher = Cipher.getInstance("AES"); //Initializes this cipher instance with the specified key. //The cipher is initialized for the specified operational //mode (one of: encryption, decryption, key wrapping or key unwrapping) //depending on opmode. //If this cipher instance needs any algorithm parameters //or random values that the specified key cannot provide, //the underlying implementation of this cipher is supposed //to generate the required parameters (using its provider or random values). cipher.init(Cipher.ENCRYPT_MODE, skeySpec); //Finishes a multi-part transformation (encryption or decryption). //Processes the bytes in input buffer, and any bytes that //have been buffered in previous update calls. byte[] encrypted = cipher.doFinal(plaintext.getBytes()); return encrypted; }
解密只需要该这一句
cipher.init(Cipher.DECRYPT_MODE, skeySpec);