List of usage examples for org.bouncycastle.crypto.paddings PaddedBufferedBlockCipher getBlockSize
public int getBlockSize()
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/*from ww w.j a v a 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 a v a 2 s .com*/ 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:jcrypter.JCrypterFrame.java
License:Apache License
private void decryptWithBypass() //TODO this is only a test, review!! { try //TODO this is only a test, review!! {//from w w w.j a va 2s . c o m PaddedBufferedBlockCipher bc = new PaddedBufferedBlockCipher(new TwofishEngine(), new PKCS7Padding()); int bs = bc.getBlockSize(); //Blocksize //Get data byte[] passwordBytes = new String(passwordField.getPassword()).getBytes(); byte[] input; //Base64-decode the ciphertext input = Base64.decode(inputField.getText().getBytes()); //All data will be read from this stream ByteArrayInputStream bin = new ByteArrayInputStream(input); //Hash the password to fit it into the right size (with salt) byte[] salt = new byte[8]; byte[] keyBytes = new byte[32]; bin.read(salt); //Get the salt from the input stream Digest digest = new SHA256Digest(); digest.update(salt, 0, salt.length); //Add the salt... digest.update(passwordBytes, 0, passwordBytes.length); //...and the password to the generator digest.doFinal(keyBytes, 0); //Do the final hashing //IV generation/retrievement byte[] iv = new byte[cipher.getBlockSize()]; //Using iv array only with offset bin.read(iv); ByteArrayOutputStream bout = new ByteArrayOutputStream(); /* * IMPORTANT NOTE: * This implementation bypasses the policy but does only support TWOFISH/ECB */ CipherParameters params = new ParametersWithIV(new KeyParameter(keyBytes), iv); bc.init(false, params); byte[] plaintext = new byte[bc.getOutputSize(bin.available())]; //All at once byte[] buffer = new byte[bs]; byte[] oBuffer = new byte[bs]; //OutputBuffer while (bin.available() > 0) { int read = bin.read(buffer); bc.processBytes(buffer, 0, read, oBuffer, 0); bout.write(oBuffer); } outputField.setText(new String(bout.toByteArray())); } catch (IOException ex) { Logger.getLogger(JCrypterFrame.class.getName()).log(Level.SEVERE, null, ex); } }
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);//from www .j a v 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()]; 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(); } }