Example usage for org.bouncycastle.crypto.params AEADParameters AEADParameters

List of usage examples for org.bouncycastle.crypto.params AEADParameters AEADParameters

Introduction

In this page you can find the example usage for org.bouncycastle.crypto.params AEADParameters AEADParameters.

Prototype

public AEADParameters(KeyParameter key, int macSize, byte[] nonce) 

Source Link

Document

Base constructor.

Usage

From source file:ECToken3.java

License:Open Source License

public static final String encryptv3(String key, String input) throws java.io.UnsupportedEncodingException,
        java.security.NoSuchAlgorithmException, javax.crypto.NoSuchPaddingException,
        java.security.InvalidKeyException, javax.crypto.IllegalBlockSizeException,
        javax.crypto.BadPaddingException, java.security.InvalidAlgorithmParameterException {

    //System.out.format("+-------------------------------------------------------------\n");
    //System.out.format("| Encrypt\n");
    //System.out.format("+-------------------------------------------------------------\n");
    //System.out.format("| key:                   %s\n", key);
    //System.out.format("| token:                 %s\n", input);

    //----------------------------------------------------
    // Get SHA-256 of key
    //----------------------------------------------------
    MessageDigest md = MessageDigest.getInstance("SHA-256");
    md.update(key.getBytes("ASCII"));
    byte[] keyDigest = md.digest();

    //----------------------------------------------------
    // Get Random IV
    //----------------------------------------------------
    SecureRandom random = new SecureRandom();
    byte[] ivBytes = new byte[12];
    random.nextBytes(ivBytes);//from w  w w  .ja v a 2 s .c o m

    //----------------------------------------------------
    // Encrypt
    //----------------------------------------------------
    AEADBlockCipher cipher = new GCMBlockCipher(new AESEngine());
    cipher.init(true, new AEADParameters(new KeyParameter(keyDigest), MAC_SIZE_BITS, ivBytes));
    byte[] inputBytes = input.getBytes("ASCII");

    byte[] enc = new byte[cipher.getOutputSize(inputBytes.length)];

    try {
        int res = cipher.processBytes(inputBytes, 0, inputBytes.length, enc, 0);
        cipher.doFinal(enc, res);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }

    byte[] ivPlusCipherText = new byte[ivBytes.length + enc.length];
    System.arraycopy(ivBytes, 0, ivPlusCipherText, 0, ivBytes.length);
    System.arraycopy(enc, 0, ivPlusCipherText, ivBytes.length, enc.length);

    //System.out.format("+-------------------------------------------------------------\n");
    //System.out.format("| iv:                    %s\n", bytesToHex(ivBytes));
    //System.out.format("| ciphertext:            %s\n", bytesToHex(Arrays.copyOfRange(enc, 0, enc.length - 16)));
    //System.out.format("| tag:                   %s\n", bytesToHex(Arrays.copyOfRange(enc, enc.length - 16, enc.length)));
    //System.out.format("+-------------------------------------------------------------\n");
    //System.out.format("| token:                 %s\n", bytesToHex(ivPlusCipherText));
    //System.out.format("+-------------------------------------------------------------\n");

    String result = null;
    byte[] temp = null;
    Base64 encoder = new Base64(0, temp, true);
    byte[] encodedBytes = encoder.encode(ivPlusCipherText);
    String encodedStr = new String(encodedBytes, "ASCII").trim();
    String encodedStrTrim = encodedStr.trim();
    return encodedStr.trim();
}

From source file:ECToken3.java

License:Open Source License

public static final String decryptv3(String key, String input) throws java.io.UnsupportedEncodingException,
        java.security.NoSuchAlgorithmException, javax.crypto.NoSuchPaddingException,
        java.security.InvalidKeyException, javax.crypto.IllegalBlockSizeException,
        javax.crypto.BadPaddingException, java.security.InvalidAlgorithmParameterException {

    //----------------------------------------------------
    // Base64 decode
    //----------------------------------------------------
    String result = null;//from  w ww . j a  va  2 s .  c  om
    Base64 encoder = new Base64(true);
    byte[] inputBytes = encoder.decode(input.getBytes("ASCII"));

    //----------------------------------------------------
    // Get SHA-256 of key
    //----------------------------------------------------
    MessageDigest md = MessageDigest.getInstance("SHA-256");
    md.update(key.getBytes("ASCII"));
    byte[] keyDigest = md.digest();

    //System.out.format("+-------------------------------------------------------------\n");
    //System.out.format("| Decrypt\n");
    //System.out.format("+-------------------------------------------------------------\n");
    //System.out.format("| key:                   %s\n", key);
    //System.out.format("| token:                 %s\n", input);

    //----------------------------------------------------
    // Rip up the ciphertext
    //----------------------------------------------------
    byte[] ivBytes = new byte[12];
    ivBytes = Arrays.copyOfRange(inputBytes, 0, ivBytes.length);

    byte[] cipherBytes = new byte[inputBytes.length - ivBytes.length];
    cipherBytes = Arrays.copyOfRange(inputBytes, ivBytes.length, inputBytes.length);

    //----------------------------------------------------
    // Decrypt
    //----------------------------------------------------
    AEADBlockCipher cipher = new GCMBlockCipher(new AESEngine());
    cipher.init(false, new AEADParameters(new KeyParameter(keyDigest), MAC_SIZE_BITS, ivBytes));

    //System.out.format("+-------------------------------------------------------------\n");
    //System.out.format("| iv:                    %s\n", bytesToHex(ivBytes));
    //System.out.format("| ciphertext:            %s\n", bytesToHex(Arrays.copyOfRange(cipherBytes, 0, cipherBytes.length - 16)));
    //System.out.format("| tag:                   %s\n", bytesToHex(Arrays.copyOfRange(cipherBytes, cipherBytes.length - 16, cipherBytes.length)));
    //System.out.format("+-------------------------------------------------------------\n");

    byte[] dec = new byte[cipher.getOutputSize(cipherBytes.length)];

    try {
        int res = cipher.processBytes(cipherBytes, 0, cipherBytes.length, dec, 0);
        cipher.doFinal(dec, res);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }

    //System.out.format("token: %s\n", new String(dec, "ASCII"));
    return new String(dec, "ASCII");
}

From source file:at.archistar.crypto.symmetric.AESGCMEncryptor.java

@Override
public byte[] encrypt(byte[] data, byte[] randomKeyBytes) throws IOException, InvalidKeyException,
        InvalidAlgorithmParameterException, InvalidCipherTextException, ImpossibleException {

    AEADBlockCipher cipher = new GCMBlockCipher(new AESFastEngine());
    cipher.init(true, new AEADParameters(new KeyParameter(randomKeyBytes), 128, randomIvBytes));
    return cipherData(cipher, data);
}

From source file:at.archistar.crypto.symmetric.AESGCMEncryptor.java

@Override
public byte[] decrypt(byte[] data, byte[] randomKey)
        throws InvalidKeyException, InvalidAlgorithmParameterException, IOException, IllegalStateException,
        InvalidCipherTextException, ImpossibleException {

    AEADBlockCipher cipher = new GCMBlockCipher(new AESFastEngine());
    cipher.init(false, new AEADParameters(new KeyParameter(randomKey), 128, randomIvBytes));
    return cipherData(cipher, data);
}

From source file:cologne.eck.peafactory.crypto.EAXMode.java

License:Open Source License

/**
 * Encrypt/decrypt an array of bytes//  w w  w.j  a v a  2  s  .  c  om
 * 
 * @param forEncryption - true for encryption, false for decryption
 * @param input         - plain text or cipher text
 * @param key         - the cryptographic key for the cipher
 * @param nonce         - unique Nonce of 8 byte
 * @return            - plain text or cipher text
 */
public final byte[] processBytes(boolean forEncryption, byte[] input, byte[] key, byte[] nonce) {

    int resultLen = 0;// proceeded bytes

    KeyParameter aeKey = new KeyParameter(key);

    int macLength = CipherStuff.getCipherAlgo().getBlockSize();
    if (macLength < 16) {
        System.out.println("Warning: short mac size: " + macLength);
    }

    EAXBlockCipher eaxCipher = new EAXBlockCipher(CipherStuff.getCipherAlgo());

    AEADParameters params = new AEADParameters(aeKey, macLength * 8, nonce);

    eaxCipher.init(forEncryption, params);

    byte[] result = new byte[eaxCipher.getOutputSize(input.length)];
    resultLen = eaxCipher.processBytes(input, 0, input.length, result, 0);
    try {
        resultLen += eaxCipher.doFinal(result, resultLen);
        // KeyParameter uses a copy of the key: 
        Zeroizer.zero(aeKey.getKey());
    } catch (IllegalStateException e) {
        CipherStuff.setErrorMessage("Internal application error");
        System.err.println("EAXMode - processBytes: " + e.toString());
        return null;
    } catch (InvalidCipherTextException e) {

        System.err.println("Authentication failed. ");
        if (PswDialogBase.getWorkingMode().equals("-r")) { // rescue mode

            Object[] options = { "Continue decryption despite error", "Do not decrypt" };
            int n = JOptionPane.showOptionDialog(null,
                    "Authentication failed:  \n" + "The content is not the previousely encrypted content. \n"
                            + "Normally that means, that the password is not correct, \n"
                            + "but there is the possibility that the file is damaged. \n"
                            + "In this case, some parts of the file might be restored \n"
                            + "by the decryption. \n" + "If you are sure, the password is correct, continue.\n"
                            + "Warning: For incorrect password files may be irretrievably lost. ",
                    "Authentication Error", JOptionPane.YES_NO_OPTION, JOptionPane.ERROR_MESSAGE, null, options,
                    options[1]);

            if (n == JOptionPane.YES_OPTION) {
                return result;
            } else {
                return null;
            }
        } else {// not rescue mode
            CipherStuff.setErrorMessage("Authentication failed");
            return null;
        }
    } catch (Exception e) {
        CipherStuff.setErrorMessage("Unexpected error");
        return null;
    }
    return result;
}

From source file:com.github.horrorho.inflatabledonkey.cache.StreamCryptor.java

License:Open Source License

public CipherOutputStream newCipherOutputStream(OutputStream os, byte[] password) throws IOException {
    byte[] salt = randomBytes(saltLength);
    byte[] nonce = randomBytes(nonceLength);
    os.write(salt);/*from ww w. ja v  a 2  s .  c o  m*/
    os.write(nonce);
    byte[] dk = kdf.apply(password, salt);
    GCMBlockCipher cipher = new GCMBlockCipher(new AESEngine());
    AEADParameters parameters = new AEADParameters(new KeyParameter(dk), tagLength * 8, nonce);
    cipher.init(true, parameters);
    return new CipherOutputStream(os, cipher);
}

From source file:com.github.horrorho.inflatabledonkey.cache.StreamCryptor.java

License:Open Source License

public CipherInputStream newCipherInputStream(InputStream is, byte[] password) throws IOException {
    byte[] salt = IOUtils.readFully(is, saltLength);
    byte[] nonce = IOUtils.readFully(is, nonceLength);
    byte[] dk = kdf.apply(password, salt);
    GCMBlockCipher cipher = new GCMBlockCipher(new AESEngine());
    AEADParameters parameters = new AEADParameters(new KeyParameter(dk), tagLength * 8, nonce);
    cipher.init(false, parameters);//  w  w w .j a v  a  2s.co  m
    return new CipherInputStream(is, cipher);
}

From source file:com.github.horrorho.inflatabledonkey.crypto.GCMDataB.java

License:Open Source License

public static byte[] decrypt(byte[] key, byte[] data) {
    // TODO utilize GCMAES#decrypt method
    try {/*www.  j  av  a  2s .c om*/
        if (data.length < NONCE_LENGTH + TAG_LENGTH) {
            throw new IllegalArgumentException("data packet too short");
        }

        int cipherTextLength = data.length - NONCE_LENGTH - TAG_LENGTH;

        byte[] nonce = Arrays.copyOf(data, NONCE_LENGTH);

        GCMBlockCipher cipher = new GCMBlockCipher(new AESFastEngine());
        AEADParameters parameters = new AEADParameters(new KeyParameter(key), TAG_LENGTH * 8, nonce);
        cipher.init(false, parameters);

        byte[] out = new byte[cipher.getOutputSize(cipherTextLength + TAG_LENGTH)];

        int pos = cipher.processBytes(data, NONCE_LENGTH, data.length - NONCE_LENGTH, out, 0);
        pos += cipher.doFinal(out, pos);

        return Arrays.copyOf(out, pos);

    } catch (IllegalStateException | InvalidCipherTextException ex) {
        throw new IllegalArgumentException(ex);
    }
}

From source file:org.avasquez.seccloudfs.utils.CryptoUtils.java

License:Open Source License

/**
 * Creates a cipher that uses AES encryption with GCM block mode.
 *
 * @param forEncryption true if the cipher is going to be used for encryption, false for decryption
 * @param key           the encryption key
 * @param iv            the initialization vector, or nonce
 *
 * @return the initialized cipher/*from  w w  w.ja  v  a2 s.  c  o m*/
 */
public static AEADBlockCipher createAesWithGcmCipher(boolean forEncryption, byte[] key, byte[] iv) {
    AEADBlockCipher cipher = new GCMBlockCipher(new AESEngine());
    cipher.init(forEncryption, new AEADParameters(new KeyParameter(key), 128, iv));

    return cipher;
}

From source file:org.sfs.encryption.CipherWriteStreamValidation.java

License:Apache License

public CipherWriteStreamValidation(byte[] secretBytes, byte[] salt) {
    this.salt = salt.clone();
    secretBytes = secretBytes.clone();//from   w  w w  .j av  a2s.  c  om
    if (secretBytes.length != KEY_SIZE_BYTES) {
        secretBytes = Hashing.sha256().hashBytes(secretBytes).asBytes();
    }
    try {
        KeyParameter key = new KeyParameter(secretBytes);
        AEADParameters params = new AEADParameters(key, MAC_SIZE_BITS, this.salt);

        this.encryptor = new GCMBlockCipher(new AESFastEngine());
        this.encryptor.init(true, params);

        this.decryptor = new GCMBlockCipher(new AESFastEngine());
        this.decryptor.init(false, params);

    } catch (Exception e) {
        throw new RuntimeException("could not create cipher for AES256", e);
    } finally {
        Arrays.fill(secretBytes, (byte) 0);
    }
}