Example usage for org.bouncycastle.crypto.engines XSalsa20Engine XSalsa20Engine

List of usage examples for org.bouncycastle.crypto.engines XSalsa20Engine XSalsa20Engine

Introduction

In this page you can find the example usage for org.bouncycastle.crypto.engines XSalsa20Engine XSalsa20Engine.

Prototype

XSalsa20Engine

Source Link

Usage

From source file:com.github.capone.protocol.crypto.SymmetricKey.java

License:Open Source License

public byte[] encrypt(Nonce nonce, byte[] message) throws EncryptionException {
    try {/*from  w  w  w.j a v  a 2  s  .com*/
        byte[] subkey = new byte[SUBKEYBYTES];
        byte[] encrypted = new byte[message.length + MACBYTES];

        StreamCipher cipher = new XSalsa20Engine();
        cipher.init(true, new ParametersWithIV(key, nonce.nonce));
        cipher.processBytes(subkey, 0, subkey.length, subkey, 0);
        cipher.processBytes(message, 0, message.length, encrypted, MACBYTES);

        Mac auth = new Poly1305();
        auth.init(new KeyParameter(subkey));
        auth.update(encrypted, MACBYTES, message.length);
        auth.doFinal(encrypted, 0);

        return encrypted;
    } catch (Exception e) {
        throw new EncryptionException();
    }
}

From source file:com.github.capone.protocol.crypto.SymmetricKey.java

License:Open Source License

public byte[] decrypt(Nonce nonce, byte[] encrypted) throws DecryptionException {
    byte[] subkey = new byte[SUBKEYBYTES];
    byte[] mac = new byte[MACBYTES];
    byte[] plain = new byte[encrypted.length - MACBYTES];

    if (encrypted.length < MACBYTES) {
        throw new DecryptionException();
    }//from   w  ww  . j ava  2 s. c  o  m

    StreamCipher cipher = new XSalsa20Engine();
    cipher.init(true, new ParametersWithIV(key, nonce.nonce));
    cipher.processBytes(subkey, 0, subkey.length, subkey, 0);

    Mac auth = new Poly1305();
    auth.init(new KeyParameter(subkey));
    auth.update(encrypted, MACBYTES, encrypted.length - MACBYTES);
    auth.doFinal(mac, 0);

    boolean validMac = true;
    for (int i = 0; i < MACBYTES; i++) {
        validMac &= mac[i] == encrypted[i];
    }
    if (!validMac) {
        throw new DecryptionException();
    }

    cipher.processBytes(encrypted, MACBYTES, encrypted.length - MACBYTES, plain, 0);

    return plain;
}