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:sec_algo.commonenc.java

/**
 * Encrypts the AES key to a file using an RSA public key
 *///from ww w  .  j a v  a2 s . c  o m
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
        pkCipher.init(Cipher.ENCRYPT_MODE, pk);
        CipherOutputStream os = new CipherOutputStream(new FileOutputStream(out), pkCipher);
        os.write(key);
        os.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:edu.ncsu.asbransc.mouflon.recorder.UploadFile.java

private void encryptAndWriteAESKey(SecretKey aeskey, File dest)
        throws IOException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeySpecException,
        InvalidKeyException, IllegalBlockSizeException, BadPaddingException, NoSuchProviderException {
    Cipher keyc;// ww  w .  ja v a 2  s.  c o  m
    AssetManager am = getAssets();
    InputStream in = am.open("mouflon_key.pub");
    byte[] readFromFile = new byte[in.available()];
    //TODO check that this is 294 bytes and replace with a constant. in.available is not guaranteed to return a useful value
    in.read(readFromFile);
    keyc = Cipher.getInstance("RSA/ECB/PKCS1Padding", "BC");
    //ECB and CBC etc don't make sense for RSA, but the way this API is designed you have to specify something.
    KeyFactory kf = KeyFactory.getInstance("RSA");
    KeySpec ks = new X509EncodedKeySpec(readFromFile);
    RSAPublicKey key = (RSAPublicKey) kf.generatePublic(ks);
    keyc.init(Cipher.ENCRYPT_MODE, key);
    //byte[] encrpytedKey = keyc.doFinal(aeskey.getEncoded());
    FileOutputStream out = new FileOutputStream(dest);
    CipherOutputStream outcipher = new CipherOutputStream(out, keyc);
    outcipher.write(aeskey.getEncoded());
    outcipher.close();
    out.close();
}

From source file:de.schildbach.wallet.util.FingerprintHelper.java

@RequiresApi(api = Build.VERSION_CODES.M)
public boolean encryptPassword(Cipher cipher, String password) {
    try {//from w  w  w .  j a  va  2 s  . c  o  m
        // Encrypt the text
        if (password.isEmpty()) {
            log.info("Password is empty");
            return false;
        }

        if (cipher == null) {
            log.info("Could not create cipher");
            return false;
        }

        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        CipherOutputStream cipherOutputStream = new CipherOutputStream(outputStream, cipher);
        byte[] bytes = password.getBytes(Charset.defaultCharset());
        cipherOutputStream.write(bytes);
        cipherOutputStream.flush();
        cipherOutputStream.close();
        saveEncryptedPassword(encodeBytes(outputStream.toByteArray()));
    } catch (Throwable t) {
        log.info("Encryption failed " + t.getMessage());
        return false;
    }

    return true;
}

From source file:nl.afas.cordova.plugin.secureLocalStorage.SecureLocalStorage.java

private void writeAndEncryptStorage(KeyStore keyStore, HashMap<String, String> hashMap)
        throws SecureLocalStorageException {

    try {/*from w  w w . j  a v  a  2 s .co  m*/
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        try {
            ObjectOutputStream oos = new ObjectOutputStream(bos);
            try {
                oos.writeObject(hashMap);
            } finally {
                oos.close();
            }
        } finally {
            bos.close();
        }

        SecretKey key = getSecretKey(keyStore);

        Cipher input = Cipher.getInstance("DES");
        input.init(Cipher.ENCRYPT_MODE, key);

        // encrypt the hashmap
        FileOutputStream fos = _cordova.getActivity().openFileOutput(SECURELOCALSTORAGEFILE,
                Context.MODE_PRIVATE);
        try {
            CipherOutputStream cipherOutputStream = new CipherOutputStream(fos, input);
            try {
                cipherOutputStream.write(bos.toByteArray());
            } finally {
                cipherOutputStream.flush();
                cipherOutputStream.close();
            }
        } finally {
            fos.flush();
            fos.close();
        }

    } catch (Exception e) {
        Log.e("SecureStorage", "Write", e);
        throw new SecureLocalStorageException("Error encrypting storage", e);
    }
}

From source file:nl.afas.cordova.plugin.secureLocalStorage.SecureLocalStorage.java

private void generateKey(KeyStore keyStore) throws SecureLocalStorageException {

    try {//from ww  w . ja va 2  s  . c  o m
        _key = null;

        SecretKey key = KeyGenerator.getInstance("DES").generateKey();
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        try {
            ObjectOutputStream oos = new ObjectOutputStream(bos);
            try {
                oos.writeObject(key);
            } finally {
                oos.close();
            }
        } finally {
            bos.close();
        }

        // store key encrypted with keystore key pair
        KeyStore.PrivateKeyEntry privateKeyEntry = (KeyStore.PrivateKeyEntry) keyStore
                .getEntry(SECURELOCALSTORAGEALIAS, null);

        Cipher input = Cipher.getInstance("RSA/ECB/PKCS1Padding");
        input.init(Cipher.ENCRYPT_MODE, privateKeyEntry.getCertificate().getPublicKey());

        FileOutputStream fos = _cordova.getActivity().openFileOutput(SECURELOCALSTORAGEKEY,
                Context.MODE_PRIVATE);
        try {
            CipherOutputStream cipherOutputStream = new CipherOutputStream(fos, input);
            try {
                cipherOutputStream.write(bos.toByteArray());
            } finally {
                cipherOutputStream.close();
            }
        } finally {
            fos.close();
        }

    } catch (Exception e) {
        Log.e("SecureStorage", "Read", e);
        throw new SecureLocalStorageException("Error generating key", e);
    }
}

From source file:uk.ac.ox.webauth.Token.java

/**
 * Encode the token and return it.//from   w w w . jav  a  2s  .c o  m
 * @param   sessionKey  The session key to use to AES encrypt and feed the HMAC.
 * @return  The escaped, encrypted and base64 encoded token.
 * @throws  GeneralSecurityException    if there was a problem with the security code used.
 */
public String encrypt(Key sessionKey) throws GeneralSecurityException {
    // a token is:
    // {key-hint}{nonce   }{hmac    }{token-attributes     }{padding         }
    // {4 bytes }{16 bytes}{20 bytes}{make the data into multiple of 16 bytes}
    // everything after the key hint is aes encrypted

    // this is where we want to final data packet to end up
    ByteArrayOutputStream data = new ByteArrayOutputStream();
    try {
        data.write(unixTimestampBytes(System.currentTimeMillis()));

        // set up the AES encryption
        Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
        cipher.init(ENCRYPT_MODE, sessionKey, IV);
        CipherOutputStream encrypt = new CipherOutputStream(data, cipher);

        // write the nonce
        byte[] nonce = new byte[16];
        RAND.nextBytes(nonce);
        encrypt.write(nonce);

        // put together the actual key-value pair data to send
        ByteArrayOutputStream paddedKeyValueData = new ByteArrayOutputStream();
        for (KeyValuePair kvp : kv.values()) {
            paddedKeyValueData.write(kvp.bytes());
        }

        // and pad it (including the size of the hmac to be added later)
        int padding = 16 - ((20 + paddedKeyValueData.size()) % 16);
        for (int i = 0; i < padding; i++) {
            paddedKeyValueData.write(padding);
        }
        byte[] paddedKeyValueDataArray = paddedKeyValueData.toByteArray();

        // then work out and write the SHA1 HMAC
        Mac hmacSHA1 = Mac.getInstance("HmacSHA1");
        hmacSHA1.init(sessionKey);
        encrypt.write(hmacSHA1.doFinal(paddedKeyValueDataArray));

        // then write the actual key-value pair data and padding and close it
        encrypt.write(paddedKeyValueDataArray);
        encrypt.close();
    } catch (IOException ioe) {
        /* should never happen as it's a ByteArrayOutputStream */
        ioe.printStackTrace();
    }

    // return the token after base64 encoding it
    return new String(Base64.encodeBase64(data.toByteArray()));
}

From source file:org.openchaos.android.fooping.service.PingService.java

private void sendMessage(final JSONObject json) {
    boolean encrypt = prefs.getBoolean("SendAES", false);
    boolean compress = prefs.getBoolean("SendGZIP", false);
    String exchangeHost = prefs.getString("ExchangeHost", null);
    int exchangePort = Integer.valueOf(prefs.getString("ExchangePort", "-1"));

    if (encrypt) {
        if (skeySpec == null) {
            try {
                skeySpec = new SecretKeySpec(MessageDigest.getInstance("SHA-256")
                        .digest(prefs.getString("ExchangeKey", null).getBytes("US-ASCII")), "AES");
            } catch (Exception e) {
                Log.e(tag, e.toString());
                e.printStackTrace();//from ww w. j a v  a  2s  . c o m
            }
        }

        if (cipher == null) {
            try {
                cipher = Cipher.getInstance("AES/CFB8/NoPadding");
            } catch (Exception e) {
                Log.e(tag, e.toString());
                e.printStackTrace();
            }
        }

        if (skeySpec == null || cipher == null) {
            Log.e(tag, "Encryption requested but not available");
            throw new AssertionError();
        }
    }

    if (exchangeHost == null || exchangePort <= 0 || exchangePort >= 65536) {
        Log.e(tag, "Invalid server name or port");
        throw new AssertionError();
    }

    try {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        CipherOutputStream cos = null;
        GZIPOutputStream zos = null;

        // TODO: send protocol header to signal compression & encryption

        if (encrypt) {
            cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
            cos = new CipherOutputStream(baos, cipher);

            // write iv block
            baos.write(cipher.getIV());
        }

        final byte[] message = new JSONArray().put(json).toString().getBytes();

        if (compress) {
            zos = new GZIPOutputStream((encrypt) ? (cos) : (baos));
            zos.write(message);
            zos.finish();
            zos.close();
            if (encrypt) {
                cos.close();
            }
        } else if (encrypt) {
            cos.write(message);
            cos.close();
        } else {
            baos.write(message);
        }

        baos.flush();
        final byte[] output = baos.toByteArray();
        baos.close();

        // path MTU is the actual limit here, not only local MTU
        // TODO: make packet fragmentable (clear DF flag)
        if (output.length > 1500) {
            Log.w(tag, "Message probably too long: " + output.length + " bytes");
        }

        DatagramSocket socket = new DatagramSocket();
        // socket.setTrafficClass(0x04 | 0x02); // IPTOS_RELIABILITY | IPTOS_LOWCOST
        socket.send(
                new DatagramPacket(output, output.length, InetAddress.getByName(exchangeHost), exchangePort));
        socket.close();
        Log.d(tag, "message sent: " + output.length + " bytes (raw: " + message.length + " bytes)");
    } catch (Exception e) {
        Log.e(tag, e.toString());
        e.printStackTrace();
    }
}

From source file:com.zacwolf.commons.crypto._CRYPTOfactory.java

public final void encryptToOutputStream(final byte[] bytes, final OutputStream outputStream)
        throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException,
        InvalidAlgorithmParameterException, IOException {
    ready();//from   w w w.  j  a va 2s  .  c o m
    activecrypts++;
    try {
        final Cipher ecipher = crypter.getEcipher();
        final byte[] salt = ecipher.getIV();
        if (salt == null) {
            outputStream.write(0);
        } else {
            outputStream.write(salt.length);
            outputStream.write(salt);
        }
        outputStream.flush();
        CipherOutputStream cop = null;
        try {
            cop = new CipherOutputStream(outputStream, ecipher) {
                /*
                 * WebSphere 7 has a known bug with it's implementation of ibmjceprovider.jar
                 * concerning writing byte-arrays in a serialized object when the byte-array length
                 * is zero.
                 * see: http://www.ibm.com/developerworks/forums/thread.jspa?messageID=14597510
                 * 
                 * Added an override of the CipherOutputStream write method so that it is only called when
                 * the byte array has length > 0
                 */
                @Override
                public void write(final byte[] b, final int off, final int len) throws IOException {
                    if (len > 0) {
                        super.write(b, off, len);
                        //super.flush(); Do NOT flush here, as it slows the process down exponentially
                    }
                }
            };
            cop.write(bytes);
            cop.flush();
        } finally {
            if (cop != null) {
                cop.flush();
                cop.close();
            }
            outputStream.flush();
            outputStream.close();
        }
    } finally {
        activecrypts--;
    }
}