List of usage examples for org.bouncycastle.crypto.digests SHA256Digest SHA256Digest
public SHA256Digest()
From source file:freemail.OutboundContact.java
License:Open Source License
private String popNextSlot() { String slot = this.contactfile.get("nextslot"); if (slot == null) { return generateFirstSlot(); }//from w w w.j a va 2s. c o m SHA256Digest sha256 = new SHA256Digest(); sha256.update(Base32.decode(slot), 0, Base32.decode(slot).length); byte[] nextslot = new byte[sha256.getDigestSize()]; sha256.doFinal(nextslot, 0); this.contactfile.put("nextslot", Base32.encode(nextslot)); return slot; }
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; }/* w w w .java 2 s. c om*/ // 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:freenet.keys.InsertableClientSSK.java
License:GNU General Public License
public ClientSSKBlock encode(Bucket sourceData, boolean asMetadata, boolean dontCompress, short alreadyCompressedCodec, long sourceLength, RandomSource r, String compressordescriptor, boolean pre1254) throws SSKEncodeException, IOException, InvalidCompressionCodecException { byte[] compressedData; short compressionAlgo; try {//from ww w. j a v a 2 s.c o m Compressed comp = Key.compress(sourceData, dontCompress, alreadyCompressedCodec, sourceLength, ClientSSKBlock.MAX_DECOMPRESSED_DATA_LENGTH, SSKBlock.DATA_LENGTH, true, compressordescriptor, pre1254); compressedData = comp.compressedData; compressionAlgo = comp.compressionAlgorithm; } catch (KeyEncodeException e) { throw new SSKEncodeException(e.getMessage(), e); } // Pad it MessageDigest md256 = SHA256.getMessageDigest(); try { byte[] data; // First pad it if (compressedData.length != SSKBlock.DATA_LENGTH) { // Hash the data if (compressedData.length != 0) md256.update(compressedData); byte[] digest = md256.digest(); MersenneTwister mt = new MersenneTwister(digest); data = Arrays.copyOf(compressedData, SSKBlock.DATA_LENGTH); if (compressedData.length > data.length) { throw new RuntimeException( "compressedData.length = " + compressedData.length + " but data.length=" + data.length); } Util.randomBytes(mt, data, compressedData.length, SSKBlock.DATA_LENGTH - compressedData.length); } else { data = compressedData; } // Implicit hash of data byte[] origDataHash = md256.digest(data); Rijndael aes; try { aes = new Rijndael(256, 256); } catch (UnsupportedCipherException e) { throw new Error("256/256 Rijndael not supported!"); } // Encrypt data. Data encryption key = H(plaintext data). aes.initialize(origDataHash); PCFBMode pcfb = PCFBMode.create(aes, origDataHash); pcfb.blockEncipher(data, 0, data.length); byte[] encryptedDataHash = md256.digest(data); // Create headers byte[] headers = new byte[SSKBlock.TOTAL_HEADERS_LENGTH]; // First two bytes = hash ID int x = 0; headers[x++] = (byte) (KeyBlock.HASH_SHA256 >> 8); headers[x++] = (byte) (KeyBlock.HASH_SHA256); // Then crypto ID headers[x++] = (byte) (Key.ALGO_AES_PCFB_256_SHA256 >> 8); headers[x++] = Key.ALGO_AES_PCFB_256_SHA256; // Then E(H(docname)) // Copy to headers System.arraycopy(ehDocname, 0, headers, x, ehDocname.length); x += ehDocname.length; // Now the encrypted headers byte[] encryptedHeaders = Arrays.copyOf(origDataHash, SSKBlock.ENCRYPTED_HEADERS_LENGTH); int y = origDataHash.length; short len = (short) compressedData.length; if (asMetadata) len |= 32768; encryptedHeaders[y++] = (byte) (len >> 8); encryptedHeaders[y++] = (byte) len; encryptedHeaders[y++] = (byte) (compressionAlgo >> 8); encryptedHeaders[y++] = (byte) compressionAlgo; if (encryptedHeaders.length != y) throw new IllegalStateException("Have more bytes to generate encoding SSK"); aes.initialize(cryptoKey); pcfb.reset(ehDocname); pcfb.blockEncipher(encryptedHeaders, 0, encryptedHeaders.length); System.arraycopy(encryptedHeaders, 0, headers, x, encryptedHeaders.length); x += encryptedHeaders.length; // Generate implicit overall hash. md256.update(headers, 0, x); md256.update(encryptedDataHash); byte[] overallHash = md256.digest(); // Now sign it DSASigner dsa = new DSASigner(new HMacDSAKCalculator(new SHA256Digest())); dsa.init(true, new DSAPrivateKeyParameters(privKey.getX(), Global.getDSAgroupBigAParameters())); BigInteger[] sig = dsa.generateSignature(Global.truncateHash(overallHash)); // Pack R and S into 32 bytes each, and copy to headers. // Then create and return the ClientSSKBlock. byte[] rBuf = truncate(sig[0].toByteArray(), SSKBlock.SIG_R_LENGTH); byte[] sBuf = truncate(sig[1].toByteArray(), SSKBlock.SIG_S_LENGTH); System.arraycopy(rBuf, 0, headers, x, rBuf.length); x += rBuf.length; System.arraycopy(sBuf, 0, headers, x, sBuf.length); x += sBuf.length; if (x != SSKBlock.TOTAL_HEADERS_LENGTH) throw new IllegalStateException("Too long"); try { return new ClientSSKBlock(data, headers, this, !logMINOR); } catch (SSKVerifyException e) { throw (AssertionError) new AssertionError("Impossible encoding error").initCause(e); } } finally { SHA256.returnMessageDigest(md256); } }
From source file:gnu.java.zrtp.ZRtp.java
License:Open Source License
private void setNegotiatedHash(ZrtpConstants.SupportedHashes hash) { if (hash == ZrtpConstants.SupportedHashes.S256) { hashFunction = new SHA256Digest(); hmacFunction = new HMac(new SHA256Digest()); hashCtxFunction = new SHA256Digest(); } else if (hash == ZrtpConstants.SupportedHashes.S384) { hashFunction = new SHA384Digest(); hmacFunction = new HMac(new SHA384Digest()); hashCtxFunction = new SHA384Digest(); }//from www . j a v a 2s . co m hashLength = hashFunction.getDigestSize(); }
From source file:hu.akarnokd.utils.crypto.CryptoUtils.java
License:Apache License
/** * Generates salt with the given length. * @param size the number of bytes//from w ww. j a va 2 s .c o m * @return the salt bytes */ @NonNull public static byte[] generateSalt(int size) { Digest digest = null; switch (String.format(DEFAULT_SALT_ALG, DEFAULT_PBE_KEY_BITS)) { case "SHA224PRNG": digest = new SHA224Digest(); break; case "SHA256PRNG": digest = new SHA256Digest(); break; case "SHA384PRNG": digest = new SHA384Digest(); break; case "SHA512PRNG": digest = new SHA512Digest(); break; default: digest = new SHA1Digest(); } DigestRandomGenerator drg = new DigestRandomGenerator(digest); drg.addSeedMaterial(System.currentTimeMillis()); byte[] r = new byte[size]; drg.nextBytes(r); return r; }
From source file:io.netty.example.ocsp.Digester.java
License:Apache License
public static DigestCalculator sha256() { Digest digest = new SHA256Digest(); // The OID for SHA-256: http://www.oid-info.com/get/2.16.840.1.101.3.4.2.1 ASN1ObjectIdentifier oid = new ASN1ObjectIdentifier("2.16.840.1.101.3.4.2.1").intern(); AlgorithmIdentifier algId = new AlgorithmIdentifier(oid); return new Digester(digest, algId); }
From source file:jazmin.server.relay.udp.webrtc.TlsUtils.java
License:Open Source License
static byte[] digestOf(String hashFunction, byte[] input) { Digest d;//from ww w . j a v a2 s.c om switch (hashFunction) { case SHA_1: d = new SHA1Digest(); break; case SHA_512: d = new SHA512Digest(); break; case SHA_256: default: d = new SHA256Digest(); break; } d.update(input, 0, input.length); byte[] result = new byte[d.getDigestSize()]; d.doFinal(result, 0); return result; }
From source file:jcrypter.JCrypterFrame.java
License:Apache License
private void decryptSymmetric() { try {/*w w w .ja v a 2s . co m*/ //Cipher field is automatically initialized by the CMP Dialog int bs = cipher.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); IvParameterSpec ivSpec = new IvParameterSpec(iv, 0, bs); //Generate the secret key spec SecretKeySpec keySpec = new SecretKeySpec(keyBytes, cmpDialog.getCipher()); cipher.init(Cipher.DECRYPT_MODE, keySpec, ivSpec); CipherInputStream cin = new CipherInputStream(bin, cipher); //Print the input (minus the IV, if decrypting) into cout byte[] plaintext = new byte[bin.available()]; cin.read(plaintext); //Decrypts the rest data in bin //Close the cipher stream cin.close(); //Print the output into outputField and Base64-encode if we have to encrypt outputField.setText(new String(plaintext).trim()); } catch (InvalidAlgorithmParameterException ex) { Logger.getLogger(JCrypterFrame.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) //Must not occure { Logger.getLogger(JCrypterFrame.class.getName()).log(Level.SEVERE, null, ex); } catch (InvalidKeyException ex) { Logger.getLogger(JCrypterFrame.class.getName()).log(Level.SEVERE, null, ex); } }
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!! {/* w ww .j ava 2 s .c om*/ 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:jcrypter.JCrypterFrame.java
License:Apache License
private void encryptSymmetric() { try {/*from ww w. j ava 2 s. c o m*/ //cipher field is initalized by the cmp dialog and at the beginning //Using BouncyCastle JCEs int bs = cipher.getBlockSize(); //Blocksize //Get data byte[] passwordBytes = new String(passwordField.getPassword()).getBytes(); byte[] input; //Base64-decode the ciphertext input = inputField.getText().getBytes(); //All data is written to this stream ByteArrayOutputStream bout = new ByteArrayOutputStream(); //Hash the password to fit it into the right size (with salt) byte[] salt = new byte[8]; byte[] keyBytes = new byte[32]; //Assume a 256-bit key rand.nextBytes(salt); bout.write(salt); //Write the salt to the stream Digest digest = new SHA256Digest(); //Assume a 256-bit key 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 //Generate the iv and the IvParameter spec byte[] iv = new byte[cipher.getBlockSize()]; rand.nextBytes(iv); IvParameterSpec ivSpec = new IvParameterSpec(iv, 0, bs); //Generate the secret key spec SecretKeySpec keySpec = new SecretKeySpec(keyBytes, cmpDialog.getCipher()); cipher.init(Cipher.ENCRYPT_MODE, keySpec, ivSpec); CipherOutputStream cout = new CipherOutputStream(bout, cipher); //If print the IV into bout bout.write(iv); cout.write(input); //All data has been written so close the streams cout.close(); bout.close(); //Print the output into outputField and Base64-encode if we have to encrypt outputField.setText(new String(Base64.encode(bout.toByteArray()))); } catch (InvalidAlgorithmParameterException ex) { Logger.getLogger(JCrypterFrame.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) //Must not occure { Logger.getLogger(JCrypterFrame.class.getName()).log(Level.SEVERE, null, ex); } catch (InvalidKeyException ex) { Logger.getLogger(JCrypterFrame.class.getName()).log(Level.SEVERE, null, ex); } }