Example usage for org.bouncycastle.crypto.io CipherOutputStream write

List of usage examples for org.bouncycastle.crypto.io CipherOutputStream write

Introduction

In this page you can find the example usage for org.bouncycastle.crypto.io 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:net.nharyes.secrete.curve.Curve25519PrivateKey.java

License:Open Source License

public void serialize(OutputStream out, char[] password) throws IOException {

    try {//ww  w.  j a  va2  s. co  m

        // generate initial vector
        SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
        byte[] iv = new byte[16];
        random.nextBytes(iv);

        // generate salt
        byte[] salt = new byte[64];
        random.nextBytes(salt);

        // initialize cipher
        CipherParameters params = new ParametersWithIV(new KeyParameter(deriveKey(password, salt)), iv);
        BufferedBlockCipher cipher = new PaddedBufferedBlockCipher(new CBCBlockCipher(new AESEngine()),
                new PKCS7Padding());
        cipher.reset();
        cipher.init(true, params);

        // write magic number
        out.write(MagicNumbers.PRIVATE_KEY);
        out.flush();

        // write initial vector and salt
        out.write(iv);
        out.write(salt);
        out.flush();

        // write encrypted key to output stream
        ByteArrayOutputStream buf = new ByteArrayOutputStream();
        CipherOutputStream cout = new CipherOutputStream(buf, cipher);
        cout.write(key);
        cout.close();
        out.write(buf.toByteArray());
        out.flush();

    } catch (UnsupportedEncodingException | NoSuchAlgorithmException ex) {

        throw new UnsupportedOperationException(ex.getMessage(), ex);
    }
}