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

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

Introduction

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

Prototype

public AESEngine() 

Source Link

Document

default constructor - 128 bit block size.

Usage

From source file:freemail.OutboundContact.java

License:Open Source License

/**
 * Set up an outbound contact. Fetch the mailsite, generate a new SSK keypair and post an RTS message to the appropriate KSK.
 * Will block for mailsite retrieval and RTS insertion
 *
 * @return true for success/*w w  w. ja  va 2  s .  c  o m*/
 */
private boolean init() throws ConnectionTerminatedException, InterruptedException {
    Logger.normal(this, "Initialising Outbound Contact " + address.toString());

    // try to fetch get all necessary info. will fetch mailsite / generate new keys if necessary
    String initialslot = this.getCurrentLowestSlot();
    SSKKeyPair commssk = this.getCommKeyPair();
    if (commssk == null)
        return false;
    SSKKeyPair ackssk = this.getAckKeyPair();
    RSAKeyParameters their_pub_key = this.getPubKey();
    if (their_pub_key == null)
        return false;
    String rtsksk = this.getRtsKsk();
    if (rtsksk == null)
        return false;

    StringBuffer rtsmessage = new StringBuffer();

    // the public part of the SSK keypair we generated
    rtsmessage.append("commssk=" + commssk.pubkey + "\r\n");

    rtsmessage.append("ackssk=" + ackssk.privkey + "\r\n");

    rtsmessage.append("initialslot=" + initialslot + "\r\n");

    rtsmessage.append("messagetype=rts\r\n");

    // must include who this RTS is to, otherwise we're vulnerable to surreptitious forwarding
    rtsmessage.append("to=" + this.address.getSubDomain() + "\r\n");

    // get our mailsite URI
    String our_mailsite_uri = account.getProps().get("mailsite.pubkey");

    rtsmessage.append("mailsite=" + our_mailsite_uri + "\r\n");

    rtsmessage.append("\r\n");
    //FreemailLogger.normal(this,rtsmessage.toString());

    // sign the message
    SHA256Digest sha256 = new SHA256Digest();
    sha256.update(rtsmessage.toString().getBytes(), 0, rtsmessage.toString().getBytes().length);
    byte[] hash = new byte[sha256.getDigestSize()];
    sha256.doFinal(hash, 0);

    RSAKeyParameters our_priv_key = AccountManager.getPrivateKey(account.getProps());

    AsymmetricBlockCipher sigcipher = new RSAEngine();
    sigcipher.init(true, our_priv_key);
    byte[] sig = null;
    try {
        sig = sigcipher.processBlock(hash, 0, hash.length);
    } catch (InvalidCipherTextException icte) {
        Logger.error(this, "Failed to RSA encrypt hash: " + icte.getMessage());
        icte.printStackTrace();
        return false;
    }

    ByteArrayOutputStream bos = new ByteArrayOutputStream();

    try {
        bos.write(rtsmessage.toString().getBytes());
        bos.write(sig);
    } catch (IOException ioe) {
        ioe.printStackTrace();
        return false;
    }

    // make up a symmetric key
    PaddedBufferedBlockCipher aescipher = new PaddedBufferedBlockCipher(new CBCBlockCipher(new AESEngine()),
            new PKCS7Padding());

    // quick paranoia check!
    if (aescipher.getBlockSize() != AES_BLOCK_LENGTH) {
        // bouncycastle must have changed their implementation, so 
        // we're in trouble
        Logger.normal(this,
                "Incompatible block size change detected in cryptography API! Are you using a newer version of the bouncycastle libraries? If so, we suggest you downgrade for now, or check for a newer version of Freemail.");
        return false;
    }

    byte[] aes_iv_and_key = this.getAESParams();

    // now encrypt that with our recipient's public key
    AsymmetricBlockCipher enccipher = new RSAEngine();
    enccipher.init(true, their_pub_key);
    byte[] encrypted_aes_params = null;
    try {
        encrypted_aes_params = enccipher.processBlock(aes_iv_and_key, 0, aes_iv_and_key.length);
    } catch (InvalidCipherTextException icte) {
        Logger.error(this,
                "Failed to perform asymmertic encryption on RTS symmetric key: " + icte.getMessage());
        icte.printStackTrace();
        return false;
    }

    // now encrypt the message with the symmetric key
    KeyParameter kp = new KeyParameter(aes_iv_and_key, aescipher.getBlockSize(), AES_KEY_LENGTH);
    ParametersWithIV kpiv = new ParametersWithIV(kp, aes_iv_and_key, 0, aescipher.getBlockSize());
    aescipher.init(true, kpiv);

    byte[] encmsg = new byte[aescipher.getOutputSize(bos.toByteArray().length) + encrypted_aes_params.length];
    System.arraycopy(encrypted_aes_params, 0, encmsg, 0, encrypted_aes_params.length);
    int offset = encrypted_aes_params.length;
    offset += aescipher.processBytes(bos.toByteArray(), 0, bos.toByteArray().length, encmsg, offset);

    try {
        aescipher.doFinal(encmsg, offset);
    } catch (InvalidCipherTextException icte) {
        Logger.error(this, "Failed to perform symmertic encryption on RTS data: " + icte.getMessage());
        icte.printStackTrace();
        return false;
    }

    // insert it!
    HighLevelFCPClient cli = new HighLevelFCPClient();
    if (cli.slotInsert(encmsg, "KSK@" + rtsksk + "-" + DateStringFactory.getKeyString(), 1, "") < 0) {
        // safe to copy the message into the contact outbox though
        return false;
    }

    // remember the fact that we have successfully inserted the rts
    this.contactfile.put("status", "rts-sent");
    // and remember when we sent it!
    this.contactfile.put("rts-sent-at", Long.toString(System.currentTimeMillis()));
    // and since that's been successfully inserted to that key, we can
    // throw away the symmetric key
    this.contactfile.remove("aesparams");

    Logger.normal(this, "Succesfully initialised Outbound Contact");

    return true;
}

From source file:freemail.RTSFetcher.java

License:Open Source License

private byte[] decrypt_rts(File rtsmessage) throws IOException, InvalidCipherTextException {
    // initialise our ciphers
    RSAKeyParameters ourprivkey = AccountManager.getPrivateKey(account.getProps());
    AsymmetricBlockCipher deccipher = new RSAEngine();
    deccipher.init(false, ourprivkey);/*from  w  w w  .  j  av a  2  s.c o m*/

    PaddedBufferedBlockCipher aescipher = new PaddedBufferedBlockCipher(new CBCBlockCipher(new AESEngine()),
            new PKCS7Padding());

    // first n bytes will be an encrypted RSA block containting the
    // AES IV and Key. Read that.
    byte[] encrypted_params = new byte[deccipher.getInputBlockSize()];
    FileInputStream fis = new FileInputStream(rtsmessage);
    int read = 0;

    while (read < encrypted_params.length) {
        read += fis.read(encrypted_params, read, encrypted_params.length - read);
        if (read < 0)
            break;
    }

    if (read < 0) {
        throw new InvalidCipherTextException("RTS Message too short");
    }

    byte[] aes_iv_and_key = deccipher.processBlock(encrypted_params, 0, encrypted_params.length);

    KeyParameter kp = new KeyParameter(aes_iv_and_key, aescipher.getBlockSize(),
            aes_iv_and_key.length - aescipher.getBlockSize());
    ParametersWithIV kpiv = new ParametersWithIV(kp, aes_iv_and_key, 0, aescipher.getBlockSize());
    try {
        aescipher.init(false, kpiv);
    } catch (IllegalArgumentException iae) {
        throw new InvalidCipherTextException(iae.getMessage());
    }

    byte[] plaintext = new byte[aescipher.getOutputSize((int) rtsmessage.length() - read)];

    int ptbytes = 0;
    while (read < rtsmessage.length()) {
        byte[] buf = new byte[(int) rtsmessage.length() - read];

        int thisread = fis.read(buf, 0, (int) rtsmessage.length() - read);
        ptbytes += aescipher.processBytes(buf, 0, thisread, plaintext, ptbytes);
        read += thisread;
    }

    fis.close();

    try {
        aescipher.doFinal(plaintext, ptbytes);
    } catch (DataLengthException dle) {
        throw new InvalidCipherTextException(dle.getMessage());
    }

    return plaintext;
}

From source file:heat.crypto.Crypto.java

License:Open Source License

public static byte[] aesEncrypt(byte[] plaintext, byte[] myPrivateKey, byte[] theirPublicKey, byte[] nonce) {
    try {/*from  w  w w. ja  v a 2s  .  com*/
        byte[] dhSharedSecret = new byte[32];
        Curve25519.curve(dhSharedSecret, myPrivateKey, theirPublicKey);
        for (int i = 0; i < 32; i++) {
            dhSharedSecret[i] ^= nonce[i];
        }
        byte[] key = sha256().digest(dhSharedSecret);
        byte[] iv = new byte[16];
        secureRandom.get().nextBytes(iv);
        PaddedBufferedBlockCipher aes = new PaddedBufferedBlockCipher(new CBCBlockCipher(new AESEngine()));
        CipherParameters ivAndKey = new ParametersWithIV(new KeyParameter(key), iv);
        aes.init(true, ivAndKey);
        byte[] output = new byte[aes.getOutputSize(plaintext.length)];
        int ciphertextLength = aes.processBytes(plaintext, 0, plaintext.length, output, 0);
        ciphertextLength += aes.doFinal(output, ciphertextLength);
        byte[] result = new byte[iv.length + ciphertextLength];
        System.arraycopy(iv, 0, result, 0, iv.length);
        System.arraycopy(output, 0, result, iv.length, ciphertextLength);
        return result;
    } catch (InvalidCipherTextException e) {
        throw new RuntimeException(e.getMessage(), e);
    }
}

From source file:heat.crypto.Crypto.java

License:Open Source License

public static byte[] aesDecrypt(byte[] ivCiphertext, byte[] myPrivateKey, byte[] theirPublicKey, byte[] nonce) {
    try {//from   ww w.  j  av  a 2 s.co  m
        if (ivCiphertext.length < 16 || ivCiphertext.length % 16 != 0) {
            throw new InvalidCipherTextException("invalid ciphertext");
        }
        byte[] iv = Arrays.copyOfRange(ivCiphertext, 0, 16);
        byte[] ciphertext = Arrays.copyOfRange(ivCiphertext, 16, ivCiphertext.length);
        byte[] dhSharedSecret = new byte[32];
        Curve25519.curve(dhSharedSecret, myPrivateKey, theirPublicKey);
        for (int i = 0; i < 32; i++) {
            dhSharedSecret[i] ^= nonce[i];
        }
        byte[] key = sha256().digest(dhSharedSecret);
        PaddedBufferedBlockCipher aes = new PaddedBufferedBlockCipher(new CBCBlockCipher(new AESEngine()));
        CipherParameters ivAndKey = new ParametersWithIV(new KeyParameter(key), iv);
        aes.init(false, ivAndKey);
        byte[] output = new byte[aes.getOutputSize(ciphertext.length)];
        int plaintextLength = aes.processBytes(ciphertext, 0, ciphertext.length, output, 0);
        plaintextLength += aes.doFinal(output, plaintextLength);
        byte[] result = new byte[plaintextLength];
        System.arraycopy(output, 0, result, 0, result.length);
        return result;
    } catch (InvalidCipherTextException e) {
        throw new RuntimeException(e.getMessage(), e);
    }
}

From source file:io.warp10.script.lora.LORAENC.java

License:Apache License

@Override
public Object apply(WarpScriptStack stack) throws WarpScriptException {

    Object top = stack.pop();//  ww w  .j a va 2 s  .c  om

    if (!(top instanceof String)) {
        throw new WarpScriptException(getName() + " expects a 128 bits hex encoded key on top of the stack.");
    }

    String keystr = top.toString();

    if (keystr.length() != 32) {
        throw new WarpScriptException(getName() + " expects a 128 bits hex encoded key on top of the stack.");
    }

    top = stack.pop();

    if (!(top instanceof Long)) {
        throw new WarpScriptException(getName() + " expects a sequence counter below the key.");
    }

    int sequenceCounter = ((Number) top).intValue();

    top = stack.pop();

    if (!(top instanceof Long)) {
        throw new WarpScriptException(
                getName() + " expects a direction (0 uplink or 1 downlink) below the sequence counter.");
    }

    int dir = ((Number) top).intValue();

    if (0 != dir && 1 != dir) {
        throw new WarpScriptException(
                getName() + " expects a direction (0 uplink or 1 downlink) below the sequence counter.");
    }

    top = stack.pop();

    if (!(top instanceof Long)) {
        throw new WarpScriptException(getName() + " expects a device address below the direction.");
    }

    int addr = ((Number) top).intValue();

    String datastr = stack.pop().toString();

    if (0 != datastr.length() % 2) {
        throw new WarpScriptException(
                getName() + " expects a hex encoded data frame with an even length of hex digits.");
    }

    byte[] data = Hex.decode(datastr);

    //
    // Compute MIC block B0
    //

    byte[] ABlock = new byte[16];

    ABlock[0] = 0x01;
    ABlock[5] = (byte) (dir & 0x1);
    ABlock[6] = (byte) (addr & 0xFF);
    ABlock[7] = (byte) ((addr >> 8) & 0xFF);
    ABlock[8] = (byte) ((addr >> 16) & 0xFF);
    ABlock[9] = (byte) ((addr >> 24) & 0xFF);

    ABlock[10] = (byte) ((sequenceCounter) & 0xFF);
    ABlock[11] = (byte) ((sequenceCounter >> 8) & 0xFF);
    ABlock[12] = (byte) ((sequenceCounter >> 16) & 0xFF);
    ABlock[13] = (byte) ((sequenceCounter >> 24) & 0xFF);

    int nblocks = data.length / 16 + (0 == data.length % 16 ? 0 : 1);

    AESEngine aes = new AESEngine();
    KeyParameter key = new KeyParameter(Hex.decode(keystr));
    aes.init(true, key);

    byte[] SBlock = new byte[16];

    int offset = 0;

    for (int i = 0; i < nblocks; i++) {
        ABlock[15] = (byte) (i & 0xFF);
        aes.reset();
        aes.processBlock(ABlock, 0, SBlock, 0);

        for (int k = 0; i < 16; i++) {
            if (offset + k < data.length) {
                data[offset + k] = (byte) (data[offset + k] ^ SBlock[k]);
            }
        }
        offset += 16;
    }

    stack.push(new String(Hex.encode(data), Charsets.US_ASCII));

    return stack;
}

From source file:io.warp10.script.lora.LORAMIC.java

License:Apache License

@Override
public Object apply(WarpScriptStack stack) throws WarpScriptException {

    Object top = stack.pop();/*w ww . j a v a2 s  .  c o m*/

    if (!(top instanceof String)) {
        throw new WarpScriptException(getName() + " expects a 128 bits hex encoded key on top of the stack.");
    }

    String keystr = top.toString();

    if (keystr.length() != 32) {
        throw new WarpScriptException(getName() + " expects a 128 bits hex encoded key on top of the stack.");
    }

    top = stack.pop();

    if (!(top instanceof Long)) {
        throw new WarpScriptException(getName() + " expects a sequence counter below the key.");
    }

    int sequenceCounter = ((Number) top).intValue();

    top = stack.pop();

    if (!(top instanceof Long)) {
        throw new WarpScriptException(
                getName() + " expects a direction (0 uplink or 1 downlink) below the sequence counter.");
    }

    int dir = ((Number) top).intValue();

    if (0 != dir && 1 != dir) {
        throw new WarpScriptException(
                getName() + " expects a direction (0 uplink or 1 downlink) below the sequence counter.");
    }

    top = stack.pop();

    if (!(top instanceof Long)) {
        throw new WarpScriptException(getName() + " expects a device address below the direction.");
    }

    int addr = ((Number) top).intValue();

    String datastr = stack.pop().toString();

    if (0 != datastr.length() % 2) {
        throw new WarpScriptException(
                getName() + " expects a hex encoded data frame with an even length of hex digits.");
    }

    byte[] data = Hex.decode(datastr);

    //
    // Compute MIC block B0
    //

    byte[] MicBlockB0 = new byte[16];

    MicBlockB0[0] = 0x49;
    MicBlockB0[5] = (byte) (dir & 0x1);
    MicBlockB0[6] = (byte) (addr & 0xFF);
    MicBlockB0[7] = (byte) ((addr >> 8) & 0xFF);
    MicBlockB0[8] = (byte) ((addr >> 16) & 0xFF);
    MicBlockB0[9] = (byte) ((addr >> 24) & 0xFF);

    MicBlockB0[10] = (byte) ((sequenceCounter) & 0xFF);
    MicBlockB0[11] = (byte) ((sequenceCounter >> 8) & 0xFF);
    MicBlockB0[12] = (byte) ((sequenceCounter >> 16) & 0xFF);
    MicBlockB0[13] = (byte) ((sequenceCounter >> 24) & 0xFF);

    MicBlockB0[15] = (byte) (data.length & 0xFF);

    AESEngine aes = new AESEngine();
    CMac cmac = new CMac(aes);
    KeyParameter key = new KeyParameter(Hex.decode(keystr));
    cmac.init(key);
    cmac.update(MicBlockB0, 0, MicBlockB0.length);
    cmac.update(data, 0, data.length & 0xFF);

    byte[] mac = new byte[cmac.getMacSize()];
    cmac.doFinal(mac, 0);

    //    byte[] mic = new byte[4];
    //    mic[0] = mac[3];
    //    mic[1] = mac[2];
    //    mic[2] = mac[1];
    //    mic[3] = mac[0];

    stack.push(new String(Hex.encode(mac, 0, 4), Charsets.US_ASCII));

    return stack;
}

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/*from   w  w w . ja  v  a  2 s  .  com*/
 *            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  w  w  w .  j ava2  s . c om*/
    ////        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./*w w w.  j av  a  2s . c o 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:me.grapebaba.hyperledger.fabric.Crypto.java

License:Apache License

public ByteString eciesDecrypt(PrivateKey recipientPrivateKey, ByteString cipherText) {
    BCECPrivateKey bcecPrivateKey = (BCECPrivateKey) recipientPrivateKey;
    ECNamedCurveSpec ecNamedCurveSpec = (ECNamedCurveSpec) bcecPrivateKey.getParams();
    int level = SecurityLevel.from(ecNamedCurveSpec.getName()).size();

    //cipherText = ephemeralPubKeyBytes + encryptedTokBytes + macBytes
    //ephemeralPubKeyBytes = first ((384+7)/8)*2 + 1 bytes = first 97 bytes
    //hmac is sha3_384 = 48 bytes or sha3_256 = 32 bytes
    int ephemeralPubKeyLength = ((level + 7) / 8) * 2 + 1;
    int hmacLength = level >> 3;
    int cipherTextLength = cipherText.size();

    if (cipherTextLength <= ephemeralPubKeyLength + hmacLength)
        throw new RuntimeException(String.format("Illegal cipherText length: %d must be > %d", cipherTextLength,
                ephemeralPubKeyLength + hmacLength));

    ByteString ephemeralPubKey = cipherText.substring(0, ephemeralPubKeyLength);
    ByteString encryptedContent = cipherText.substring(ephemeralPubKeyLength, cipherTextLength - hmacLength);
    ByteString hmac = cipherText.substring(cipherTextLength - hmacLength);

    ECPrivateKeyParameters ecdhPrivateKeyParameters;
    try {/*from w  w w  . java 2 s  .  c  o  m*/
        ecdhPrivateKeyParameters = (ECPrivateKeyParameters) (PrivateKeyFactory
                .createKey(bcecPrivateKey.getEncoded()));
    } catch (IOException e) {
        logger.error("ECIES decrypt load private key exception", e);
        throw new RuntimeException(e);
    }
    ECDomainParameters ecDomainParameters = ecdhPrivateKeyParameters.getParameters();
    ECCurve ecCurve = ecDomainParameters.getCurve();
    ECPublicKeyParameters ecPublicKeyParameters = new ECPublicKeyParameters(
            ecCurve.decodePoint(ephemeralPubKey.toByteArray()), ecDomainParameters);
    BasicAgreement agree = new ECDHBasicAgreement();
    agree.init(ecdhPrivateKeyParameters);
    byte[] keyAgreement = agree.calculateAgreement(ecPublicKeyParameters).toByteArray();

    HKDFParameters hkdfParameters = new HKDFParameters(keyAgreement, null, null);
    HKDFBytesGenerator hkdfBytesGenerator = new HKDFBytesGenerator(digest);
    hkdfBytesGenerator.init(hkdfParameters);
    byte[] hkdfOutputBytes = new byte[AESKEY_LENGTH + HMACKEY_LENGTH];
    hkdfBytesGenerator.generateBytes(hkdfOutputBytes, 0, AESKEY_LENGTH + HMACKEY_LENGTH);
    ByteString hkdfOutput = ByteString.copyFrom(hkdfOutputBytes);
    ByteString aesKey = hkdfOutput.substring(0, AESKEY_LENGTH);
    ByteString hmacKey = hkdfOutput.substring(AESKEY_LENGTH, AESKEY_LENGTH + HMACKEY_LENGTH);
    HMac hMac = new HMac(digest);
    hMac.init(new KeyParameter(hmacKey.toByteArray()));
    hMac.update(encryptedContent.toByteArray(), 0, encryptedContent.size());
    byte[] recoveredHmac = new byte[hMac.getMacSize()];
    hMac.doFinal(recoveredHmac, 0);
    if (!MessageDigest.isEqual(hmac.toByteArray(), recoveredHmac)) {
        throw new RuntimeException("HMAC verify failed");
    }

    CFBBlockCipher aesCipher = new CFBBlockCipher(new AESEngine(), BLOCK_BIT_SIZE);
    ByteString iv = encryptedContent.substring(0, IV_LENGTH);
    CipherParameters ivAndKey = new ParametersWithIV(new KeyParameter(aesKey.toByteArray()), iv.toByteArray());
    aesCipher.init(false, ivAndKey);
    byte[] decryptedBytes = new byte[500];
    aesCipher.decryptBlock(encryptedContent.substring(IV_LENGTH).toByteArray(), 0, decryptedBytes, 0);
    return ByteString.copyFrom(decryptedBytes);
}