Example usage for javax.crypto CipherOutputStream write

List of usage examples for javax.crypto CipherOutputStream write

Introduction

In this page you can find the example usage for javax.crypto CipherOutputStream write.

Prototype

public void write(byte b[]) throws IOException 

Source Link

Document

Writes b.length bytes from the specified byte array to this output stream.

Usage

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 . j  a  va2s .  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 {
    KeyGenerator keyGenerator = KeyGenerator.getInstance("Blowfish");

    keyGenerator.init(128);//from   w  ww  .jav  a2 s. c o  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 desEncrypt(String f1, String f2) throws Exception {
    SecretKey key = null;/*  w  w w  . ja  v  a  2 s.c om*/
    ObjectInputStream keyFile = new ObjectInputStream(new FileInputStream("DESKey.ser"));
    key = (SecretKey) keyFile.readObject();
    keyFile.close();

    KeyGenerator keygen = KeyGenerator.getInstance("DES");
    key = keygen.generateKey();
    ObjectOutputStream keyFileout = new ObjectOutputStream(new FileOutputStream("DESKey.ser"));
    keyFileout.writeObject(key);
    keyFileout.close();
    Cipher cipher = null;
    cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
    cipher.init(Cipher.ENCRYPT_MODE, key);
    BufferedInputStream in = new BufferedInputStream(new FileInputStream(f1));

    CipherOutputStream out = new CipherOutputStream(new BufferedOutputStream(new FileOutputStream(f2)), cipher);
    int i;
    do {
        i = in.read();
        if (i != -1)
            out.write(i);
    } while (i != -1);
    in.close();
    out.close();
}

From source file:Main.java

@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2)
private static String encryptStringImpl(Context context, final String plainText) {
    String encryptedText = plainText;
    try {/*from   w ww  . jav  a 2s  . co m*/
        final KeyStore keyStore = getKeyStore(context);

        PublicKey publicKey = keyStore.getCertificate(KEY_ALIAS).getPublicKey();

        String algorithm = ALGORITHM_OLD;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            algorithm = ALGORITHM;
        }
        Cipher cipher = Cipher.getInstance(algorithm);
        cipher.init(Cipher.ENCRYPT_MODE, publicKey);

        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        CipherOutputStream cipherOutputStream = new CipherOutputStream(outputStream, cipher);
        cipherOutputStream.write(plainText.getBytes("UTF-8"));
        cipherOutputStream.close();

        byte[] bytes = outputStream.toByteArray();
        encryptedText = Base64.encodeToString(bytes, Base64.DEFAULT);
    } catch (Exception e) {
        e.printStackTrace();
    }
    return encryptedText;
}

From source file:org.panbox.core.crypto.CryptCore.java

public static byte[] _asymmetricDecrypt(byte[] symKey, PrivateKey pKey)
        throws InvalidKeyException, IOException {
    ASYMM_CIPHER.init(Cipher.DECRYPT_MODE, pKey);
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    CipherOutputStream cos = new CipherOutputStream(bos, ASYMM_CIPHER);
    cos.write(symKey);
    cos.flush();// w  ww  .  j  av  a2s.com
    cos.close();
    byte[] byteArray = bos.toByteArray();
    return byteArray;
}

From source file:org.panbox.core.crypto.CryptCore.java

public static byte[] encryptSymmetricKey(byte[] symKey, PublicKey pKey) throws SymmetricKeyEncryptionException {
    try {/*from   ww w  .  j  av a 2s.c  o  m*/
        ASYMM_CIPHER.init(Cipher.ENCRYPT_MODE, pKey);
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        CipherOutputStream cos = new CipherOutputStream(bos, ASYMM_CIPHER);
        cos.write(symKey);
        cos.flush();
        cos.close();
        byte[] byteArray = bos.toByteArray();
        return byteArray;
    } catch (Exception e) {
        throw new SymmetricKeyEncryptionException(e);
    }
}

From source file:com.data.pack.Util.java

public static void copyFile(InputStream in, OutputStream out, int flag) throws IOException {
    byte[] buffer = new byte[1024];
    int read;/*  ww  w .j av a  2 s .  c  om*/

    try {

        Cipher encipher = null;
        try {
            encipher = Cipher.getInstance("AES");
        } catch (NoSuchAlgorithmException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (NoSuchPaddingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        Cipher decipher = null;
        try {
            decipher = Cipher.getInstance("AES");
        } catch (NoSuchAlgorithmException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (NoSuchPaddingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        KeyGenerator kgen = null;
        try {
            kgen = KeyGenerator.getInstance("AES");
        } catch (NoSuchAlgorithmException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        byte[] keyStart = "fitnesSbridge".getBytes();
        SecureRandom sr = SecureRandom.getInstance("SHA1PRNG");
        sr.setSeed(keyStart);
        kgen.init(128, sr); // 192 and 256 bits may not be available
        SecretKey skey = kgen.generateKey();

        // byte key[] =
        // {0x00,0x32,0x22,0x11,0x00,0x00,0x00,0x00,0x00,0x23,0x00,0x00,0x00,0x00,0x00,0x00,0x00};
        skey = kgen.generateKey();
        // Lgo
        try {
            encipher.init(Cipher.ENCRYPT_MODE, skey);
        } catch (InvalidKeyException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        CipherInputStream cis = new CipherInputStream(in, encipher);
        try {
            decipher.init(Cipher.DECRYPT_MODE, skey);
        } catch (InvalidKeyException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        CipherOutputStream cos = new CipherOutputStream(out, decipher);

        try {

            if (flag == 2) {
                cos = new CipherOutputStream(out, encipher);
            } else {
                cos = new CipherOutputStream(out, decipher);
            }
            while ((read = in.read()) != -1) {
                cos.write(read);
                cos.flush();
            }

            cos.flush();
            cos.close();
            in.close();

        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        try {
            out.close();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    } catch (Exception e) {
        // TODO: handle exception
    }

    //
    // byte[] keyStart = "this is a key".getBytes();
    // KeyGenerator kgen = KeyGenerator.getInstance("AES");
    // SecureRandom sr = SecureRandom.getInstance("SHA1PRNG");
    // sr.setSeed(keyStart);
    // kgen.init(128, sr); // 192 and 256 bits may not be available
    // SecretKey skey = kgen.generateKey();
    // byte[] key = skey.getEncoded();
    //
    //
    // byte[] b = baos.toByteArray();
    // while ((read = in.read(buffer)) != -1) {
    //
    // // decrypt
    // byte[] decryptedData = Util.decrypt(key,buffer);
    // out.write(decryptedData, 0, read);
    // }
    // } catch (NoSuchAlgorithmException e) {
    // // TODO Auto-generated catch block
    // e.printStackTrace();
    // }
    // catch (Exception e) {
    // // TODO: handle exception
    // }
    //
}

From source file:com.cubusmail.server.mail.security.MailPasswordEncryptor.java

public byte[] encryptPassowrd(String password) {

    Cipher cipher;//from   w w  w. java 2s.c  om
    try {
        cipher = Cipher.getInstance(this.algorithm);
        cipher.init(Cipher.ENCRYPT_MODE, this.keyPair.getPublic());

        ByteArrayOutputStream baosEncryptedData = new ByteArrayOutputStream();
        CipherOutputStream cos = new CipherOutputStream(baosEncryptedData, cipher);

        cos.write(password.getBytes("UTF-8"));
        cos.flush();
        cos.close();

        return baosEncryptedData.toByteArray();
    } catch (Exception e) {
        log.error(e.getMessage(), e);
        throw new IllegalStateException(e.getMessage(), e);
    }
}

From source file:enc_mods.aes.java

/**
 * Encrypts the AES key to a file using an RSA public key
 *//*  w w  w .j a v  a  2  s  .c om*/
public void saveKey(File out, File publicKeyFile) {
    try {
        // read public key to be used to encrypt the AES key
        byte[] encodedKey = new byte[(int) publicKeyFile.length()];
        new FileInputStream(publicKeyFile).read(encodedKey);

        // create public key
        X509EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(encodedKey);
        KeyFactory kf = KeyFactory.getInstance("RSA");
        PublicKey pk = kf.generatePublic(publicKeySpec);

        // write AES key
        cipher.init(Cipher.ENCRYPT_MODE, pk);
        CipherOutputStream os = new CipherOutputStream(new FileOutputStream(out), cipher);
        os.write(key);
        os.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:net.tawacentral.roger.secrets.FileUtils.java

/**
 * Returns an encrypted json stream representing the user's secrets.
 *
 * @param cipher//from   w w  w  . jav a 2  s.c o m
 *          The encryption cipher to use with the file.
 * @param secrets
 *          The list of secrets.
 * @return byte array of secrets
 * @throws IOException
 *           if any error occurs
 */
public static byte[] toEncryptedJSONSecretsStream(Cipher cipher, ArrayList<Secret> secrets) throws IOException {
    CipherOutputStream output = null;
    ByteArrayOutputStream baos = new ByteArrayOutputStream();

    try {
        output = new CipherOutputStream(baos, cipher);
        output.write(FileUtils.toJSONSecrets(secrets).toString().getBytes("UTF-8"));
    } catch (Exception e) {
        Log.e(LOG_TAG, "toEncryptedJSONSecretsStream", e);
        throw new IOException("toEncryptedJSONSecretsStream failed: " + e.getMessage());
    } finally {
        try {
            if (null != output)
                output.close();
        } catch (IOException ex) {
        }
    }

    return baos.toByteArray();
}