Example usage for javax.crypto.spec IvParameterSpec IvParameterSpec

List of usage examples for javax.crypto.spec IvParameterSpec IvParameterSpec

Introduction

In this page you can find the example usage for javax.crypto.spec IvParameterSpec IvParameterSpec.

Prototype

public IvParameterSpec(byte[] iv) 

Source Link

Document

Creates an IvParameterSpec object using the bytes in iv as the IV.

Usage

From source file:MainClass.java

public static void main(String args[]) throws Exception {
    Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());

    SecretKey key = KeyGenerator.getInstance("DES").generateKey();

    // for CBC; must be 8 bytes
    byte[] initVector = new byte[] { 0x10, 0x10, 0x01, 0x04, 0x01, 0x01, 0x01, 0x02 };

    AlgorithmParameterSpec algParamSpec = new IvParameterSpec(initVector);
    Cipher m_encrypter = Cipher.getInstance("DES/CBC/PKCS5Padding");
    Cipher m_decrypter = Cipher.getInstance("DES/CBC/PKCS5Padding");

    m_encrypter.init(Cipher.ENCRYPT_MODE, key, algParamSpec);
    m_decrypter.init(Cipher.DECRYPT_MODE, key, algParamSpec);

    FileInputStream fis = new FileInputStream("cipherTest.in");
    FileOutputStream fos = new FileOutputStream("cipherTest.out");
    int dataInputSize = fis.available();

    byte[] inputBytes = new byte[dataInputSize];
    fis.read(inputBytes);//from  w ww.  jav  a2s.co m
    write(inputBytes, fos);
    fos.flush();
    fis.close();
    fos.close();

    String inputFileAsString = new String(inputBytes);
    System.out.println("INPUT FILE CONTENTS\n" + inputFileAsString + "\n");

    System.out.println("File encrypted and saved to disk\n");

    fis = new FileInputStream("cipherTest.out");

    byte[] decrypted = new byte[dataInputSize];
    read(decrypted, fis);

    fis.close();
    String decryptedAsString = new String(decrypted);

    System.out.println("DECRYPTED FILE:\n" + decryptedAsString + "\n");

}

From source file:MainClass.java

public static void main(String[] args) throws Exception {
    Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
    byte[] input = "www.java2s.com".getBytes();
    byte[] keyBytes = new byte[] { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c,
            0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17 };
    byte[] ivBytes = new byte[] { 0x00, 0x01, 0x02, 0x03, 0x00, 0x01, 0x02, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00,
            0x00, 0x00, 0x01 };/*www  .  ja va  2s.c  o m*/

    SecretKeySpec key = new SecretKeySpec(keyBytes, "AES");
    IvParameterSpec ivSpec = new IvParameterSpec(ivBytes);
    Cipher cipher = Cipher.getInstance("AES/CTR/NoPadding", "BC");
    System.out.println("input : " + new String(input));

    // encryption pass
    cipher.init(Cipher.ENCRYPT_MODE, key, ivSpec);
    ByteArrayInputStream bIn = new ByteArrayInputStream(input);
    CipherInputStream cIn = new CipherInputStream(bIn, cipher);
    ByteArrayOutputStream bOut = new ByteArrayOutputStream();

    int ch;
    while ((ch = cIn.read()) >= 0) {
        bOut.write(ch);
    }

    byte[] cipherText = bOut.toByteArray();

    System.out.println("cipher: " + new String(cipherText));

    // decryption pass
    cipher.init(Cipher.DECRYPT_MODE, key, ivSpec);
    bOut = new ByteArrayOutputStream();
    CipherOutputStream cOut = new CipherOutputStream(bOut, cipher);
    cOut.write(cipherText);
    cOut.close();
    System.out.println("plain : " + new String(bOut.toByteArray()));
}

From source file:MainClass.java

public static void main(String[] args) throws Exception {
    Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
    byte[] input = "www.java2s.com".getBytes();
    byte[] keyBytes = new byte[] { 0x73, 0x2f, 0x2d, 0x33, (byte) 0xc8, 0x01, 0x73, 0x2b, 0x72, 0x06, 0x75,
            0x6c, (byte) 0xbd, 0x44, (byte) 0xf9, (byte) 0xc1, (byte) 0xc1, 0x03, (byte) 0xdd, (byte) 0xd9,
            0x7c, 0x7c, (byte) 0xbe, (byte) 0x8e };
    byte[] ivBytes = new byte[] { (byte) 0xb0, 0x7b, (byte) 0xf5, 0x22, (byte) 0xc8, (byte) 0xd6, 0x08,
            (byte) 0xb8 };

    // encrypt the data using precalculated keys

    Cipher cEnc = Cipher.getInstance("DESede/CBC/PKCS7Padding", "BC");
    cEnc.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(keyBytes, "DESede"), new IvParameterSpec(ivBytes));

    byte[] out = cEnc.doFinal(input);
    // decrypt the data using PBE

    char[] password = "password".toCharArray();
    byte[] salt = new byte[] { 0x7d, 0x60, 0x43, 0x5f, 0x02, (byte) 0xe9, (byte) 0xe0, (byte) 0xae };
    int iterationCount = 2048;
    PBEKeySpec pbeSpec = new PBEKeySpec(password, salt, iterationCount);
    SecretKeyFactory keyFact = SecretKeyFactory.getInstance("PBEWithSHAAnd3KeyTripleDES");

    Cipher cDec = Cipher.getInstance("PBEWithSHAAnd3KeyTripleDES");
    Key sKey = keyFact.generateSecret(pbeSpec);

    cDec.init(Cipher.DECRYPT_MODE, sKey);

    System.out.println("cipher : " + new String(out));
    System.out.println("gen key: " + new String(sKey.getEncoded()));
    System.out.println("gen iv : " + new String(cDec.getIV()));
    System.out.println("plain  : " + new String(cDec.doFinal(out)));
}

From source file:MainClass.java

public static void main(String[] args) throws Exception {
    Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
    byte[] input = "www.java2s.com".getBytes();

    byte[] ivBytes = new byte[] { 0x00, 0x00, 0x00, 0x01, 0x04, 0x05, 0x06, 0x07, 0x00, 0x00, 0x00, 0x00, 0x00,
            0x00, 0x00, 0x01 };//from   www.j  a va  2s. c  om

    Cipher cipher = Cipher.getInstance("AES/CTR/NoPadding", "BC");
    KeyGenerator generator = KeyGenerator.getInstance("AES", "BC");

    generator.init(192);

    Key encryptionKey = generator.generateKey();

    System.out.println("key   : " + Utils.toHex(encryptionKey.getEncoded()));
    System.out.println("input : " + new String(input));

    // encryption pass
    cipher.init(Cipher.ENCRYPT_MODE, encryptionKey, new IvParameterSpec(ivBytes));
    byte[] cipherText = new byte[cipher.getOutputSize(input.length)];
    int ctLength = cipher.update(input, 0, input.length, cipherText, 0);
    ctLength += cipher.doFinal(cipherText, ctLength);

    // decryption pass
    Key decryptionKey = new SecretKeySpec(encryptionKey.getEncoded(), encryptionKey.getAlgorithm());
    cipher.init(Cipher.DECRYPT_MODE, decryptionKey, new IvParameterSpec(ivBytes));
    byte[] plainText = new byte[cipher.getOutputSize(ctLength)];
    int ptLength = cipher.update(cipherText, 0, ctLength, plainText, 0);
    ptLength += cipher.doFinal(plainText, ptLength);
    System.out.println("plain : " + new String(plainText) + " bytes: " + ptLength);
}

From source file:MainClass.java

public static void main(String[] args) throws Exception {
    Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
    byte[] input = "www.java2s.com".getBytes();
    byte[] keyBytes = new byte[] { 0x73, 0x2f, 0x2d, 0x33, (byte) 0xc8, 0x01, 0x73, 0x2b, 0x72, 0x06, 0x75,
            0x6c, (byte) 0xbd, 0x44, (byte) 0xf9, (byte) 0xc1, (byte) 0xc1, 0x03, (byte) 0xdd, (byte) 0xd9,
            0x7c, 0x7c, (byte) 0xbe, (byte) 0x8e };
    byte[] ivBytes = new byte[] { (byte) 0xb0, 0x7b, (byte) 0xf5, 0x22, (byte) 0xc8, (byte) 0xd6, 0x08,
            (byte) 0xb8 };

    // encrypt the data using precalculated keys

    Cipher cEnc = Cipher.getInstance("DESede/CBC/PKCS7Padding", "BC");

    cEnc.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(keyBytes, "DESede"), new IvParameterSpec(ivBytes));

    byte[] out = cEnc.doFinal(input);

    // decrypt the data using PBE

    char[] password = "password".toCharArray();
    byte[] salt = new byte[] { 0x7d, 0x60, 0x43, 0x5f, 0x02, (byte) 0xe9, (byte) 0xe0, (byte) 0xae };
    int iterationCount = 2048;
    PBEKeySpec pbeSpec = new PBEKeySpec(password);
    SecretKeyFactory keyFact = SecretKeyFactory.getInstance("PBEWithSHAAnd3KeyTripleDES", "BC");

    Cipher cDec = Cipher.getInstance("PBEWithSHAAnd3KeyTripleDES", "BC");
    Key sKey = keyFact.generateSecret(pbeSpec);

    cDec.init(Cipher.DECRYPT_MODE, sKey, new PBEParameterSpec(salt, iterationCount));

    System.out.println("cipher : " + new String(out));
    System.out.println("gen key: " + new String(sKey.getEncoded()));
    System.out.println("gen iv : " + new String(cDec.getIV()));
    System.out.println("plain  : " + new String(cDec.doFinal(out)));
}

From source file:org.apache.commons.crypto.examples.CipherByteBufferExample.java

public static void main(String[] args) throws Exception {
    final SecretKeySpec key = new SecretKeySpec(getUTF8Bytes("1234567890123456"), "AES");
    final IvParameterSpec iv = new IvParameterSpec(getUTF8Bytes("1234567890123456"));
    Properties properties = new Properties();
    //Creates a CryptoCipher instance with the transformation and properties.
    final String transform = "AES/CBC/PKCS5Padding";
    final ByteBuffer outBuffer;
    final int bufferSize = 1024;
    final int updateBytes;
    final int finalBytes;
    try (CryptoCipher encipher = Utils.getCipherInstance(transform, properties)) {

        ByteBuffer inBuffer = ByteBuffer.allocateDirect(bufferSize);
        outBuffer = ByteBuffer.allocateDirect(bufferSize);
        inBuffer.put(getUTF8Bytes("hello world!"));

        inBuffer.flip(); // ready for the cipher to read it
        // Show the data is there
        System.out.println("inBuffer=" + asString(inBuffer));

        // Initializes the cipher with ENCRYPT_MODE,key and iv.
        encipher.init(Cipher.ENCRYPT_MODE, key, iv);
        // Continues a multiple-part encryption/decryption operation for byte buffer.
        updateBytes = encipher.update(inBuffer, outBuffer);
        System.out.println(updateBytes);

        // We should call do final at the end of encryption/decryption.
        finalBytes = encipher.doFinal(inBuffer, outBuffer);
        System.out.println(finalBytes);
    }/*from  w  w w.j  av  a2s  .c o m*/

    outBuffer.flip(); // ready for use as decrypt
    byte[] encoded = new byte[updateBytes + finalBytes];
    outBuffer.duplicate().get(encoded);
    System.out.println(Arrays.toString(encoded));

    // Now reverse the process
    try (CryptoCipher decipher = Utils.getCipherInstance(transform, properties)) {
        decipher.init(Cipher.DECRYPT_MODE, key, iv);
        ByteBuffer decoded = ByteBuffer.allocateDirect(bufferSize);
        decipher.update(outBuffer, decoded);
        decipher.doFinal(outBuffer, decoded);
        decoded.flip(); // ready for use
        System.out.println("decoded=" + asString(decoded));
    }
}

From source file:org.apache.commons.crypto.examples.StreamExample.java

public static void main(String[] args) throws IOException {
    final SecretKeySpec key = new SecretKeySpec(getUTF8Bytes("1234567890123456"), "AES");
    final IvParameterSpec iv = new IvParameterSpec(getUTF8Bytes("1234567890123456"));
    Properties properties = new Properties();
    final String transform = "AES/CBC/PKCS5Padding";

    String input = "hello world!";
    //Encryption with CryptoOutputStream.

    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();

    try (CryptoOutputStream cos = new CryptoOutputStream(transform, properties, outputStream, key, iv)) {
        cos.write(getUTF8Bytes(input));/*from w w w  . j  av a  2  s  . c o m*/
        cos.flush();
    }

    // The encrypted data:
    System.out.println("Encrypted: " + Arrays.toString(outputStream.toByteArray()));

    // Decryption with CryptoInputStream.
    InputStream inputStream = new ByteArrayInputStream(outputStream.toByteArray());

    try (CryptoInputStream cis = new CryptoInputStream(transform, properties, inputStream, key, iv)) {
        byte[] decryptedData = new byte[1024];
        int decryptedLen = 0;
        int i;
        while ((i = cis.read(decryptedData, decryptedLen, decryptedData.length - decryptedLen)) > -1) {
            decryptedLen += i;
        }
        System.out.println("Decrypted: " + new String(decryptedData, 0, decryptedLen, StandardCharsets.UTF_8));
    }
}

From source file:org.apache.commons.crypto.examples.CipherByteArrayExample.java

public static void main(String[] args) throws Exception {

    final SecretKeySpec key = new SecretKeySpec(getUTF8Bytes("1234567890123456"), "AES");
    final IvParameterSpec iv = new IvParameterSpec(getUTF8Bytes("1234567890123456"));

    Properties properties = new Properties();
    properties.setProperty(CryptoCipherFactory.CLASSES_KEY, CipherProvider.OPENSSL.getClassName());
    //Creates a CryptoCipher instance with the transformation and properties.
    final String transform = "AES/CBC/PKCS5Padding";
    CryptoCipher encipher = Utils.getCipherInstance(transform, properties);
    System.out.println("Cipher:  " + encipher.getClass().getCanonicalName());

    final String sampleInput = "hello world!";
    System.out.println("input:  " + sampleInput);

    byte[] input = getUTF8Bytes(sampleInput);
    byte[] output = new byte[32];

    //Initializes the cipher with ENCRYPT_MODE, key and iv.
    encipher.init(Cipher.ENCRYPT_MODE, key, iv);
    //Continues a multiple-part encryption/decryption operation for byte array.
    int updateBytes = encipher.update(input, 0, input.length, output, 0);
    System.out.println(updateBytes);
    //We must call doFinal at the end of encryption/decryption.
    int finalBytes = encipher.doFinal(input, 0, 0, output, updateBytes);
    System.out.println(finalBytes);
    //Closes the cipher.
    encipher.close();/*from www.  ja v  a2 s .  c  o  m*/

    System.out.println(Arrays.toString(Arrays.copyOf(output, updateBytes + finalBytes)));

    // Now reverse the process using a different implementation with the same settings
    properties.setProperty(CryptoCipherFactory.CLASSES_KEY, CipherProvider.JCE.getClassName());
    CryptoCipher decipher = Utils.getCipherInstance(transform, properties);
    System.out.println("Cipher:  " + encipher.getClass().getCanonicalName());

    decipher.init(Cipher.DECRYPT_MODE, key, iv);
    byte[] decoded = new byte[32];
    decipher.doFinal(output, 0, updateBytes + finalBytes, decoded, 0);

    System.out.println("output: " + new String(decoded, StandardCharsets.UTF_8));
}

From source file:Main.java

private static AlgorithmParameterSpec getIV() {
    byte[] iv = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, };
    IvParameterSpec ivParameterSpec;
    ivParameterSpec = new IvParameterSpec(iv);
    return ivParameterSpec;
}

From source file:Main.java

private static byte[] encrypt(byte[] key, byte[] clear) throws Exception {
    SecretKeySpec skeySpec = new SecretKeySpec(key, "AES");
    Cipher cipher = Cipher.getInstance("AES");
    cipher.init(Cipher.ENCRYPT_MODE, skeySpec, new IvParameterSpec(new byte[cipher.getBlockSize()]));
    return cipher.doFinal(clear);
}