Example usage for org.bouncycastle.crypto AsymmetricBlockCipher getInputBlockSize

List of usage examples for org.bouncycastle.crypto AsymmetricBlockCipher getInputBlockSize

Introduction

In this page you can find the example usage for org.bouncycastle.crypto AsymmetricBlockCipher getInputBlockSize.

Prototype

public int getInputBlockSize();

Source Link

Document

returns the largest size an input block can be.

Usage

From source file:com.geoxp.oss.CryptoHelper.java

License:Apache License

/**
 * Encrypt data using RSA.// w w  w  .j a  va2  s  .c  o  m
 * CAUTION: this can take a while on large data
 * 
 * @param key RSA key to use for encryption
 * @param data Cleartext data
 * @return The ciphertext data or null if an error occured
 */
public static byte[] encryptRSA(Key key, byte[] data) {
    //
    // Get an RSA Cipher instance
    //
    //Cipher rsa = null;

    try {
        /* The following commented code can be used the BouncyCastle
         * JCE provider signature is intact, which is not the
         * case when BC has been repackaged using jarjar
        rsa = Cipher.getInstance("RSA/ECB/PKCS1Padding", "BC");
        rsa.init (Cipher.ENCRYPT_MODE, key, CryptoHelper.sr);                   
        return rsa.doFinal(data);
        */
        AsymmetricBlockCipher c = new PKCS1Encoding(new RSABlindedEngine());
        if (key instanceof RSAPublicKey) {
            c.init(true, new RSAKeyParameters(true, ((RSAPublicKey) key).getModulus(),
                    ((RSAPublicKey) key).getPublicExponent()));
        } else if (key instanceof RSAPrivateKey) {
            c.init(true, new RSAKeyParameters(true, ((RSAPrivateKey) key).getModulus(),
                    ((RSAPrivateKey) key).getPrivateExponent()));
        } else {
            return null;
        }

        int insize = c.getInputBlockSize();

        int offset = 0;

        ByteArrayOutputStream baos = new ByteArrayOutputStream();

        while (offset < data.length) {
            int len = Math.min(insize, data.length - offset);
            baos.write(c.processBlock(data, offset, len));
            offset += len;
        }

        return baos.toByteArray();

        /*
            } catch (NoSuchProviderException nspe) {
              return null;
            } catch (NoSuchPaddingException nspe) {
              return null;
            } catch (NoSuchAlgorithmException nsae) {
              return null;
            } catch (InvalidKeyException ike) {
              return null;
            } catch (BadPaddingException bpe) {
              return null;
            } catch (IllegalBlockSizeException ibse) {
              return null;
            }
        */
    } catch (InvalidCipherTextException icte) {
        return null;
    } catch (IOException ioe) {
        return null;
    }
}

From source file:com.geoxp.oss.CryptoHelper.java

License:Apache License

/**
 * Decrypt data previously encrypted with RSA
 * @param key RSA key to use for decryption
 * @param data Ciphertext data//from   ww  w  .j  av  a 2 s .  c om
 * @return The cleartext data or null if an error occurred
 */
public static byte[] decryptRSA(Key key, byte[] data) {
    //
    // Get an RSA Cipher instance
    //

    //Cipher rsa = null;

    try {
        /* The following commented code can be used the BouncyCastle
         * JCE provider signature is intact, which is not the
         * case when BC has been repackaged using jarjar
        rsa = Cipher.getInstance("RSA/ECB/PKCS1Padding", "BC");
        rsa.init (Cipher.DECRYPT_MODE, key, CryptoHelper.sr);
        return rsa.doFinal(data);
        */

        AsymmetricBlockCipher c = new PKCS1Encoding(new RSABlindedEngine());
        if (key instanceof RSAPublicKey) {
            c.init(false, new RSAKeyParameters(true, ((RSAPublicKey) key).getModulus(),
                    ((RSAPublicKey) key).getPublicExponent()));
        } else if (key instanceof RSAPrivateKey) {
            c.init(false, new RSAKeyParameters(true, ((RSAPrivateKey) key).getModulus(),
                    ((RSAPrivateKey) key).getPrivateExponent()));
        } else {
            return null;
        }

        int insize = c.getInputBlockSize();

        int offset = 0;

        ByteArrayOutputStream baos = new ByteArrayOutputStream();

        while (offset < data.length) {
            int len = Math.min(insize, data.length - offset);
            baos.write(c.processBlock(data, offset, len));
            offset += len;
        }

        return baos.toByteArray();

        /*
            } catch (NoSuchProviderException nspe) {
              return null;
            } catch (NoSuchPaddingException nspe) {
              return null;
            } catch (NoSuchAlgorithmException nsae) {
              return null;
            } catch (InvalidKeyException ike) {
              return null;
            } catch (BadPaddingException bpe) {
              return null;
            } catch (IllegalBlockSizeException ibse) {
              return null;
            }
        */
    } catch (InvalidCipherTextException icte) {
        return null;
    } catch (IOException ioe) {
        return null;
    }
}

From source file:com.maiereni.util.EncryptedFileLoader.java

License:Apache License

/**
 * Encrypt and encode //from  w w w  .  j  a va2 s.  c o m
 * @param buffer
 * @return
 * @throws Exception
 */
protected byte[] encryptRSA(final byte[] buffer) throws Exception {
    try (ByteArrayOutputStream out = new ByteArrayOutputStream()) {
        AsymmetricBlockCipher cipher = getAsymmetricBlockCipher(true);
        int len = cipher.getInputBlockSize();
        for (int i = 0; i < buffer.length; i += len) {
            if (i + len > buffer.length)
                len = buffer.length - i;

            byte[] encrypted = cipher.processBlock(buffer, i, len);
            out.write(encrypted);
        }
        return out.toByteArray();
    }
}

From source file:com.maiereni.util.EncryptedFileLoader.java

License:Apache License

protected byte[] decryptRSA(final byte[] buffer) throws Exception {
    try (ByteArrayOutputStream out = new ByteArrayOutputStream()) {
        AsymmetricBlockCipher cipher = getAsymmetricBlockCipher(false);
        int len = cipher.getInputBlockSize();
        for (int i = 0; i < buffer.length; i += len) {
            if (i + len > buffer.length) {
                len = buffer.length - i;
            }/*from   w  w w  .  j a  va  2  s  .  c  o  m*/

            byte[] decrypted = cipher.processBlock(buffer, i, len);
            out.write(decrypted);
        }
        return out.toByteArray();
    }
}

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

License:Apache License

/**
 * RSA encrypts data with a specified key.
 *
 * @param logger/*from w w w .  ja  v a 2s.  c o  m*/
 *                 may be null, if no log output is necessary
 *
 * @return empty byte[] if error
 */
public static byte[] encrypt(AsymmetricBlockCipher rsaEngine, RSAKeyParameters rsaPublicKey, byte[] bytes,
        Logger logger) {
    rsaEngine.init(true, rsaPublicKey);

    try {
        int inputBlockSize = rsaEngine.getInputBlockSize();
        if (inputBlockSize < bytes.length) {
            int outSize = rsaEngine.getOutputBlockSize();
            //noinspection NumericCastThatLosesPrecision
            int realsize = (int) Math.round(bytes.length / (outSize * 1.0D) + 0.5);
            ByteBuffer buffer = ByteBuffer.allocateDirect(outSize * realsize);

            int position = 0;

            while (position < bytes.length) {
                int size = Math.min(inputBlockSize, bytes.length - position);

                byte[] block = rsaEngine.processBlock(bytes, position, size);
                buffer.put(block, 0, block.length);

                position += size;
            }

            return buffer.array();

        } else {
            return rsaEngine.processBlock(bytes, 0, bytes.length);
        }
    } catch (Exception e) {
        if (logger != null) {
            logger.error("Unable to perform RSA cipher.", e);
        }
        return new byte[0];
    }
}

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

License:Apache License

/**
 * RSA decrypt data with a specified key.
 *
 * @param logger// w  w w.  jav a  2 s  .  co m
 *                 may be null, if no log output is necessary
 *
 * @return empty byte[] if error
 */
public static byte[] decrypt(AsymmetricBlockCipher rsaEngine, RSAPrivateCrtKeyParameters rsaPrivateKey,
        byte[] bytes, Logger logger) {
    rsaEngine.init(false, rsaPrivateKey);

    try {
        int inputBlockSize = rsaEngine.getInputBlockSize();
        if (inputBlockSize < bytes.length) {
            int outSize = rsaEngine.getOutputBlockSize();
            //noinspection NumericCastThatLosesPrecision
            int realsize = (int) Math.round(bytes.length / (outSize * 1.0D) + 0.5);
            ByteArrayOutputStream buffer = new ByteArrayOutputStream(outSize * realsize);

            int position = 0;

            while (position < bytes.length) {
                int size = Math.min(inputBlockSize, bytes.length - position);

                byte[] block = rsaEngine.processBlock(bytes, position, size);
                buffer.write(block, 0, block.length);

                position += size;
            }

            return buffer.toByteArray();
        } else {
            return rsaEngine.processBlock(bytes, 0, bytes.length);
        }
    } catch (Exception e) {
        if (logger != null) {
            logger.error("Unable to perform RSA cipher.", e);
        }
        return new byte[0];
    }
}

From source file:freemail.RTSFetcher.java

License:Open Source License

private boolean handle_rts(File rtsmessage) throws ConnectionTerminatedException, InterruptedException {
    // sanity check!
    if (!rtsmessage.exists())
        return false;

    if (rtsmessage.length() > RTS_MAX_SIZE) {
        Logger.normal(this, "RTS Message is too large - discarding!");
        return true;
    }/*  www. jav a  2  s .  c o  m*/

    // decrypt
    byte[] plaintext;
    try {
        plaintext = decrypt_rts(rtsmessage);
    } catch (IOException ioe) {
        Logger.normal(this, "Error reading RTS message!");
        return false;
    } catch (InvalidCipherTextException icte) {
        Logger.normal(this, "Could not decrypt RTS message - discarding." + icte.getMessage());
        return true;
    }

    File rtsfile = null;
    byte[] their_encrypted_sig;
    int messagebytes = 0;
    try {
        rtsfile = File.createTempFile("rtstmp", "tmp", Freemail.getTempDir());

        ByteArrayInputStream bis = new ByteArrayInputStream(plaintext);
        LineReadingInputStream lis = new LineReadingInputStream(bis);
        PrintStream ps = new PrintStream(new FileOutputStream(rtsfile));

        String line;
        while (true) {
            try {
                line = lis.readLine(200, 200, false);
            } catch (TooLongException tle) {
                Logger.normal(this, "RTS message has lines that are too long. Discarding.");
                rtsfile.delete();
                return true;
            }
            messagebytes += lis.getLastBytesRead();

            if (line == null || line.equals(""))
                break;
            //FreemailLogger.normal(this,line);

            ps.println(line);
        }

        ps.close();

        if (line == null) {
            // that's not right, we shouldn't have reached the end of the file, just the blank line before the signature

            Logger.normal(this, "Couldn't find signature on RTS message - ignoring!");
            rtsfile.delete();
            return true;
        }

        // read the rest of the file into a byte array.
        // will probably have extra stuff on the end because
        // the byte array returned by the decrypt function
        // isn't resized when we know how much plaintext
        // there is. It would be a waste of time, we know
        // we have to read exactly one RSA block's worth.
        their_encrypted_sig = new byte[bis.available()];

        int totalread = 0;
        while (true) {
            int read = bis.read(their_encrypted_sig, totalread, bis.available());
            if (read <= 0)
                break;
            totalread += read;
        }

        bis.close();
    } catch (IOException ioe) {
        Logger.normal(this, "IO error whilst handling RTS message. " + ioe.getMessage());
        ioe.printStackTrace();
        if (rtsfile != null)
            rtsfile.delete();
        return false;
    }

    PropsFile rtsprops = PropsFile.createPropsFile(rtsfile);

    try {
        validate_rts(rtsprops);
    } catch (Exception e) {
        Logger.normal(this,
                "RTS message does not contain vital information: " + e.getMessage() + " - discarding");
        rtsfile.delete();
        return true;
    }

    // verify the signature
    String their_mailsite_raw = rtsprops.get("mailsite");

    SHA256Digest sha256 = new SHA256Digest();
    sha256.update(plaintext, 0, messagebytes);
    byte[] our_hash = new byte[sha256.getDigestSize()];
    sha256.doFinal(our_hash, 0);

    HighLevelFCPClient fcpcli = new HighLevelFCPClient();

    FreenetURI their_mailsite_furi;
    try {
        their_mailsite_furi = new FreenetURI(their_mailsite_raw);
    } catch (MalformedURLException mfue) {
        Logger.normal(this, "Mailsite in the RTS message is not a valid Freenet URI. Discarding RTS message.");
        rtsfile.delete();
        return true;
    }

    String their_mailsite = "USK@" + their_mailsite_furi.getKeyBody() + "/" + their_mailsite_furi.getSuffix();

    if (!their_mailsite.endsWith("/")) {
        their_mailsite += "/";
    }
    their_mailsite += AccountManager.MAILSITE_VERSION + "/" + MailSite.MAILPAGE;

    Logger.normal(this, "Trying to fetch sender's mailsite: " + their_mailsite);
    File msfile;
    try {
        msfile = fcpcli.fetch(their_mailsite);
    } catch (FCPFetchException fe) {
        // oh well, try again in a bit
        rtsfile.delete();
        return false;
    } catch (FCPException e) {
        Logger.error(this, "Unknown error while checking sender's mailsite: " + e);

        //Try again later
        rtsfile.delete();
        return false;
    }

    PropsFile mailsite = PropsFile.createPropsFile(msfile);
    String their_exponent = mailsite.get("asymkey.pubexponent");
    String their_modulus = mailsite.get("asymkey.modulus");

    if (their_exponent == null || their_modulus == null) {
        Logger.normal(this,
                "Mailsite fetched successfully but missing vital information! Discarding this RTS.");
        msfile.delete();
        rtsfile.delete();
        return true;
    }

    RSAKeyParameters their_pubkey = new RSAKeyParameters(false, new BigInteger(their_modulus, 32),
            new BigInteger(their_exponent, 32));
    AsymmetricBlockCipher deccipher = new RSAEngine();
    deccipher.init(false, their_pubkey);

    byte[] their_hash;
    try {
        their_hash = deccipher.processBlock(their_encrypted_sig, 0, deccipher.getInputBlockSize());
    } catch (InvalidCipherTextException icte) {
        Logger.normal(this,
                "It was not possible to decrypt the signature of this RTS message. Discarding the RTS message.");
        msfile.delete();
        rtsfile.delete();
        return true;
    }

    // finally we can now check that our hash and their hash
    // match!
    if (their_hash.length < our_hash.length) {
        Logger.normal(this, "The signature of the RTS message is not valid (our hash: " + our_hash.length
                + "bytes, their hash: " + their_hash.length + "bytes. Discarding the RTS message.");
        msfile.delete();
        rtsfile.delete();
        return true;
    }
    int i;
    for (i = 0; i < our_hash.length; i++) {
        if (their_hash[i] != our_hash[i]) {
            Logger.normal(this, "The signature of the RTS message is not valid. Discarding the RTS message.");
            msfile.delete();
            rtsfile.delete();
            return true;
        }
    }
    Logger.normal(this, "Signature valid :)");
    // the signature is valid! Hooray!
    // Now verify the message is for us
    String our_mailsite_keybody;
    try {
        our_mailsite_keybody = new FreenetURI(account.getProps().get("mailsite.pubkey")).getKeyBody();
    } catch (MalformedURLException mfue) {
        Logger.normal(this, "Local mailsite URI is invalid! Corrupt account file?");
        msfile.delete();
        rtsfile.delete();
        return false;
    }

    String our_domain_alias = account.getProps().get("domain_alias");
    FreenetURI mailsite_furi;
    try {
        mailsite_furi = new FreenetURI(our_mailsite_keybody);
    } catch (MalformedURLException mfe) {
        msfile.delete();
        rtsfile.delete();
        return false;
    }
    String our_subdomain = Base32.encode(mailsite_furi.getKeyBody().getBytes());

    if (!rtsprops.get("to").equalsIgnoreCase(our_subdomain) && our_domain_alias != null
            && !rtsprops.get("to").equals(our_domain_alias)) {
        Logger.normal(this, "Recieved an RTS message that was not intended for the recipient. Discarding.");
        msfile.delete();
        rtsfile.delete();
        return true;
    }

    Logger.normal(this, "Original message intended for us :)");

    // create the inbound contact
    InboundContact ibct = new InboundContact(this.contact_dir, their_mailsite_furi);

    ibct.setProp("commssk", rtsprops.get("commssk"));
    String ackssk = rtsprops.get("ackssk");
    if (!ackssk.endsWith("/"))
        ackssk += "/";
    ibct.setProp("ackssk", ackssk);
    ibct.setProp("slots", rtsprops.get("initialslot"));

    // insert the cts at some point
    AckProcrastinator.put(ackssk + "cts");

    msfile.delete();
    rtsfile.delete();

    Logger.normal(this, "Inbound contact created!");

    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  ava 2s  .  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:org.freenetproject.freemail.RTSFetcher.java

License:Open Source License

private boolean handle_rts(File rtsmessage) throws ConnectionTerminatedException, InterruptedException {
    // sanity check!
    if (!rtsmessage.exists())
        return false;

    if (rtsmessage.length() > RTS_MAX_SIZE) {
        Logger.normal(this, "RTS Message is too large - discarding!");
        return true;
    }/* w  ww. ja va2s  .  c  o m*/

    // decrypt
    byte[] plaintext;
    try {
        plaintext = decrypt_rts(rtsmessage);
    } catch (IOException ioe) {
        Logger.normal(this, "Error reading RTS message!");
        return false;
    } catch (InvalidCipherTextException icte) {
        Logger.normal(this, "Could not decrypt RTS message - discarding. " + icte.getMessage());
        return true;
    }

    File rtsfile = null;
    byte[] their_encrypted_sig;
    int messagebytes = 0;
    LineReadingInputStream lis = null;
    PrintStream ps = null;
    try {
        rtsfile = File.createTempFile("rtstmp", "tmp", Freemail.getTempDir());

        ByteArrayInputStream bis = new ByteArrayInputStream(plaintext);
        lis = new LineReadingInputStream(bis);
        ps = new PrintStream(new FileOutputStream(rtsfile));

        String line;
        while (true) {
            try {
                line = lis.readLine(200, 200, false);
            } catch (TooLongException tle) {
                Logger.normal(this, "RTS message has lines that are too long. Discarding.");
                rtsfile.delete();
                return true;
            }
            messagebytes += lis.getLastBytesRead();

            if (line == null || line.equals(""))
                break;
            //FreemailLogger.normal(this, line);

            ps.println(line);
        }

        if (line == null) {
            // that's not right, we shouldn't have reached the end of the file, just the blank line before the signature

            Logger.normal(this, "Couldn't find signature on RTS message - ignoring!");
            rtsfile.delete();
            return true;
        }

        // read the rest of the file into a byte array.
        // will probably have extra stuff on the end because
        // the byte array returned by the decrypt function
        // isn't resized when we know how much plaintext
        // there is. It would be a waste of time, we know
        // we have to read exactly one RSA block's worth.
        their_encrypted_sig = new byte[bis.available()];

        int totalread = 0;
        while (true) {
            int read = bis.read(their_encrypted_sig, totalread, bis.available());
            if (read <= 0)
                break;
            totalread += read;
        }
    } catch (IOException ioe) {
        Logger.normal(this, "IO error whilst handling RTS message. " + ioe.getMessage());
        ioe.printStackTrace();
        if (rtsfile != null)
            rtsfile.delete();
        return false;
    } finally {
        if (ps != null) {
            ps.close();
        }
        if (lis != null) {
            try {
                lis.close();
            } catch (IOException e) {
                Logger.error(this, "Caugth IOException while closing input", e);
            }
        }
    }

    PropsFile rtsprops = PropsFile.createPropsFile(rtsfile);

    try {
        validate_rts(rtsprops);
    } catch (Exception e) {
        Logger.normal(this,
                "RTS message does not contain vital information: " + e.getMessage() + " - discarding");
        rtsfile.delete();
        return true;
    }

    // verify the signature
    String their_mailsite = rtsprops.get("mailsite");

    SHA256Digest sha256 = new SHA256Digest();
    sha256.update(plaintext, 0, messagebytes);
    byte[] our_hash = new byte[sha256.getDigestSize()];
    sha256.doFinal(our_hash, 0);

    HighLevelFCPClient fcpcli = new HighLevelFCPClient();

    Logger.normal(this, "Trying to fetch sender's mailsite: " + their_mailsite);
    File msfile;
    try {
        msfile = fcpcli.fetch(their_mailsite);
    } catch (FCPFetchException fe) {
        // oh well, try again in a bit
        rtsfile.delete();
        return false;
    } catch (FCPException e) {
        Logger.error(this, "Unknown error while checking sender's mailsite: " + e.getMessage());

        //Try again later
        rtsfile.delete();
        return false;
    }

    PropsFile mailsite = PropsFile.createPropsFile(msfile);
    String their_exponent = mailsite.get("asymkey.pubexponent");
    String their_modulus = mailsite.get("asymkey.modulus");

    if (their_exponent == null || their_modulus == null) {
        Logger.normal(this,
                "Mailsite fetched successfully but missing vital information! Discarding this RTS.");
        msfile.delete();
        rtsfile.delete();
        return true;
    }

    RSAKeyParameters their_pubkey = new RSAKeyParameters(false, new BigInteger(their_modulus, 32),
            new BigInteger(their_exponent, 32));
    AsymmetricBlockCipher deccipher = new RSAEngine();
    deccipher.init(false, their_pubkey);

    byte[] their_hash;
    try {
        their_hash = deccipher.processBlock(their_encrypted_sig, 0, deccipher.getInputBlockSize());
    } catch (InvalidCipherTextException icte) {
        Logger.normal(this,
                "It was not possible to decrypt the signature of this RTS message. Discarding the RTS message.");
        msfile.delete();
        rtsfile.delete();
        return true;
    }

    // finally we can now check that our hash and their hash
    // match!
    if (their_hash.length < our_hash.length) {
        Logger.normal(this, "The signature of the RTS message is not valid (our hash: " + our_hash.length
                + "bytes, their hash: " + their_hash.length + "bytes. Discarding the RTS message.");
        msfile.delete();
        rtsfile.delete();
        return true;
    }
    int i;
    for (i = 0; i < our_hash.length; i++) {
        if (their_hash[i] != our_hash[i]) {
            Logger.normal(this, "The signature of the RTS message is not valid. Discarding the RTS message.");
            msfile.delete();
            rtsfile.delete();
            return true;
        }
    }
    Logger.normal(this, "Signature valid :)");
    // the signature is valid! Hooray!
    // Now verify the message is for us
    if (!account.getIdentity().equals(rtsprops.get("to"))) {
        Logger.normal(this, "Recieved an RTS message that was not intended for the recipient. Discarding.");
        msfile.delete();
        rtsfile.delete();
        return true;
    }

    Logger.normal(this, "Original message intended for us :)");

    //Clean up temp files
    if (!msfile.delete()) {
        Logger.error(this, "Couldn't delete fetched mailsite: " + msfile);
    }
    if (!rtsfile.delete()) {
        Logger.error(this, "Couldn't delete rts file: " + rtsfile);
    }

    account.getMessageHandler().createChannelFromRTS(rtsprops);

    return true;
}

From source file:org.freenetproject.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);//w w  w . j a v a2 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()];
    int read = 0;
    FileInputStream fis = new FileInputStream(rtsmessage);
    try {
        while (read < encrypted_params.length) {
            read += fis.read(encrypted_params, read, encrypted_params.length - read);
            if (read < 0)
                break;
        }

        if (read < 0) {
            fis.close();
            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) {
            fis.close();
            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;
        }

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

        return plaintext;
    } finally {
        fis.close();
    }
}