Example usage for org.bouncycastle.crypto BufferedBlockCipher reset

List of usage examples for org.bouncycastle.crypto BufferedBlockCipher reset

Introduction

In this page you can find the example usage for org.bouncycastle.crypto BufferedBlockCipher reset.

Prototype

public void reset() 

Source Link

Document

Reset the buffer and cipher.

Usage

From source file:cologne.eck.dr.op.crypto.password_hashing.Battcrypt_v0.java

License:Open Source License

@Override
public byte[] hashPassword(int outlen, byte[] in, byte[] salt, int t_cost, int m_cost, Object... varArgs)
        throws DataLengthException, IllegalStateException, InvalidCipherTextException {

    SHA512Digest sha = new SHA512Digest();
    int[] data = new int[DATA_SIZE_INT];
    BlowfishEngine blowfish;//from  w ww .  jav a 2  s  .c  om
    long upgradeLoops = 1;
    long loops;
    int memSize = 4 << m_cost;//= 4 * 2 ** m_cost
    int memMask = memSize - 1;
    int[] mem;

    byte[] hashBuffer = new byte[HASH_LENGTH_BYTE];// holds hash value as bytes
    byte[] dataBuffer = new byte[DATA_SIZE_BYTE];// holds encrypted bytes

    // These are the PHP max. values 
    if (m_cost > 18 || // maximum: 2.147.483.648 bytes
            (t_cost & 0xffff) > 62 || (t_cost >> 16) > 63 || outlen > HASH_LENGTH_BYTE) {
        throw new IllegalArgumentException("invalid parameters");
    }

    int tmp = t_cost >> 16;

    if (tmp != 0) {
        // upgradeLoops = 1, 2, 3, 4, 6, 8, 12, 16, ...
        upgradeLoops = (long) (3 - (tmp & 1)) << ((tmp - 1) >> 1);
    }

    // loops = 2, 3, 4, 6, 8, 12, 16, ...
    tmp = t_cost & 0xffff;
    loops = (long) ((tmp & 1) + 2) << (tmp >> 1);

    // key = SHA512(SHA512(salt) || in)
    byte[] keyBytes = new byte[HASH_LENGTH_BYTE];
    sha.update(salt, 0, salt.length);
    sha.doFinal(keyBytes, 0);
    sha.reset();
    sha.update(keyBytes, 0, HASH_LENGTH_BYTE);
    sha.update(in, 0, in.length);//password
    sha.doFinal(keyBytes, 0);
    sha.reset();
    if (wipePassword == true) {
        Arrays.fill(in, (byte) 0);
    }

    // initialize cipher with 448 bit (56 byte) key: 
    // truncate keyBytes:
    byte[] blowfishKey = new byte[56];
    System.arraycopy(keyBytes, 0, blowfishKey, 0, 56);
    // use zeros as IV
    byte[] iv = new byte[IV_LENGTH_BYTE];
    KeyParameter params = new KeyParameter(blowfishKey);
    Arrays.fill(blowfishKey, (byte) 0);
    ParametersWithIV ivParams = new ParametersWithIV(params, iv);
    blowfish = new BlowfishEngine();
    // CBC, no padding: all vectors are multiples of Blowfish block length
    BufferedBlockCipher cipher = new BufferedBlockCipher(new CBCBlockCipher(blowfish));
    cipher.init(true, ivParams);

    // initialize memory-hard vector:
    mem = new int[DATA_SIZE_INT * memSize];

    for (long u = 0; u < upgradeLoops; u++) {

        // initialize data:
        // data = SHA512(BIG_ENDIAN_64( 0) || key) || ...
        // ... || SHA512(BIG_ENDIAN_64(31) || key)         
        byte[] counterBytesBE = new byte[8]; // holds counter as long to update
        for (int i = 0; i < DATA_SIZE_BYTE / HASH_LENGTH_BYTE; i++) {

            counterBytesBE[7] = (byte) i; // set first byte
            sha.update(counterBytesBE, 0, counterBytesBE.length); // BIG_ENDIAN_64(i)
            sha.update(keyBytes, 0, HASH_LENGTH_BYTE);
            sha.doFinal(hashBuffer, 0);
            sha.reset();
            // hash values allow weak garbage collector attack - 
            // so, avoid new allocations:             
            for (int j = 0; j < HASH_LENGTH_BYTE / 4; j++) {
                data[HASH_LENGTH_INT * i + j] = ((hashBuffer[j * 4 + 3] & 0xFF) << 24)
                        | ((hashBuffer[j * 4 + 2] & 0xFF) << 16) | ((hashBuffer[j * 4 + 1] & 0xFF) << 8)
                        | (hashBuffer[j * 4 + 0] & 0xFF); // little endian order
            }
            Arrays.fill(hashBuffer, (byte) 0);
        }

        // Initialize memory:
        for (int i = 0; i < memSize; i++) {
            // data = blowfish_encrypt_cbc(data)
            // mem = mem || data            
            for (int j = 0; j < DATA_SIZE_INT; j++) {
                dataBuffer[j * 4 + 0] = (byte) (data[j]);// little endian
                dataBuffer[j * 4 + 1] = (byte) (data[j] >>> 8);
                dataBuffer[j * 4 + 2] = (byte) (data[j] >>> 16);
                dataBuffer[j * 4 + 3] = (byte) (data[j] >>> 24);
            }
            int len = cipher.processBytes(dataBuffer, 0, DATA_SIZE_BYTE, dataBuffer, 0);
            cipher.doFinal(dataBuffer, len);
            cipher.reset();

            // get iv for next encryption step:
            // "running CBC": the last block of the
            //  previous call is the IV for the next call
            System.arraycopy(dataBuffer, DATA_SIZE_BYTE - IV_LENGTH_BYTE, iv, 0, IV_LENGTH_BYTE);
            ivParams = new ParametersWithIV(params, iv);
            cipher.init(true, ivParams);

            for (int j = 0; j < DATA_SIZE_INT; j++) {
                data[j] = ((dataBuffer[j * 4 + 3] & 0xFF) << 24) | ((dataBuffer[j * 4 + 2] & 0xFF) << 16)
                        | ((dataBuffer[j * 4 + 1] & 0xFF) << 8) | (dataBuffer[j * 4 + 0] & 0xFF); // little endian order
            }
            System.arraycopy(data, 0, mem, DATA_SIZE_INT * i, DATA_SIZE_INT);
        }

        // encrypt data:
        for (int j = 0; j < DATA_SIZE_INT; j++) {
            dataBuffer[j * 4 + 0] = (byte) (data[j]);// little endian
            dataBuffer[j * 4 + 1] = (byte) (data[j] >>> 8);
            dataBuffer[j * 4 + 2] = (byte) (data[j] >>> 16);
            dataBuffer[j * 4 + 3] = (byte) (data[j] >>> 24);
        }
        int len = cipher.processBytes(dataBuffer, 0, DATA_SIZE_BYTE, dataBuffer, 0);
        cipher.doFinal(dataBuffer, len);
        cipher.reset();
        System.arraycopy(dataBuffer, DATA_SIZE_BYTE - IV_LENGTH_BYTE, iv, 0, IV_LENGTH_BYTE);
        ivParams = new ParametersWithIV(params, iv);
        cipher.init(true, ivParams);

        for (int j = 0; j < DATA_SIZE_INT; j++) {
            data[j] = ((dataBuffer[j * 4 + 3] & 0xFF) << 24) | ((dataBuffer[j * 4 + 2] & 0xFF) << 16)
                    | ((dataBuffer[j * 4 + 1] & 0xFF) << 8) | (dataBuffer[j * 4 + 0] & 0xFF); // little endian order
        }

        // work:
        for (long i = 0; i < loops; i++) {
            for (int j = 0; j < memSize; j++) {
                // in the C++ reference implementation and the paper 
                // this rValue a 64 bit integer, but this makes only a
                // difference for memSize > 0xFFFFFFFF +1, while the
                // recommended maximum for memSize is 2^32
                int rValue = ((((int) data[DATA_SIZE_INT - 1]) << 24) & 0xff000000)
                        | ((((int) data[DATA_SIZE_INT - 1]) << 8) & 0x00ff0000)
                        | ((((int) data[DATA_SIZE_INT - 1]) >>> 8) & 0x0000ff00)
                        | ((((int) data[DATA_SIZE_INT - 1]) >>> 24) & 0x000000ff);
                int index = (int) (DATA_SIZE_INT * (rValue & memMask));

                for (int k = 0; k < DATA_SIZE_INT; k++) {
                    mem[j * DATA_SIZE_INT + k] ^= data[k] ^ mem[index + k];
                }

                // convert to byte: 
                for (int k = 0; k < DATA_SIZE_INT; k++) {
                    dataBuffer[k * 4 + 0] = (byte) (mem[j * DATA_SIZE_INT + k]);
                    dataBuffer[k * 4 + 1] = (byte) (mem[j * DATA_SIZE_INT + k] >>> 8);
                    dataBuffer[k * 4 + 2] = (byte) (mem[j * DATA_SIZE_INT + k] >>> 16);
                    dataBuffer[k * 4 + 3] = (byte) (mem[j * DATA_SIZE_INT + k] >>> 24);
                }
                int len1 = cipher.processBytes(dataBuffer, 0, DATA_SIZE_BYTE, dataBuffer, 0);

                cipher.doFinal(dataBuffer, len1);
                cipher.reset();
                // get iv for next step:
                System.arraycopy(dataBuffer, DATA_SIZE_BYTE - IV_LENGTH_BYTE, iv, 0, IV_LENGTH_BYTE);

                for (int k = 0; k < DATA_SIZE_INT; k++) {
                    mem[j * DATA_SIZE_INT + k] = ((dataBuffer[k * 4 + 3] & 0xFF) << 24)
                            | ((dataBuffer[k * 4 + 2] & 0xFF) << 16) | ((dataBuffer[k * 4 + 1] & 0xFF) << 8)
                            | (dataBuffer[k * 4 + 0] & 0xFF); // little endian order
                }

                ivParams = new ParametersWithIV(params, iv);
                cipher.init(true, ivParams);

                // data ^= mem[j]
                for (int k = 0; k < DATA_SIZE_INT; k++) {
                    data[k] ^= mem[DATA_SIZE_INT * j + k];
                }
            }
        }
        // Finish
        // key = truncate(SHA512(SHA512(data || key)), outlen) || zeros(HASH_LENGTH - outlen)
        // convert to byte: 
        for (int k = 0; k < DATA_SIZE_INT; k++) {
            dataBuffer[k * 4 + 0] = (byte) (data[k]);
            dataBuffer[k * 4 + 1] = (byte) (data[k] >>> 8);
            dataBuffer[k * 4 + 2] = (byte) (data[k] >>> 16);
            dataBuffer[k * 4 + 3] = (byte) (data[k] >>> 24);
        }
        sha.update(dataBuffer, 0, DATA_SIZE_BYTE);
        sha.update(keyBytes, 0, HASH_LENGTH_BYTE);
        sha.doFinal(keyBytes, 0);
        sha.reset();
    }

    sha.update(keyBytes, 0, HASH_LENGTH_BYTE);
    sha.doFinal(keyBytes, 0);
    sha.reset();

    byte[] out = new byte[outlen];

    System.arraycopy(keyBytes, 0, out, 0, out.length);

    // Clean-up:
    Arrays.fill(keyBytes, (byte) 0);
    Arrays.fill(dataBuffer, (byte) 0);
    Arrays.fill(iv, (byte) 0);
    Arrays.fill(data, 0);
    Arrays.fill(mem, (byte) 0);

    // wipe the key from parameters
    Arrays.fill(params.getKey(), (byte) 0);

    // prevent dead code eliminations (compiler optimizations):
    if ((keyBytes[HASH_LENGTH_BYTE - 1] | blowfishKey[blowfishKey.length - 1] | dataBuffer[DATA_SIZE_BYTE - 1]
            | hashBuffer[HASH_LENGTH_BYTE - 1] | data[DATA_SIZE_INT - 1] | iv[IV_LENGTH_BYTE - 1]
            | mem[mem.length - 1] | params.getKey()[params.getKey().length - 1]) != 0) {
        System.err.print("zeroization failed!");
    }
    if ((wipePassword == true) && (in[in.length - 1] != 0)) {
        System.err.print("zeroization failed!");
    }
    return out;
}

From source file:dorkbox.util.crypto.CryptoAES.java

License:Apache License

/**
 * <b>CONVENIENCE METHOD ONLY - DO NOT USE UNLESS YOU HAVE TO</b>
 * <p>//from ww  w .  ja  va2s .co  m
 * Use GCM instead, as it's an authenticated cipher (and "regular" AES is not). This prevents tampering with the blocks of encrypted
 * data.
 * <p>
 * AES encrypts data with a specified key.
 *
 * @param aesIV
 *                 must be a nonce (unique value) !!
 * @param logger
 *                 may be null, if no log output is necessary
 *
 * @return empty byte[] if error
 */
@Deprecated
public static byte[] encrypt(BufferedBlockCipher aesEngine, byte[] aesKey, byte[] aesIV, byte[] data,
        Logger logger) {
    int length = data.length;

    CipherParameters aesIVAndKey = new ParametersWithIV(new KeyParameter(aesKey), aesIV);
    aesEngine.reset();
    aesEngine.init(true, aesIVAndKey);

    int minSize = aesEngine.getOutputSize(length);
    byte[] outBuf = new byte[minSize];

    int actualLength = aesEngine.processBytes(data, 0, length, outBuf, 0);

    try {
        actualLength += aesEngine.doFinal(outBuf, actualLength);
    } catch (Exception e) {
        if (logger != null) {
            logger.error("Unable to perform AES cipher.", e);
        }
        return new byte[0];
    }

    if (outBuf.length == actualLength) {
        return outBuf;
    } else {
        byte[] result = new byte[actualLength];
        System.arraycopy(outBuf, 0, result, 0, result.length);
        return result;
    }
}

From source file:dorkbox.util.crypto.CryptoAES.java

License:Apache License

/**
 * <b>CONVENIENCE METHOD ONLY - DO NOT USE UNLESS YOU HAVE TO</b>
 * <p>/*from w  w  w .  jav  a  2  s . c  o m*/
 * Use GCM instead, as it's an authenticated cipher (and "regular" AES is not). This prevents tampering with the blocks of encrypted
 * data.
 * <p>
 * AES encrypt from one stream to another.
 *
 * @param aesIV
 *                 must be a nonce (unique value) !!
 * @param logger
 *                 may be null, if no log output is necessary
 *
 * @return true if successful
 */
@Deprecated
public static boolean encryptStream(BufferedBlockCipher aesEngine, byte[] aesKey, byte[] aesIV, InputStream in,
        OutputStream out, Logger logger) {
    byte[] buf = new byte[ivSize];
    byte[] outbuf = new byte[512];

    CipherParameters aesIVAndKey = new ParametersWithIV(new KeyParameter(aesKey), aesIV);
    aesEngine.reset();
    aesEngine.init(true, aesIVAndKey);

    try {
        int bytesRead;
        int bytesProcessed;

        while ((bytesRead = in.read(buf)) >= 0) {
            bytesProcessed = aesEngine.processBytes(buf, 0, bytesRead, outbuf, 0);
            out.write(outbuf, 0, bytesProcessed);
        }

        bytesProcessed = aesEngine.doFinal(outbuf, 0);

        out.write(outbuf, 0, bytesProcessed);
        out.flush();
    } catch (Exception e) {
        if (logger != null) {
            logger.error("Unable to perform AES cipher.", e);
        }
        return false;
    }

    return true;
}

From source file:dorkbox.util.crypto.CryptoAES.java

License:Apache License

/**
 * <b>CONVENIENCE METHOD ONLY - DO NOT USE UNLESS YOU HAVE TO</b>
 * <p>//ww w  . j  a  va 2  s.  co  m
 * Use GCM instead, as it's an authenticated cipher (and "regular" AES is not). This prevents tampering with the blocks of encrypted
 * data.
 * <p>
 * AES decrypt (if we already know the aes IV -- and it's NOT included in the data)
 *
 * @param aesIV
 *                 must be a nonce (unique value) !!
 * @param logger
 *                 may be null, if no log output is necessary
 *
 * @return empty byte[] if error
 */
@Deprecated
public static byte[] decrypt(BufferedBlockCipher aesEngine, byte[] aesKey, byte[] aesIV, byte[] data,
        Logger logger) {

    int length = data.length;

    CipherParameters aesIVAndKey = new ParametersWithIV(new KeyParameter(aesKey), aesIV);
    aesEngine.reset();
    aesEngine.init(false, aesIVAndKey);

    int minSize = aesEngine.getOutputSize(length);
    byte[] outBuf = new byte[minSize];

    int actualLength = aesEngine.processBytes(data, 0, length, outBuf, 0);

    try {
        actualLength += aesEngine.doFinal(outBuf, actualLength);
    } catch (Exception e) {
        if (logger != null) {
            logger.error("Unable to perform AES cipher.", e);
        }
        return new byte[0];
    }

    if (outBuf.length == actualLength) {
        return outBuf;
    } else {
        byte[] result = new byte[actualLength];
        System.arraycopy(outBuf, 0, result, 0, result.length);
        return result;
    }
}

From source file:dorkbox.util.crypto.CryptoAES.java

License:Apache License

/**
 * <b>CONVENIENCE METHOD ONLY - DO NOT USE UNLESS YOU HAVE TO</b>
 * <p>/* w w  w  .j  a v a 2  s .c o  m*/
 * Use GCM instead, as it's an authenticated cipher (and "regular" AES is not). This prevents tampering with the blocks of encrypted
 * data.
 * <p>
 * AES decrypt from one stream to another.
 *
 * @param aesIV
 *                 must be a nonce (unique value) !!
 * @param logger
 *                 may be null, if no log output is necessary
 *
 * @return true if successful
 */
@Deprecated
public static boolean decryptStream(BufferedBlockCipher aesEngine, byte[] aesKey, byte[] aesIV, InputStream in,
        OutputStream out, Logger logger) {
    byte[] buf = new byte[ivSize];
    byte[] outbuf = new byte[512];

    CipherParameters aesIVAndKey = new ParametersWithIV(new KeyParameter(aesKey), aesIV);
    aesEngine.reset();
    aesEngine.init(false, aesIVAndKey);

    try {
        int bytesRead;
        int bytesProcessed;

        while ((bytesRead = in.read(buf)) >= 0) {
            bytesProcessed = aesEngine.processBytes(buf, 0, bytesRead, outbuf, 0);
            out.write(outbuf, 0, bytesProcessed);
        }

        bytesProcessed = aesEngine.doFinal(outbuf, 0);

        out.write(outbuf, 0, bytesProcessed);
        out.flush();
    } catch (Exception e) {
        if (logger != null) {
            logger.error("Unable to perform AES cipher.", e);
        }
        return false;
    }

    return true;
}

From source file:jd.plugins.hoster.CrunchyRollCom.java

License:Open Source License

/**
 * Decrypt and convert the downloaded file from CrunchyRoll's own encrypted xml format into its .ass equivalent.
 *
 * @param downloadLink/*w  ww  .  ja  v a2s . c  o m*/
 *            The DownloadLink to convert to .ass
 */
private void convertSubs(final DownloadLink downloadLink) throws PluginException {
    downloadLink.getLinkStatus().setStatusText("Decrypting subtitles...");
    try {

        final File source = new File(downloadLink.getFileOutput());
        final StringBuilder xmltext = new StringBuilder();
        final String lineseparator = System.getProperty("line.separator");

        Scanner in = null;
        try {
            in = new Scanner(new FileReader(source));
            while (in.hasNext()) {
                xmltext.append(in.nextLine() + lineseparator);
            }
        } catch (Exception e) {
        } finally {
            in.close();
        }
        if (xmltext.toString().contains("<error>No Permission</error>")) {
            throw new PluginException(LinkStatus.ERROR_FILE_NOT_FOUND);
        }

        // Create the XML Parser
        final DocumentBuilderFactory xmlDocBuilderFactory = DocumentBuilderFactory.newInstance();
        final DocumentBuilder xmlDocBuilder = xmlDocBuilderFactory.newDocumentBuilder();
        final Document xml = xmlDocBuilder.parse(new File(downloadLink.getFileOutput()));
        xml.getDocumentElement().normalize();

        // Get the subtitle information
        final Element xmlSub = (Element) xml.getElementsByTagName("subtitle").item(0);

        final Node error = xmlSub.getAttributeNode("error");
        final Node xmlId = xmlSub.getAttributeNode("id");
        final Node xmlIv = xmlSub.getElementsByTagName("iv").item(0);
        final Node xmlData = xmlSub.getElementsByTagName("data").item(0);

        final int subId = Integer.parseInt(xmlId.getNodeValue());
        final String subIv = xmlIv.getTextContent();
        final String subData = xmlData.getTextContent();

        // Generate the AES parameters
        final byte[] key = this.subsGenerateKey(subId, 32);
        final byte[] ivData = DatatypeConverter.parseBase64Binary(subIv);
        final byte[] encData = DatatypeConverter.parseBase64Binary(subData);
        byte[] decrypted = null;
        try {
            final KeyParameter keyParam = new KeyParameter(key);
            final CipherParameters cipherParams = new ParametersWithIV(keyParam, ivData);

            // Prepare the cipher (AES, CBC, no padding)
            final BufferedBlockCipher cipher = new BufferedBlockCipher(new CBCBlockCipher(new AESEngine()));
            cipher.reset();
            cipher.init(false, cipherParams);

            // Decrypt the subtitles
            decrypted = new byte[cipher.getOutputSize(encData.length)];
            final int decLength = cipher.processBytes(encData, 0, encData.length, decrypted, 0);
            cipher.doFinal(decrypted, decLength);
        } catch (final Throwable e) {
            logger.severe(e.getMessage());
            throw new PluginException(LinkStatus.ERROR_PLUGIN_DEFECT, "Error decrypting subtitles!");
        }
        // Create the XML Parser (and zlib decompress using InflaterInputStream)
        final DocumentBuilderFactory subsDocBuilderFactory = DocumentBuilderFactory.newInstance();
        final DocumentBuilder subsDocBuilder = subsDocBuilderFactory.newDocumentBuilder();
        final Document subs = subsDocBuilder
                .parse(new InflaterInputStream(new ByteArrayInputStream(decrypted)));
        subs.getDocumentElement().normalize();

        // Get the header
        final Element subHeaderElem = (Element) subs.getElementsByTagName("subtitle_script").item(0);
        final String subHeaderTitle = subHeaderElem.getAttributeNode("title").getNodeValue();
        final String subHeaderWrap = subHeaderElem.getAttributeNode("wrap_style").getNodeValue();
        final String subHeaderResX = subHeaderElem.getAttributeNode("play_res_x").getNodeValue();
        final String subHeaderResY = subHeaderElem.getAttributeNode("play_res_y").getNodeValue();

        final String subHeader = "[Script Info]\nTitle: " + subHeaderTitle + "\nScriptType: v4.00+\nWrapStyle: "
                + subHeaderWrap + "\nPlayResX: " + subHeaderResX + "\nPlayResY: " + subHeaderResY + "\n";

        // Get the styles
        String subStyles = "[V4 Styles]\nFormat: Name, Fontname, Fontsize, PrimaryColour, SecondaryColour, OutlineColour, BackColour, Bold, Italic, Underline, StrikeOut, ScaleX, ScaleY, Spacing, Angle, BorderStyle, Outline, Shadow, Alignment, MarginL, MarginR, MarginV, Encoding\n";
        final NodeList subStylesNodes = subs.getElementsByTagName("style");

        for (int i = 0; i < subStylesNodes.getLength(); i++) {
            final Element subStylesElem = (Element) subStylesNodes.item(i);
            final String subStylesName = subStylesElem.getAttributeNode("name").getNodeValue();
            final String subStylesFontName = subStylesElem.getAttributeNode("font_name").getNodeValue();
            final String subStylesFontSize = subStylesElem.getAttributeNode("font_size").getNodeValue();
            final String subStylesPriColor = subStylesElem.getAttributeNode("primary_colour").getNodeValue();
            final String subStylesSecColor = subStylesElem.getAttributeNode("secondary_colour").getNodeValue();
            final String subStylesOutColor = subStylesElem.getAttributeNode("outline_colour").getNodeValue();
            final String subStylesBacColor = subStylesElem.getAttributeNode("back_colour").getNodeValue();
            final String subStylesUnderline = subStylesElem.getAttributeNode("underline").getNodeValue();
            final String subStylesStrikeout = subStylesElem.getAttributeNode("strikeout").getNodeValue();
            final String subStylesAlignment = subStylesElem.getAttributeNode("alignment").getNodeValue();
            final String subStylesSpacing = subStylesElem.getAttributeNode("spacing").getNodeValue();
            final String subStylesItalic = subStylesElem.getAttributeNode("italic").getNodeValue();
            String subStylesScaleX = subStylesElem.getAttributeNode("scale_x").getNodeValue();
            String subStylesScaleY = subStylesElem.getAttributeNode("scale_y").getNodeValue();
            final String subStylesBorder = subStylesElem.getAttributeNode("border_style").getNodeValue();
            final String subStylesShadow = subStylesElem.getAttributeNode("shadow").getNodeValue();
            final String subStylesBold = subStylesElem.getAttributeNode("bold").getNodeValue();
            final String subStylesAngle = subStylesElem.getAttributeNode("angle").getNodeValue();
            final String subStylesOutline = subStylesElem.getAttributeNode("outline").getNodeValue();
            final String subStylesMarginL = subStylesElem.getAttributeNode("margin_l").getNodeValue();
            final String subStylesMarginR = subStylesElem.getAttributeNode("margin_r").getNodeValue();
            final String subStylesMarginV = subStylesElem.getAttributeNode("margin_v").getNodeValue();
            final String subStylesEncoding = subStylesElem.getAttributeNode("encoding").getNodeValue();

            // Fix the odd case where the subtitles are scaled to nothing
            if (subStylesScaleX.equals("0")) {
                subStylesScaleX = "100";
            }
            if (subStylesScaleY.equals("0")) {
                subStylesScaleY = "100";
            }

            subStyles += "Style: " + subStylesName + ", " + subStylesFontName + ", " + subStylesFontSize + ", "
                    + subStylesPriColor + ", " + subStylesSecColor + ", " + subStylesOutColor + ", "
                    + subStylesBacColor + ", " + subStylesBold + ", " + subStylesItalic + ", "
                    + subStylesUnderline + ", " + subStylesStrikeout + ", " + subStylesScaleX + ", "
                    + subStylesScaleY + ", " + subStylesSpacing + ", " + subStylesAngle + ", " + subStylesBorder
                    + ", " + subStylesOutline + ", " + subStylesShadow + ", " + subStylesAlignment + ", "
                    + subStylesMarginL + ", " + subStylesMarginR + ", " + subStylesMarginV + ", "
                    + subStylesEncoding + "\n";
        }

        // Get the elements
        String subEvents = "[Events]\nFormat: Layer, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text\n";
        final NodeList subEventsNodes = subs.getElementsByTagName("event");

        for (int i = 0; i < subEventsNodes.getLength(); i++) {
            final Element subEventsElem = (Element) subEventsNodes.item(i);
            final String subEventsStart = subEventsElem.getAttributeNode("start").getNodeValue();
            final String subEventsEnd = subEventsElem.getAttributeNode("end").getNodeValue();
            final String subEventsStyle = subEventsElem.getAttributeNode("style").getNodeValue();
            final String subEventsName = subEventsElem.getAttributeNode("name").getNodeValue();
            final String subEventsMarginL = subEventsElem.getAttributeNode("margin_l").getNodeValue();
            final String subEventsMarginR = subEventsElem.getAttributeNode("margin_r").getNodeValue();
            final String subEventsMarginV = subEventsElem.getAttributeNode("margin_v").getNodeValue();
            final String subEventsEffect = subEventsElem.getAttributeNode("effect").getNodeValue();
            final String subEventsText = subEventsElem.getAttributeNode("text").getNodeValue();

            subEvents += "Dialogue: 0," + subEventsStart + "," + subEventsEnd + "," + subEventsStyle + ","
                    + subEventsName + "," + subEventsMarginL + "," + subEventsMarginR + "," + subEventsMarginV
                    + "," + subEventsEffect + "," + subEventsText + "\n";
        }

        // Output to the original file
        final FileWriter subOutFile = new FileWriter(downloadLink.getFileOutput());
        final BufferedWriter subOut = new BufferedWriter(subOutFile);

        try {
            subOut.write(subHeader + "\n");
            subOut.write(subStyles + "\n");
            subOut.write(subEvents);
        } catch (final Throwable e) {
            subOut.close();
            subOutFile.close();
            throw new PluginException(LinkStatus.ERROR_DOWNLOAD_FAILED, "Error writing decrypted subtitles!");
        }

        subOut.close();
        subOutFile.close();
        downloadLink.getLinkStatus().setStatusText(
                JDL.L("plugins.hoster.crunchyrollcom.decryptedsubtitles", "Subtitles decrypted"));
    } catch (final SAXException e) {
        throw new PluginException(LinkStatus.ERROR_PLUGIN_DEFECT,
                "Error decrypting subtitles: Invalid XML file!");
    } catch (final DOMException e) {
        throw new PluginException(LinkStatus.ERROR_PLUGIN_DEFECT,
                "Error decrypting subtitles: XML file changed!");
    } catch (final PluginException e) {
        throw e;
    } catch (final Throwable e) {
        e.printStackTrace();
        throw new PluginException(LinkStatus.ERROR_PLUGIN_DEFECT, "Error decrypting subtitles!");
    }
}

From source file:labr_client.Public.encryption.java

License:Open Source License

public static String encode(String dec) throws GeneralSecurityException {
    // Generate 128 bits of random data for use as the IV. It is important to use a different IV for
    // each encrypted block of text, to ensure that the same string encrypted by two different people
    // does not give the same encrypted text string - that leads to obvious attack possibilities. Note
    // however that the IV does not need to be kept secret; it is a little bit like a 'salt' for a
    // password, which improves security even when the salt is stored in plaintext in a database or
    // prefixed to the encrypted file.
    byte[] ivData = new byte[AES_NIVBITS / 8]; //Hoe groot is deze array -> 128/8 = 16
    Random r = new Random(); // Note: no  seed here, ie these values are truly random
    r.nextBytes(ivData);/*from   ww  w .  ja v a2  s.  c  o m*/
    ////        try {
    ////            System.out.println(new String(ivData, "UTF-8")); // for UTF-8 encoding
    ////        } catch (UnsupportedEncodingException ex) {
    ////            Logger.getLogger(encryption.class.getName()).log(Level.SEVERE, null, ex);
    ////        }
    //        ivData[0] = Byte.valueOf("100");
    //        ivData[1] = Byte.valueOf("1");
    //        ivData[2] = Byte.valueOf("15");
    //        ivData[3] = Byte.valueOf("50");
    //        ivData[4] = Byte.valueOf("70");
    //        ivData[5] = Byte.valueOf("80");
    //        ivData[6] = Byte.valueOf("5");
    //        ivData[7] = Byte.valueOf("45");
    //        ivData[8] = Byte.valueOf("100");
    //        ivData[9] = Byte.valueOf("1");
    //        ivData[10] = Byte.valueOf("15");
    //        ivData[11] = Byte.valueOf("50");
    //        ivData[12] = Byte.valueOf("70");
    //        ivData[13] = Byte.valueOf("80");
    //        ivData[14] = Byte.valueOf("5");
    //        ivData[15] = Byte.valueOf("45");
    // Select encryption algorithm and padding : AES with CBC and PCKS#7

    //byte[] ivData = new sun.misc.BASE64Decoder().decodeBuffer(salt);
    BlockCipherPadding padding = new PKCS7Padding();
    BufferedBlockCipher cipher = new PaddedBufferedBlockCipher(new CBCBlockCipher(new AESEngine()), padding);

    // Encrypt the input string using key + iv
    KeyParameter keyParam = getAesKey();
    CipherParameters params = new ParametersWithIV(keyParam, ivData);

    cipher.reset();
    cipher.init(true, params); // first param = encode/decode

    byte[] bytesDec = dec.getBytes(UTF8); // data to decode

    byte[] bytesEnc;
    try {
        int buflen = cipher.getOutputSize(bytesDec.length);
        bytesEnc = new byte[buflen];
        int nBytesEnc = cipher.processBytes(bytesDec, 0, bytesDec.length, bytesEnc, 0);
        nBytesEnc += cipher.doFinal(bytesEnc, nBytesEnc);

        if (nBytesEnc != bytesEnc.length) {
            throw new IllegalStateException("Unexpected behaviour : getOutputSize value incorrect");
        }
    } catch (InvalidCipherTextException | RuntimeException e) {
        throw new GeneralSecurityException("encryption failed");
    }

    // Return a base-64-encoded string containing IV + encrypted input string
    byte[] bytesAll = new byte[ivData.length + bytesEnc.length];
    arraycopy(ivData, 0, bytesAll, 0, ivData.length);
    arraycopy(bytesEnc, 0, bytesAll, ivData.length, bytesEnc.length);
    out.println(new String(encodeBase64(bytesAll), UTF8));
    return new String(encodeBase64(bytesAll), UTF8);
}

From source file:labr_client.Public.encryption.java

License:Open Source License

/**
 * Decode a string which has first been encrypted with AES, and then
 * base64-encoded.//from   w w w  . jav  a  2 s  .  co m
 */
public static String decodeBase64Aes(String enc) throws GeneralSecurityException {
    byte[] bytesEnc = decodeBase64(enc.getBytes(UTF8));

    // Extract the IV, which is stored in the next N bytes
    int nIvBytes = AES_NIVBITS / 8;
    byte[] ivBytes = new byte[nIvBytes];
    arraycopy(bytesEnc, 0, ivBytes, 0, nIvBytes);

    // Select encryption algorithm and padding : AES with CBC and PCKS#7.
    // Note that the "encryption strength" (128 or 256 bit key) is set by the KeyParameter object.
    KeyParameter keyParam = getAesKey();
    CipherParameters params = new ParametersWithIV(keyParam, ivBytes);
    BlockCipherPadding padding = new PKCS7Padding();
    BufferedBlockCipher cipher = new PaddedBufferedBlockCipher(new CBCBlockCipher(new AESEngine()), padding);

    // Decrypt all bytes that follow the IV
    cipher.reset();
    cipher.init(false, params); // first param = encode/decode

    byte[] bytesDec;

    try {
        int buflen = cipher.getOutputSize(bytesEnc.length - nIvBytes);
        byte[] workingBuffer = new byte[buflen];
        int len = cipher.processBytes(bytesEnc, nIvBytes, bytesEnc.length - nIvBytes, workingBuffer, 0);
        len += cipher.doFinal(workingBuffer, len);

        // Note that getOutputSize returns a number which includes space for "padding" bytes to be stored in.
        // However we don't want these padding bytes; the "len" variable contains the length of the *real* data
        // (which is always less than the return value of getOutputSize.
        bytesDec = new byte[len];
        arraycopy(workingBuffer, 0, bytesDec, 0, len);
    } catch (InvalidCipherTextException e) {
        throw new GeneralSecurityException("decode failed");
    } catch (RuntimeException e) {
        throw new GeneralSecurityException("encryption failed");
    }

    // And convert the result to a string
    out.println(new String(bytesDec, UTF8));
    return new String(bytesDec, UTF8);
}

From source file:net.nharyes.secrete.curve.Curve25519PrivateKey.java

License:Open Source License

public static Curve25519PrivateKey deserialize(InputStream in, char[] password) throws IOException {

    try {//from  w  w  w. j a  v  a2s.co  m

        // check magic number
        byte[] mn = new byte[MagicNumbers.PRIVATE_KEY.length];
        IOUtils.readFully(in, mn, 0, mn.length);
        if (!Arrays.areEqual(mn, MagicNumbers.PRIVATE_KEY))
            throw new IllegalArgumentException("Wrong key file format");

        // read initial vector
        byte[] iv = new byte[16];
        IOUtils.readFully(in, iv, 0, iv.length);

        // read salt
        byte[] salt = new byte[64];
        IOUtils.readFully(in, salt, 0, salt.length);

        // 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(false, params);

        // decrypt key
        CipherInputStream cin = new CipherInputStream(in, cipher);
        byte[] key = new byte[Curve25519.KEY_SIZE];
        IOUtils.readFully(cin, key, 0, key.length);

        // return key instance
        return new Curve25519PrivateKey(key);

    } catch (UnsupportedEncodingException ex) {

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

From source file:net.nharyes.secrete.curve.Curve25519PrivateKey.java

License:Open Source License

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

    try {/*from  w  ww.ja va2 s . com*/

        // 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);
    }
}