Example usage for javax.crypto Cipher getIV

List of usage examples for javax.crypto Cipher getIV

Introduction

In this page you can find the example usage for javax.crypto Cipher getIV.

Prototype

public final byte[] getIV() 

Source Link

Document

Returns the initialization vector (IV) in a new buffer.

Usage

From source file:MainClass.java

public static void main(String[] args) throws Exception {
    KeyGenerator keyGenerator = KeyGenerator.getInstance("Blowfish");

    keyGenerator.init(128);/*from  w  ww .j ava 2  s. co m*/
    Key secretKey = keyGenerator.generateKey();

    Cipher cipherOut = Cipher.getInstance("Blowfish/CFB/NoPadding");

    cipherOut.init(Cipher.ENCRYPT_MODE, secretKey);
    BASE64Encoder encoder = new BASE64Encoder();
    byte iv[] = cipherOut.getIV();
    if (iv != null) {
        System.out.println("Initialization Vector of the Cipher:\n" + encoder.encode(iv));
    }
    FileInputStream fin = new FileInputStream("inputFile.txt");
    FileOutputStream fout = new FileOutputStream("outputFile.txt");
    CipherOutputStream cout = new CipherOutputStream(fout, cipherOut);
    int input = 0;
    while ((input = fin.read()) != -1) {
        cout.write(input);
    }

    fin.close();
    cout.close();
}

From source file:MainClass.java

public static void main(String args[]) throws Exception {
    KeyGenerator kg = KeyGenerator.getInstance("DES");
    Cipher c = Cipher.getInstance("DES/CBC/PKCS5Padding");
    Key key = kg.generateKey();//from   www . j a va  2s.c  o m

    c.init(Cipher.ENCRYPT_MODE, key);
    byte input[] = "Stand and unfold yourself".getBytes();
    byte encrypted[] = c.doFinal(input);
    byte iv[] = c.getIV();

    IvParameterSpec dps = new IvParameterSpec(iv);
    c.init(Cipher.DECRYPT_MODE, key, dps);
    byte output[] = c.doFinal(encrypted);
    System.out.println(new String(output));
}

From source file:MainClass.java

public static void main(String args[]) throws Exception {
    KeyGenerator kg = KeyGenerator.getInstance("DES");
    kg.init(new SecureRandom());
    SecretKey key = kg.generateKey();
    SecretKeyFactory skf = SecretKeyFactory.getInstance("DES");
    Class spec = Class.forName("javax.crypto.spec.DESKeySpec");
    DESKeySpec ks = (DESKeySpec) skf.getKeySpec(key, spec);
    ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("keyfile"));
    oos.writeObject(ks.getKey());//from   w ww  .ja v  a2s .  com

    Cipher c = Cipher.getInstance("DES/CFB8/NoPadding");
    c.init(Cipher.ENCRYPT_MODE, key);
    CipherOutputStream cos = new CipherOutputStream(new FileOutputStream("ciphertext"), c);
    PrintWriter pw = new PrintWriter(new OutputStreamWriter(cos));
    pw.println("Stand and unfold yourself");
    pw.close();
    oos.writeObject(c.getIV());
    oos.close();
}

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[] 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:com.tremolosecurity.unison.u2f.util.U2fUtil.java

public static String encode(List<SecurityKeyData> devices, String encyrptionKeyName) throws Exception {
    ArrayList<KeyHolder> keys = new ArrayList<KeyHolder>();
    for (SecurityKeyData dr : devices) {
        KeyHolder kh = new KeyHolder();
        kh.setCounter(dr.getCounter());/*from  w w  w  .  j  a v a  2 s.co  m*/
        kh.setEnrollmentTime(dr.getEnrollmentTime());
        kh.setKeyHandle(dr.getKeyHandle());
        kh.setPublicKey(dr.getPublicKey());
        kh.setTransports(dr.getTransports());
        keys.add(kh);
    }

    String json = gson.toJson(keys);
    EncryptedMessage msg = new EncryptedMessage();

    SecretKey key = GlobalEntries.getGlobalEntries().getConfigManager().getSecretKey(encyrptionKeyName);
    if (key == null) {
        throw new Exception("Queue message encryption key not found");
    }

    Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
    cipher.init(Cipher.ENCRYPT_MODE, key);
    msg.setMsg(cipher.doFinal(json.getBytes("UTF-8")));
    msg.setIv(cipher.getIV());

    ByteArrayOutputStream baos = new ByteArrayOutputStream();

    DeflaterOutputStream compressor = new DeflaterOutputStream(baos,
            new Deflater(Deflater.BEST_COMPRESSION, true));

    compressor.write(gson.toJson(msg).getBytes("UTF-8"));
    compressor.flush();
    compressor.close();

    String b64 = new String(Base64.encodeBase64(baos.toByteArray()));

    return b64;

}

From source file:de.marius_oe.cfs.cryption.Crypter.java

/**
 * Encrypts the given input stream and stores the encrypted data in the
 * destinationFile.//ww w  . jav  a2  s .  c o  m
 *
 * @param inStream
 *            plain text stream
 * @param destinationStream
 *            stream for the encrypted data
 * @param compressStream
 *            whether the data should be compressed before encryption
 */
public static void encrypt(InputStream inStream, OutputStream destinationStream, boolean compressStream) {
    logger.debug("encrypting inputstream - compressed: {}", compressStream);

    InputStream tempInputStream;

    if (compressStream) {
        logger.debug("Compress InputStream.");
        tempInputStream = StreamUtils.zipStream(inStream);
    } else {
        tempInputStream = inStream;
    }

    Cipher cipher = getCipher(Cipher.ENCRYPT_MODE, null);

    logger.debug("Encrypt InputStream.");
    tempInputStream = new CipherInputStream(tempInputStream, cipher);

    try {
        // write iv to the beginning of the stream
        destinationStream.write((byte) cipher.getIV().length);
        destinationStream.write(cipher.getIV());

        int bytesCopied = IOUtils.copy(tempInputStream, destinationStream);

        logger.debug("encryption done. copied {} encrypted bytes to the outputstream", bytesCopied);

        tempInputStream.close();
        destinationStream.close();
    } catch (IOException e) {
        logger.error("Encryption failed - Reason: {}", e.getLocalizedMessage());
        throw new RuntimeException(e);
    }
}

From source file:com.tremolosecurity.provisioning.customTasks.CreateOTPKey.java

public static String generateEncryptedToken(String userID, GoogleAuthenticatorKey key, String hostName,
        ConfigManager cfg, String encryptionKey) throws ProvisioningException {
    TOTPKey totpkey = new TOTPKey();
    totpkey.setHost(hostName);/*from   w  w w  .  j av  a  2 s . c o m*/
    totpkey.setScratchCodes(key.getScratchCodes());
    totpkey.setSecretKey(key.getKey());
    totpkey.setUserName(userID);
    totpkey.setValidationCode(key.getVerificationCode());

    Gson gson = new Gson();
    String json = gson.toJson(totpkey);
    SecretKey sc = cfg.getSecretKey(encryptionKey);
    String attrVal = null;
    try {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        baos.write(json.getBytes("UTF-8"));

        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        cipher.init(Cipher.ENCRYPT_MODE, sc);

        byte[] encJson = cipher.doFinal(baos.toByteArray());
        String base64d = new String(org.bouncycastle.util.encoders.Base64.encode(encJson));

        Token token = new Token();
        token.setEncryptedRequest(base64d);
        token.setIv(new String(org.bouncycastle.util.encoders.Base64.encode(cipher.getIV())));

        json = gson.toJson(token);
        attrVal = new String(org.bouncycastle.util.encoders.Base64.encode(json.getBytes("UTF-8")));

    } catch (Exception e) {
        throw new ProvisioningException("Could not encrypt key", e);
    }
    return attrVal;
}

From source file:alfio.manager.CheckInManager.java

public static String encrypt(String key, String payload) {
    try {//from  w w  w  . j  a v  a  2  s . com
        Pair<Cipher, SecretKeySpec> cipherAndSecret = getCypher(key);
        Cipher cipher = cipherAndSecret.getKey();
        cipher.init(Cipher.ENCRYPT_MODE, cipherAndSecret.getRight());
        byte[] data = cipher.doFinal(payload.getBytes(StandardCharsets.UTF_8));
        byte[] iv = cipher.getIV();
        return Base64.encodeBase64URLSafeString(iv) + "|" + Base64.encodeBase64URLSafeString(data);
    } catch (GeneralSecurityException e) {
        throw new IllegalStateException(e);
    }
}

From source file:org.mozilla.android.sync.Cryptographer.java

public static CryptoInfo encrypt(CryptoInfo info) {

    Cipher cipher = getCipher();
    try {/*from ww  w.  j  a v  a2 s . com*/
        cipher.init(Cipher.ENCRYPT_MODE,
                new SecretKeySpec(info.getKeys().getEncryptionKey(), KEY_ALGORITHM_SPEC));
    } catch (InvalidKeyException e) {
        e.printStackTrace();
        return null;
    }

    // Encrypt
    byte[] encryptedBytes = commonCrypto(cipher, info.getMessage());
    info.setMessage(encryptedBytes);

    // Save IV
    info.setIv(cipher.getIV());

    // Generate HMAC
    info.setHmac(generateHmac(info));

    return info;

}