Class CodecCipher

  • Direct Known Subclasses:
    AESCipher

    public class CodecCipher
    extends Object
    Cipher with encoder and decoder.
     // This example shows encryption/decryption using "AES/CBC/PKCS5Padding",
     // but AESCipher is much easier to use for "AES/CBC/PKCS5Padding".
    
     // Prepare cipher initialization parameters.
     Key key
         = new SecretKeySpec("1234567890123456".getBytes("UTF-8"), "AES");
     AlgorithmParameterSpec spec
         = new IvParameterSpec("abcdefghijklmnop".getBytes("UTF-8"));
    
     // Create a cipher using "AES/CBC/PKCS5Padding".
     String transformation = StandardCipherTransformations.AES_CBC_PKCS5PADDING;
     CodecCipher cipher = new CodecCipher(transformation);
    
     // Set initialization parameters.
     cipher.setInit(key, spec);
    
     // Encryption & decryption.
     // 'plaintext' and 'decrypted' have the same value.
     String plaintext = "plain text";
     String encrypted = cipher.encrypt(plaintext);
     String decrypted = cipher.decrypt(encrypted);
    
     // In the above example, 'encrypted' is encoded by Base64 (default).
     // If you want to change the format, use setCoder method.
     // For example, to change the format to hexadecimal:
     Hex hex = new org.apache.commons.codec.binary.Hex();
     cipher.setCoder(hex);
    
     // Binary representation (only "0"s and "1"s) also can be used.
     BinaryCodec binary = new org.apache.commons.codec.BinaryCodec();
     cipher.setCoder(binary);
    
     // Coder can be specified as a parameter of some constructors.
     cipher = new CodecCipher("AES/CBC/PKCS5Padding", hex);
    
     // If you want, an encoder and a decoder can be set separately.
     cipher.setEncoder(hex);
     cipher.setDecoder(hex);
     
    Since:
    4.23
    Author:
    Takahiko Kawasaki
    See Also:
    javax.crypto.Cipher