List of usage examples for org.bouncycastle.crypto.digests SHA256Digest SHA256Digest
public SHA256Digest()
From source file:jcrypter.JCrypterFrame.java
License:Apache License
private void encryptWithBypass() //TODO this is only a test, review!! { try //TODO this is only a test, review!! {/*w w w. j a v a2s . c o m*/ PaddedBufferedBlockCipher bc = new PaddedBufferedBlockCipher(new TwofishEngine(), new PKCS7Padding()); //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(); ByteArrayInputStream bin = new ByteArrayInputStream(input); //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); /* * IMPORTANT NOTE: * This implementation bypasses the policy but does only support TWOFISH/ECB */ CipherParameters params = new ParametersWithIV(new KeyParameter(keyBytes), iv); bc.init(true, 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:me.grapebaba.hyperledger.fabric.Crypto.java
License:Apache License
public Crypto(SecurityLevel securityLevel, HashAlgorithm hashAlgorithm) { curveName = SecurityLevel.CURVE_P_256_Size == securityLevel ? "secp256r1" : "secp384r1"; if (hashAlgorithm == HashAlgorithm.SHA2 && securityLevel == SecurityLevel.CURVE_P_384_Size) { throw new RuntimeException("SHA2 not support size 384"); } else if (hashAlgorithm == HashAlgorithm.SHA2 && securityLevel == SecurityLevel.CURVE_P_256_Size) { digest = new SHA256Digest(); } else if (hashAlgorithm == HashAlgorithm.SHA3 && securityLevel == SecurityLevel.CURVE_P_384_Size) { digest = new SHA3Digest(384); } else {// w w w. ja va 2 s .c o m digest = new SHA3Digest(); } }
From source file:net.ripe.rpki.commons.crypto.cms.manifest.ManifestCms.java
License:BSD License
public static byte[] hashContents(byte[] contents) { final Digest digest = new SHA256Digest(); digest.update(contents, 0, contents.length); final byte[] digestValue = new byte[digest.getDigestSize()]; digest.doFinal(digestValue, 0);/* w ww. j av a 2s .co m*/ return digestValue; }
From source file:net.sourceforge.keepassj2me.datasource.HTTPConnectionThread.java
License:Open Source License
/** * Generate key from encryption code by running SHA256 multiple rounds * @param encCode String with code//from ww w .ja va2 s. com * @return String with encrypted code */ private byte[] passwordKeySHA(String encCode) { byte[] encBytes = encCode.getBytes(); for (int i = 0; i < encBytes.length; i++) encBytes[i] -= '0'; byte[] encKey; SHA256Digest md = new SHA256Digest(); encKey = new byte[md.getDigestSize()]; // #ifdef DEBUG System.out.println("encBytes: " + new String(Hex.encode(encBytes))); // #endif md.update(encBytes, 0, encBytes.length); md.doFinal(encKey, 0); for (int i = 0; i < HTTPConnectionThread.PASSWORD_KEY_SHA_ROUNDS - 1; i++) { md.reset(); md.update(encKey, 0, encKey.length); md.doFinal(encKey, 0); } // #ifdef DEBUG System.out.println("encKey: " + new String(Hex.encode(encKey))); // #endif return encKey; }
From source file:net.sourceforge.keepassj2me.importerv3.ImporterV3.java
License:Open Source License
/** * Load a v3 database file, return contents in a new PwManager. * // ww w . j a v a 2 s . c o m * @param infile Existing file to load. * @param password Pass phrase for infile. * @param pRepair (unused) * @return new PwManager container. * * @throws IOException on any file error. * @throws InvalidKeyException on a decryption error, or possible internal bug. * @throws IllegalBlockSizeException on a decryption error, or possible internal bug. * @throws BadPaddingException on a decryption error, or possible internal bug. * @throws NoSuchAlgorithmException on a decryption error, or possible internal bug. * @throws NoSuchPaddingException on a decryption error, or possible internal bug. * @throws InvalidAlgorithmParameterException if error decrypting main file body. * @throws ShortBufferException if error decrypting main file body. */ public PwManager openDatabase(InputStream inStream, String password) throws IOException, InvalidCipherTextException, Exception { PwManager newManager; SHA256Digest md; /** Master key encrypted several times */ byte[] transformedMasterKey; byte[] finalKey; setProgress(5, "Open database"); // #ifdef DEBUG System.out.println("Open database"); // #endif // Load entire file, most of it's encrypted. // InputStream in = new FileInputStream( infile ); byte[] filebuf = new byte[(int) inStream.available()]; inStream.read(filebuf, 0, (int) inStream.available()); inStream.close(); // Parse header (unencrypted) if (filebuf.length < PwDbHeader.BUF_SIZE) throw new IOException("File too short for header"); PwDbHeader hdr = new PwDbHeader(filebuf, 0); if ((hdr.signature1 != PwManager.PWM_DBSIG_1) || (hdr.signature2 != PwManager.PWM_DBSIG_2)) { // #ifdef DEBUG System.out.println("Bad database file signature"); // #endif throw new IOException("Bad database file signature"); } if (hdr.version != PwManager.PWM_DBVER_DW) { // #ifdef DEBUG System.out.println("Bad database file version"); // #endif throw new IOException("Bad database file version"); } newManager = new PwManager(); newManager.setMasterKey(password); // Select algorithm if ((hdr.flags & PwManager.PWM_FLAG_RIJNDAEL) != 0) { // #ifdef DEBUG System.out.println("Algorithm AES"); // #endif newManager.algorithm = PwManager.ALGO_AES; } else if ((hdr.flags & PwManager.PWM_FLAG_TWOFISH) != 0) { // #ifdef DEBUG System.out.println("Algorithm TWOFISH"); // #endif newManager.algorithm = PwManager.ALGO_TWOFISH; } else { throw new IOException("Unknown algorithm."); } if (newManager.algorithm == PwManager.ALGO_TWOFISH) throw new IOException("TwoFish algorithm is not supported"); newManager.numKeyEncRounds = hdr.numKeyEncRounds; // #ifdef DEBUG System.out.println("rounds = " + newManager.numKeyEncRounds); // #endif // testRijndael_JCE(); newManager.name = "KeePass Password Manager"; // Generate transformedMasterKey from masterKey //KeePassMIDlet.logS ("masterSeed2: " + new String(Hex.encode(hdr.masterSeed2))); setProgress(10, "Decrypt key"); transformedMasterKey = transformMasterKey(hdr.masterSeed2, newManager.masterKey, newManager.numKeyEncRounds); // Hash the master password with the salt in the file md = new SHA256Digest(); md.update(hdr.masterSeed, 0, hdr.masterSeed.length); md.update(transformedMasterKey, 0, transformedMasterKey.length); finalKey = new byte[md.getDigestSize()]; md.doFinal(finalKey, 0); setProgress(90, "Decrypt database"); // NI //KeePassMIDlet.logS ("finalKey: " + new String(Hex.encode(finalKey))); // Initialize Rijndael algorithm // Cipher cipher = Cipher.getInstance( "AES/CBC/PKCS5Padding" ); //PaddedBufferedBlockCipher cipher = new PaddedBufferedBlockCipher(new CBCBlockCipher(new AESEngine())); BufferedBlockCipher cipher = new BufferedBlockCipher(new CBCBlockCipher(new AESEngine())); //cipher.init( Cipher.DECRYPT_MODE, new SecretKeySpec( finalKey, "AES" ), new IvParameterSpec( hdr.encryptionIV ) ); cipher.init(false, new ParametersWithIV(new KeyParameter(finalKey), hdr.encryptionIV)); // Decrypt! The first bytes aren't encrypted (that's the header) //int encryptedPartSize = cipher.doFinal( filebuf, PwDbHeader.BUF_SIZE, filebuf.length - PwDbHeader.BUF_SIZE, filebuf, PwDbHeader.BUF_SIZE ); //int encryptedPartSize int paddedEncryptedPartSize = cipher.processBytes(filebuf, PwDbHeader.BUF_SIZE, filebuf.length - PwDbHeader.BUF_SIZE, filebuf, PwDbHeader.BUF_SIZE); int encryptedPartSize = 0; //try { PKCS7Padding padding = new PKCS7Padding(); encryptedPartSize = paddedEncryptedPartSize - padding.padCount(filebuf); //} catch (Exception e) { //} // NI byte[] plainContent = new byte[encryptedPartSize]; System.arraycopy(filebuf, PwDbHeader.BUF_SIZE, plainContent, 0, encryptedPartSize); // #ifdef DEBUG System.out.println("filebuf length: " + filebuf.length); // #endif //System.out.println ("file length: " + filebuf.length); //System.out.println ("plaintext contents length: " + encryptedPartSize); //System.out.println ("plaintext contents:\n" + new String(Hex.encode(plainContent))); //if( pRepair == null ) { //md = MessageDigest.getInstance( "SHA-256" ); md = new SHA256Digest(); md.update(filebuf, PwDbHeader.BUF_SIZE, encryptedPartSize); // md.update( makePad(filebuf) ); md.doFinal(finalKey, 0); if (Util.compare(finalKey, hdr.contentsHash) == false) { //KeePassMIDlet.logS ( "Database file did not decrypt correctly. (checksum code is broken)" ); // #ifdef DEBUG System.out.println("Database file did not decrypt correctly. (checksum code is broken)"); // #endif throw new Exception( "Wrong Password, or Database File Corrupted (database file did not decrypt correctly)"); } // } setProgress(95, "Import groups"); // Import all groups // #ifdef DEBUG System.out.println("Import all groups"); // #endif int pos = PwDbHeader.BUF_SIZE; PwGroup newGrp = new PwGroup(); for (int i = 0; i < hdr.numGroups;) { int fieldType = Types.readShort(filebuf, pos); pos += 2; int fieldSize = Types.readInt(filebuf, pos); pos += 4; if (fieldType == 0xFFFF) { // #ifdef DEBUG System.out.println(newGrp.level + " " + newGrp.name); // #endif // End-Group record. Save group and count it. //newManager.groups.add( newGrp ); newManager.addGroup(newGrp); newGrp = new PwGroup(); i++; } else { readGroupField(newGrp, fieldType, filebuf, pos); } pos += fieldSize; } // fixGroups( groups ); setProgress(97, "Import entries"); // Import all entries // #ifdef DEBUG System.out.println("Import all entries"); // #endif PwEntry newEnt = new PwEntry(); for (int i = 0; i < hdr.numEntries;) { int fieldType = Types.readShort(filebuf, pos); int fieldSize = Types.readInt(filebuf, pos + 2); if (fieldType == 0xFFFF) { // End-Group record. Save group and count it. newManager.addEntry(newEnt); // #ifdef DEBUG System.out.println(newEnt.title); // #endif newEnt = new PwEntry(); i++; } else { readEntryField(newEnt, filebuf, pos); } pos += 2 + 4 + fieldSize; } // Keep the Meta-Info entry separate // #ifdef DEBUG System.out.println("Keep the Meta-Info entry separate"); // #endif for (int i = 0; i < newManager.entries.size(); i++) { PwEntry ent = (PwEntry) newManager.entries.elementAt(i); if (ent.title.equals("Meta-Info") && ent.url.equals("$") && ent.username.equals("SYSTEM")) { newManager.metaInfo = ent; newManager.entries.removeElementAt(i); } } setProgress(100, "Done"); // #ifdef DEBUG System.out.println("Return newManager: " + newManager); // #endif return newManager; }
From source file:net.sourceforge.keepassj2me.importerv3.ImporterV3.java
License:Open Source License
/** * Encrypt the master key a few times to make brute-force key-search harder * @throws NoSuchPaddingException /*from ww w. jav a 2s. c o m*/ * @throws NoSuchAlgorithmException * @throws ShortBufferException */ private byte[] transformMasterKey(byte[] pKeySeed, byte[] pKey, int rounds) /*throws InvalidKeyException, IllegalBlockSizeException, BadPaddingException, NoSuchAlgorithmException, NoSuchPaddingException, ShortBufferException*/ { // #ifdef DEBUG System.out.println("transformMasterKey, rounds=" + rounds); System.out.println("transformMasterKey, pkey=" + new String(Hex.encode(pKey))); // #endif byte[] newKey = new byte[pKey.length]; int i; BufferedBlockCipher cipher = new BufferedBlockCipher(new AESEngine()); cipher.init(true, new KeyParameter(pKeySeed)); int procent = 10; //10% - progress start int step = 5;//% step int roundsByStep = rounds * step / ((90 - procent)); //90% - progress end int count = 0; newKey = pKey; for (i = 0; i < rounds; i++) { cipher.processBytes(newKey, 0, newKey.length, newKey, 0); if (++count == roundsByStep) { count = 0; setProgress(procent += step, null); } } // Hash once with SHA-256 SHA256Digest md = new SHA256Digest(); md.update(newKey, 0, newKey.length); //newKey = md.digest( newKey ); md.doFinal(newKey, 0); return newKey; }
From source file:net.sourceforge.keepassj2me.importerv3.PwManager.java
License:Open Source License
public void setMasterKey(String key) { if (key == null || key.length() == 0) throw new IllegalArgumentException("Key cannot be empty."); SHA256Digest md = new SHA256Digest(); md.update(key.getBytes(), 0, key.getBytes().length); masterKey = new byte[md.getDigestSize()]; md.doFinal(masterKey, 0);// w w w. j a va2 s. c om }
From source file:net.sourceforge.keepassj2me.keydb.KeydbUtil.java
License:Open Source License
/** * hash data from input stream// ww w . j av a 2 s .c o m * @param is input stream * @param size data size or -1 * @return hash * @throws KeydbException */ public static byte[] hash(InputStream is, int size) throws KeydbException { try { byte[] buf; if (size == -1) size = is.available(); switch (size) { case 0: throw new KeydbException(Config.getLocaleString(keys.KD_KEYFILE_EMPTY)); case 32: buf = new byte[32]; is.read(buf, 0, 32); return buf; case 64: buf = new byte[64]; is.read(buf, 0, 64); try { checkHex(buf); return Hex.decode(buf); } catch (Exception e) { return hash(buf); } default: buf = new byte[4096]; SHA256Digest digest = new SHA256Digest(); while (size > 0) { int len = (size > buf.length ? buf.length : size); is.read(buf, 0, len); digest.update(buf, 0, len); size -= len; } ; byte[] hash = new byte[digest.getDigestSize()]; digest.doFinal(hash, 0); return hash; } } catch (IOException e) { throw new KeydbException(Config.getLocaleString(keys.KD_KEYFILE_READ_ERR)); } }
From source file:net.sourceforge.keepassj2me.keydb.KeydbUtil.java
License:Open Source License
/** * Get hash of binary chanks//from w ww . j av a 2 s . c om * @param bufs * @return hash */ public static byte[] hash(byte[][] bufs) { SHA256Digest digest = new SHA256Digest(); for (int i = 0; i < bufs.length; ++i) digest.update(bufs[i], 0, bufs[i].length); byte[] hash = new byte[digest.getDigestSize()]; digest.doFinal(hash, 0); return hash; }
From source file:net.sourceforge.keepassj2me.keydb.KeydbUtil.java
License:Open Source License
/** * Get hash of buffer part/*from w ww . j a v a2s.co m*/ * @param buf * @param offset * @param length * @return hash */ public static byte[] hash(byte[] buf, int offset, int length) { SHA256Digest digest = new SHA256Digest(); digest.update(buf, offset, length); byte[] hash = new byte[digest.getDigestSize()]; digest.doFinal(hash, 0); return hash; }