List of usage examples for org.bouncycastle.crypto.generators SCrypt generate
public static byte[] generate(byte[] P, byte[] S, int N, int r, int p, int dkLen)
From source file:com.bitsofproof.supernode.api.SerializedWallet.java
License:Apache License
public void writeWallet(OutputStream output, String passphrase) throws ValidationException { try {//from www. j a v a 2s.co m output.write(MAGIC.getBytes("US-ASCII")); byte[] iv = new byte[16]; rnd.nextBytes(iv); output.write(iv); byte[] derived = SCrypt.generate(passphrase.getBytes("UTF-8"), iv, 16384, 8, 8, 32); SecretKeySpec keyspec = new SecretKeySpec(derived, "AES"); Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding", "BC"); cipher.init(Cipher.ENCRYPT_MODE, keyspec, new IvParameterSpec(iv)); CipherOutputStream cip = new CipherOutputStream(output, cipher); GZIPOutputStream zip = new GZIPOutputStream(cip); BCSAPIMessage.Wallet.Builder builder = BCSAPIMessage.Wallet.newBuilder(); builder.setBcsapiversion(1); for (WalletKey key : keys) { BCSAPIMessage.Wallet.Key.Builder kb = BCSAPIMessage.Wallet.Key.newBuilder(); kb.setKey(key.key); kb.setNextSequence(key.nextSequence); if (key.name != null) { kb.setName(key.name); } if (key.created != 0) { kb.setCreated(key.created); } builder.addKeys(kb.build()); } for (Transaction t : transactions) { builder.addTransactions(t.toProtobuf()); } for (Map.Entry<String, String> e : addresses.entrySet()) { BCSAPIMessage.Wallet.PublicAddress.Builder pa = BCSAPIMessage.Wallet.PublicAddress.newBuilder(); pa.setName(e.getKey()); pa.setAddress(e.getValue()); builder.addPublicAddresses(pa.build()); } builder.build().writeTo(zip); zip.finish(); zip.flush(); cip.close(); } catch (UnsupportedEncodingException e) { } catch (IOException e) { throw new ValidationException(e); } catch (NoSuchAlgorithmException e) { throw new ValidationException(e); } catch (NoSuchProviderException e) { throw new ValidationException(e); } catch (NoSuchPaddingException e) { throw new ValidationException(e); } catch (InvalidKeyException e) { throw new ValidationException(e); } catch (InvalidAlgorithmParameterException e) { throw new ValidationException(e); } }
From source file:com.bitsofproof.supernode.api.SerializedWallet.java
License:Apache License
public static SerializedWallet readWallet(InputStream input, String passphrase) throws ValidationException { SerializedWallet wallet = new SerializedWallet(); try {/*from w w w . j av a 2s .co m*/ byte[] derived; byte[] magic = new byte[MAGIC.getBytes("US-ASCII").length]; input.read(magic); if (!Arrays.equals(magic, MAGIC.getBytes("US-ASCII"))) { throw new ValidationException("Not a wallet"); } byte[] iv = new byte[16]; input.read(iv); derived = SCrypt.generate(passphrase.getBytes("UTF-8"), iv, 16384, 8, 8, 32); SecretKeySpec keyspec = new SecretKeySpec(derived, "AES"); Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding", "BC"); cipher.init(Cipher.DECRYPT_MODE, keyspec, new IvParameterSpec(iv)); CipherInputStream cis = new CipherInputStream(input, cipher); GZIPInputStream unzip = new GZIPInputStream(cis); BCSAPIMessage.Wallet walletMessage = BCSAPIMessage.Wallet.parseFrom(unzip); wallet.keys = new ArrayList<WalletKey>(); for (BCSAPIMessage.Wallet.Key k : walletMessage.getKeysList()) { WalletKey key = new WalletKey(); key.key = k.getKey(); key.nextSequence = k.getNextSequence(); if (k.hasName()) { key.name = k.getName(); } if (k.hasCreated()) { key.created = k.getCreated(); } wallet.keys.add(key); } wallet.transactions = new ArrayList<Transaction>(); for (BCSAPIMessage.Transaction t : walletMessage.getTransactionsList()) { Transaction transaction = Transaction.fromProtobuf(t); transaction.computeHash(); wallet.addTransaction(transaction); } wallet.addresses = new HashMap<String, String>(); for (BCSAPIMessage.Wallet.PublicAddress p : walletMessage.getPublicAddressesList()) { wallet.addresses.put(p.getName(), p.getAddress()); } } catch (UnsupportedEncodingException e) { } catch (NoSuchAlgorithmException e) { throw new ValidationException(e); } catch (NoSuchProviderException e) { throw new ValidationException(e); } catch (NoSuchPaddingException e) { throw new ValidationException(e); } catch (InvalidKeyException e) { throw new ValidationException(e); } catch (IOException e) { throw new ValidationException(e); } catch (InvalidAlgorithmParameterException e) { throw new ValidationException(e); } return wallet; }
From source file:com.bitsofproof.supernode.common.ExtendedKey.java
License:Apache License
public static ExtendedKey createFromPassphrase(String passphrase, byte[] encrypted) throws ValidationException { try {//from ww w. j a v a2s. c o m byte[] key = SCrypt.generate(passphrase.getBytes("UTF-8"), BITCOIN_SEED, 16384, 8, 8, 32); SecretKeySpec keyspec = new SecretKeySpec(key, "AES"); if (encrypted.length == 32) { // asssume encrypted is seed Cipher cipher = Cipher.getInstance("AES/ECB/NoPadding", "BC"); cipher.init(Cipher.DECRYPT_MODE, keyspec); return create(cipher.doFinal(encrypted)); } else { // assume encrypted serialization of a key Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding", "BC"); byte[] iv = Arrays.copyOfRange(encrypted, 0, 16); byte[] data = Arrays.copyOfRange(encrypted, 16, encrypted.length); cipher.init(Cipher.DECRYPT_MODE, keyspec, new IvParameterSpec(iv)); return ExtendedKey.parse(new String(cipher.doFinal(data))); } } catch (UnsupportedEncodingException e) { throw new ValidationException(e); } catch (IllegalBlockSizeException e) { throw new ValidationException(e); } catch (BadPaddingException e) { throw new ValidationException(e); } catch (InvalidKeyException e) { throw new ValidationException(e); } catch (NoSuchAlgorithmException e) { throw new ValidationException(e); } catch (NoSuchProviderException e) { throw new ValidationException(e); } catch (NoSuchPaddingException e) { throw new ValidationException(e); } catch (InvalidAlgorithmParameterException e) { throw new ValidationException(e); } }
From source file:com.bitsofproof.supernode.common.ExtendedKey.java
License:Apache License
public byte[] encrypt(String passphrase, boolean production) throws ValidationException { try {//from w w w.ja v a2 s . co m byte[] key = SCrypt.generate(passphrase.getBytes("UTF-8"), BITCOIN_SEED, 16384, 8, 8, 32); SecretKeySpec keyspec = new SecretKeySpec(key, "AES"); Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding", "BC"); cipher.init(Cipher.ENCRYPT_MODE, keyspec); byte[] iv = cipher.getIV(); byte[] c = cipher.doFinal(serialize(production).getBytes()); byte[] result = new byte[iv.length + c.length]; System.arraycopy(iv, 0, result, 0, iv.length); System.arraycopy(c, 0, result, iv.length, c.length); return result; } catch (UnsupportedEncodingException | NoSuchAlgorithmException | NoSuchProviderException | NoSuchPaddingException | InvalidKeyException | IllegalBlockSizeException | BadPaddingException e) { throw new ValidationException(e); } }
From source file:com.bitsofproof.supernode.wallet.EncryptedHDRoot.java
License:Apache License
public static ExtendedKey decrypt(String ws, String passphrase) throws ValidationException { byte[] raw = ByteUtils.fromBase58WithChecksum(ws); byte[] magic = Arrays.copyOf(raw, 3); byte[] encryptedSeed; int N = 1 << 14; int r = 16;//w w w . j av a 2 s .co m int p = 16; if (Arrays.equals(magic, encrypted16l)) { encryptedSeed = Arrays.copyOfRange(raw, 9, 16 + 9); r = p = 8; } else if (Arrays.equals(magic, encrypted16m)) { encryptedSeed = Arrays.copyOfRange(raw, 9, 16 + 9); N = 1 << 16; } else if (Arrays.equals(magic, encrypted16h)) { encryptedSeed = Arrays.copyOfRange(raw, 9, 16 + 9); N = 1 << 18; } else if (Arrays.equals(magic, encrypted32l)) { encryptedSeed = Arrays.copyOfRange(raw, 9, 32 + 9); r = p = 8; } else if (Arrays.equals(magic, encrypted32m)) { encryptedSeed = Arrays.copyOfRange(raw, 9, 32 + 9); N = 1 << 16; } else if (Arrays.equals(magic, encrypted32h)) { encryptedSeed = Arrays.copyOfRange(raw, 9, 32 + 9); N = 1 << 18; } else if (Arrays.equals(magic, encrypted64l)) { encryptedSeed = Arrays.copyOfRange(raw, 9, 64 + 9); r = p = 8; } else if (Arrays.equals(magic, encrypted64m)) { encryptedSeed = Arrays.copyOfRange(raw, 9, 64 + 9); N = 1 << 16; } else if (Arrays.equals(magic, encrypted64h)) { encryptedSeed = Arrays.copyOfRange(raw, 9, 64 + 9); N = 1 << 18; } else { throw new ValidationException("Not an encoded HD root"); } byte salt[] = Arrays.copyOf(raw, 9); Mac mac; try { mac = Mac.getInstance("HmacSHA512", "BC"); SecretKey seedkey = new SecretKeySpec(salt, "HmacSHA512"); mac.init(seedkey); byte[] preH = mac.doFinal(passphrase.getBytes("UTF-8")); byte[] strongH = SCrypt.generate(preH, preH, N, r, p, 64); seedkey = new SecretKeySpec(passphrase.getBytes("UTF-8"), "HmacSHA512"); mac.init(seedkey); byte[] postH = mac.doFinal(salt); byte[] H = SCrypt.generate(postH, strongH, 1 << 10, 1, 1, encryptedSeed.length + 32); byte[] X = Arrays.copyOf(H, encryptedSeed.length); SecretKeySpec keyspec = new SecretKeySpec( Arrays.copyOfRange(H, encryptedSeed.length, encryptedSeed.length + 32), "AES"); Cipher cipher = Cipher.getInstance("AES/ECB/NoPadding", "BC"); cipher.init(Cipher.DECRYPT_MODE, keyspec); byte[] seed = cipher.doFinal(encryptedSeed); for (int i = 0; i < encryptedSeed.length; ++i) { seed[i] ^= X[i]; } ExtendedKey key = ExtendedKey.create(seed); if (!Arrays.equals(Arrays.copyOf(Hash.hash(key.getMaster().getPrivate()), 4), Arrays.copyOfRange(raw, 5, 9))) { throw new ValidationException("HD root checksum error"); } return key; } catch (NoSuchAlgorithmException | NoSuchProviderException | InvalidKeyException | UnsupportedEncodingException | NoSuchPaddingException | IllegalBlockSizeException | BadPaddingException e) { throw new ValidationException(e); } }
From source file:com.bitsofproof.supernode.wallet.EncryptedHDRoot.java
License:Apache License
public static String encrypt(byte[] seed, Date birth, String passphrase, ScryptDifficulty scryptDifficulty) throws ValidationException { if (seed == null || (seed.length != 16 && seed.length != 32 && seed.length != 64)) { throw new ValidationException("Seed must be 16, 32 or 64 bytes"); }//from w w w . j a v a2s .co m int weeks = (int) ((birth.getTime() - new GregorianCalendar(2013, Calendar.JANUARY, 1).getTime().getTime()) / (7 * 24 * 60 * 60 * 1000L)); ExtendedKey key = ExtendedKey.create(seed); byte raw[]; byte[] salt = new byte[9]; if (seed.length == 16) { raw = new byte[25]; System.arraycopy(encrypted16, 0, salt, 0, 3); } else if (seed.length == 32) { raw = new byte[41]; System.arraycopy(encrypted32, 0, salt, 0, 3); } else { raw = new byte[73]; System.arraycopy(encrypted64, 0, salt, 0, 3); } salt[2] += scryptDifficulty.ordinal(); salt[3] = (byte) (weeks & 0xff); salt[4] = (byte) ((weeks >>> 8) & 0xff); System.arraycopy(Hash.hash(key.getMaster().getPrivate()), 0, salt, 5, 4); System.arraycopy(salt, 0, raw, 0, 9); int N = (1 << 14) << (scryptDifficulty.ordinal() * 2); int r = scryptDifficulty == ScryptDifficulty.LOW ? 8 : 16; int p = scryptDifficulty == ScryptDifficulty.LOW ? 8 : 16; Mac mac; try { mac = Mac.getInstance("HmacSHA512", "BC"); SecretKey seedkey = new SecretKeySpec(salt, "HmacSHA512"); mac.init(seedkey); byte[] preH = mac.doFinal(passphrase.getBytes("UTF-8")); byte[] strongH = SCrypt.generate(preH, preH, N, r, p, 64); seedkey = new SecretKeySpec(passphrase.getBytes("UTF-8"), "HmacSHA512"); mac.init(seedkey); byte[] postH = mac.doFinal(salt); byte[] H = SCrypt.generate(postH, strongH, 1 << 10, 1, 1, seed.length + 32); byte[] X = Arrays.copyOf(H, seed.length); for (int i = 0; i < seed.length; ++i) { X[i] ^= seed[i]; } SecretKeySpec keyspec = new SecretKeySpec(Arrays.copyOfRange(H, seed.length, seed.length + 32), "AES"); Cipher cipher = Cipher.getInstance("AES/ECB/NoPadding", "BC"); cipher.init(Cipher.ENCRYPT_MODE, keyspec); System.arraycopy(cipher.doFinal(X), 0, raw, 9, seed.length); } catch (NoSuchAlgorithmException | NoSuchProviderException | InvalidKeyException | UnsupportedEncodingException | NoSuchPaddingException | IllegalBlockSizeException | BadPaddingException e) { throw new ValidationException(e); } return ByteUtils.toBase58WithChecksum(raw); }
From source file:com.distrimind.util.crypto.PasswordHashType.java
License:Open Source License
@SuppressWarnings("fallthrough") byte[] hash(byte[] data, int off, int len, byte[] salt, byte cost, byte hashLength) throws NoSuchAlgorithmException, InvalidKeySpecException, NoSuchProviderException { CodeProvider.encureProviderLoaded(codeProvider); if (cost < 4 || cost > 31) throw new IllegalArgumentException("cost must be greater or equals than 4 and lower or equals than 31"); if (defaultOf != null) return defaultOf.hash(data, off, len, salt, cost, hashLength); if (OSVersion.getCurrentOSVersion() != null && OSVersion.getCurrentOSVersion().getOS() == OS.MAC_OS_X) { if (this == PBKDF2WithHMacSHA2_256) return PasswordHashType.BC_FIPS_PBKFD2WithHMacSHA2_256.hash(data, off, len, salt, cost, hashLength); if (this == PBKDF2WithHMacSHA2_384) return PasswordHashType.BC_FIPS_PBKFD2WithHMacSHA2_384.hash(data, off, len, salt, cost, hashLength); if (this == PBKDF2WithHMacSHA2_512) return PasswordHashType.BC_FIPS_PBKFD2WithHMacSHA2_512.hash(data, off, len, salt, cost, hashLength); }/*from w ww. j a v a2 s . c om*/ int scryptN = 1 << 18; int iterations = 1 << (cost - 1); switch (this) { case DEFAULT: case PBKDF2WithHmacSHA1: case PBKDF2WithHMacSHA2_256: case PBKDF2WithHMacSHA2_384: case PBKDF2WithHMacSHA2_512: { int size = len / 2; char[] password = new char[size + len % 2]; for (int i = 0; i < size; i++) { password[i] = (char) ((data[off + i * 2] & 0xFF) & ((data[off + i * 2 + 1] << 8) & 0xFF)); } if (size < password.length) password[size] = (char) (data[off + size * 2] & 0xFF); PBEKeySpec spec = new PBEKeySpec(password, salt, iterations, (hashLength) * 8); SecretKeyFactory skf = SecretKeyFactory.getInstance(algorithmName, codeProvider.checkProviderWithCurrentOS().name()); return skf.generateSecret(spec).getEncoded(); } case GNU_PBKDF2WithHMacSHA2_256: case GNU_PBKDF2WithHMacSHA2_384: case GNU_PBKDF2WithHMacSHA2_512: case GNU_PBKDF2WithHMacWhirlpool: case GNU_PBKDF2WithHmacSHA1: { int size = len / 2; char[] password = new char[size + len % 2]; for (int i = 0; i < size; i++) { password[i] = (char) ((data[off + i * 2] & 0xFF) & ((data[off + i * 2 + 1] << 8) & 0xFF)); } if (size < password.length) password[size] = (char) (data[off + size * 2] & 0xFF); Object spec = GnuFunctions.PBEKeySpecGetInstance(password, salt, iterations, (hashLength)); Object skf = GnuFunctions.secretKeyFactoryGetInstance(algorithmName); return GnuFunctions.keyGetEncoded(GnuFunctions.secretKeyFactoryGenerateSecret(skf, spec)); } case BC_BCRYPT: { byte[] passwordb; if (off != 0 || len != data.length) { passwordb = new byte[len]; System.arraycopy(data, off, passwordb, 0, len); } else passwordb = data; salt = uniformizeSaltLength(salt, 16); return BCrypt.generate(passwordb, salt, cost); } case BC_FIPS_PBKFD2WithHMacSHA2_256: case BC_FIPS_PBKFD2WithHMacSHA2_384: case BC_FIPS_PBKFD2WithHMacSHA2_512: { PasswordBasedDeriver<org.bouncycastle.crypto.fips.FipsPBKD.Parameters> deriver = new FipsPBKD.DeriverFactory() .createDeriver(FipsPBKD.PBKDF2.using(fipsDigestAlgorithm, data).withIterationCount(iterations) .withSalt(salt)); return deriver.deriveKey(PasswordBasedDeriver.KeyType.CIPHER, ((hashLength * 8) + 7) / 8); } case BC_SCRYPT_FOR_LOGIN: scryptN = 1 << 13; case BC_SCRYPT_FOR_DATAENCRYPTION: { byte[] d; if (len == data.length && off == 0) d = data; else { d = new byte[len]; System.arraycopy(data, off, d, 0, len); } return SCrypt.generate(d, salt, scryptN, 8, 1, hashLength); } default: break; } throw new InternalError(); }
From source file:com.distrimind.util.crypto.PasswordHashType.java
License:Open Source License
byte[] hash(char[] password, byte[] salt, byte cost, byte hashLength) throws NoSuchAlgorithmException, InvalidKeySpecException, NoSuchProviderException { CodeProvider.encureProviderLoaded(codeProvider); if (cost < 4 || cost > 31) throw new IllegalArgumentException("cost must be greater or equals than 4 and lower or equals than 31"); if (defaultOf != null) return defaultOf.hash(password, salt, cost, hashLength); if (OSVersion.getCurrentOSVersion() != null && OSVersion.getCurrentOSVersion().getOS() == OS.MAC_OS_X) { if (this == PBKDF2WithHMacSHA2_256) return PasswordHashType.BC_FIPS_PBKFD2WithHMacSHA2_256.hash(password, salt, cost, hashLength); if (this == PBKDF2WithHMacSHA2_384) return PasswordHashType.BC_FIPS_PBKFD2WithHMacSHA2_384.hash(password, salt, cost, hashLength); if (this == PBKDF2WithHMacSHA2_512) return PasswordHashType.BC_FIPS_PBKFD2WithHMacSHA2_512.hash(password, salt, cost, hashLength); }//from www. ja va 2s . com int iterations = 1 << (cost - 1); int scryptN = 1 << 18; switch (this) { case DEFAULT: case PBKDF2WithHmacSHA1: case PBKDF2WithHMacSHA2_256: case PBKDF2WithHMacSHA2_384: case PBKDF2WithHMacSHA2_512: { PBEKeySpec spec = new PBEKeySpec(password, salt, iterations, (hashLength) * 8); SecretKeyFactory skf = SecretKeyFactory.getInstance(algorithmName, codeProvider.checkProviderWithCurrentOS().name()); return skf.generateSecret(spec).getEncoded(); } case GNU_PBKDF2WithHMacSHA2_256: case GNU_PBKDF2WithHMacSHA2_384: case GNU_PBKDF2WithHMacSHA2_512: case GNU_PBKDF2WithHMacWhirlpool: case GNU_PBKDF2WithHmacSHA1: { Object spec = GnuFunctions.PBEKeySpecGetInstance(password, salt, iterations, hashLength); Object skf = GnuFunctions.secretKeyFactoryGetInstance(algorithmName); return GnuFunctions.keyGetEncoded(GnuFunctions.secretKeyFactoryGenerateSecret(skf, spec)); } case BC_BCRYPT: { salt = uniformizeSaltLength(salt, 16); return BCrypt.generate(BCrypt.passwordToByteArray(password), salt, cost); } case BC_FIPS_PBKFD2WithHMacSHA2_256: case BC_FIPS_PBKFD2WithHMacSHA2_384: case BC_FIPS_PBKFD2WithHMacSHA2_512: { PasswordBasedDeriver<org.bouncycastle.crypto.fips.FipsPBKD.Parameters> deriver = new FipsPBKD.DeriverFactory() .createDeriver( FipsPBKD.PBKDF2.using(fipsDigestAlgorithm, PasswordConverter.UTF8.convert(password)) .withIterationCount(iterations).withSalt(salt)); return deriver.deriveKey(PasswordBasedDeriver.KeyType.CIPHER, ((hashLength * 8) + 7) / 8); } case BC_SCRYPT_FOR_LOGIN: scryptN = 1 << 13; case BC_SCRYPT_FOR_DATAENCRYPTION: byte[] passwordb = new byte[password.length * 2]; for (int i = 0; i < password.length; i++) { passwordb[i * 2] = (byte) (password[i] & 0xFF); passwordb[i * 2 + 1] = (byte) ((password[i] >> 8 & 0xFFFF) & 0xFF); } return SCrypt.generate(passwordb, salt, scryptN, 8, 1, hashLength); } throw new InternalError(); }
From source file:org.apache.openmeetings.util.crypt.SCryptImplementation.java
License:Apache License
private static String hash(String str, byte[] salt) { byte[] dk = SCrypt.generate(str.getBytes(UTF_8), salt, COST, 8, 8, KEY_LENGTH); return Base64.encodeBase64String(dk); }
From source file:org.bunkr.core.descriptor.ScryptDescriptor.java
License:Open Source License
@Override public Inventory readInventoryFromBytes(byte[] source, UserSecurityProvider usp) throws BaseBunkrException { try {/*from ww w . ja va2 s . co m*/ // generate the encryption key and iv using scrypt byte[] data = SCrypt.generate(usp.getHashedPassword(), this.scryptSalt, this.scryptN, this.scryptR, this.scryptP, this.encryptionAlgorithm.keyByteLength + this.encryptionAlgorithm.ivByteLength); // pull key and iv out of the data byte[] key = Arrays.copyOfRange(data, 0, this.encryptionAlgorithm.keyByteLength); byte[] iv = Arrays.copyOfRange(data, this.encryptionAlgorithm.keyByteLength, data.length); byte[] decryptedInv = SimpleAES.decrypt(this.encryptionAlgorithm, source, key, iv); Arrays.fill(data, (byte) 0); Arrays.fill(key, (byte) 0); Arrays.fill(iv, (byte) 0); return InventoryJSON.decode(new String(decryptedInv)); } catch (CryptoException e) { throw new BaseBunkrException(e); } }