List of usage examples for java.security SecureRandom nextBytes
@Override public void nextBytes(byte[] bytes)
From source file:graphene.util.crypto.PasswordHash.java
/** * Returns a salted PBKDF2 hash of the password. * /*from w w w . j a v a 2 s .c om*/ * @param password * the password to hash * @return a salted PBKDF2 hash of the password */ public String createHash(final char[] password) throws NoSuchAlgorithmException, InvalidKeySpecException { // Generate a random salt final SecureRandom random = new SecureRandom(); final byte[] salt = new byte[SALT_BYTE_SIZE]; random.nextBytes(salt); // Hash the password final byte[] hash = pbkdf2(password, salt, PBKDF2_ITERATIONS, HASH_BYTE_SIZE); // format iterations:salt:hash return PBKDF2_ITERATIONS + ":" + toEncoding(salt) + ":" + toEncoding(hash); }
From source file:com.filelocker.encryption.AES_Encryption.java
/** * this must be called after creating the initial Crypto object. It creates a salt of SALT_LEN bytes * and generates the salt bytes using secureRandom(). The encryption secret key is created * along with the initialization vectory. The member variable vEcipher is created to be used * by the class later on when either creating a CipherOutputStream, or encrypting a buffer * to be written to disk./* w w w . ja v a2 s .c om*/ * * @throws NoSuchAlgorithmException * @throws InvalidKeySpecException * @throws NoSuchPaddingException * @throws InvalidParameterSpecException * @throws IllegalBlockSizeException * @throws BadPaddingException * @throws UnsupportedEncodingException * @throws InvalidKeyException */ public void setupEncrypt() throws NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException, InvalidParameterSpecException, IllegalBlockSizeException, BadPaddingException, UnsupportedEncodingException, InvalidKeyException { SecretKeyFactory factory = null; SecretKey tmp = null; // crate secureRandom salt and store as member var for later use vSalt = new byte[SALT_LEN]; SecureRandom rnd = new SecureRandom(); rnd.nextBytes(vSalt); Db("generated salt :" + Hex.encodeHexString(vSalt)); factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1"); /* Derive the key, given password and salt. * * in order to do 256 bit crypto, you have to muck with the files for Java's "unlimted security" * The end user must also install them (not compiled in) so beware. * see here: http://www.javamex.com/tutorials/cryptography/unrestricted_policy_files.shtml */ KeySpec spec = new PBEKeySpec(vPassword.toCharArray(), vSalt, ITERATIONS, KEYLEN_BITS); tmp = factory.generateSecret(spec); SecretKey secret = new SecretKeySpec(tmp.getEncoded(), "AES"); /* Create the Encryption cipher object and store as a member variable */ vEcipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); vEcipher.init(Cipher.ENCRYPT_MODE, secret); AlgorithmParameters params = vEcipher.getParameters(); // get the initialization vectory and store as member var vInitVec = params.getParameterSpec(IvParameterSpec.class).getIV(); Db("vInitVec is :" + Hex.encodeHexString(vInitVec)); }
From source file:de.rrze.idmone.utils.jidgen.random.RandomFactory.java
/** * Create a two pseudo random generator by utilizing the * <em>SecureRandom</em> class provided by SUN. Uses a two step procedure * for feeding the generator seed with two separate SecureRandom instances. * /*from w w w .j a v a2 s. c o m*/ * @see http://java.sun.com/j2se/1.4.2/docs/api/java/security/SecureRandom.html * * @param algorithm * The algorithm used for creating the pseudo random generator * @param provider * the provider identifier * @return a seeded <em>SecureRandom</em> * @throws NoSuchAlgorithmException * @throws NoSuchProviderException */ private SecureRandom initSecureRandom(String algorithm, String provider) throws NoSuchAlgorithmException, NoSuchProviderException { logger.debug(Messages.getString("RandomFactory.INIT") + algorithm + " : " + provider); if (provider == null) provider = PROVIDER_DEFAULT; // Create a secure random number generator SecureRandom sr = SecureRandom.getInstance(algorithm, provider); // Get 1024 random bits byte[] bytes = new byte[1024 / 8]; sr.nextBytes(bytes); // Create two secure number generators with the same seed int seedByteCount = 10; byte[] seed = sr.generateSeed(seedByteCount); sr = SecureRandom.getInstance(algorithm, provider); sr.setSeed(seed); SecureRandom sr2 = SecureRandom.getInstance(algorithm, provider); sr2.setSeed(seed); return sr2; }
From source file:ropes.Crypto.java
/** * this must be called after creating the initial Crypto object. It creates a salt of SALT_LEN bytes * and generates the salt bytes using secureRandom(). The encryption secret key is created * along with the initialization vectory. The member variable mEcipher is created to be used * by the class later on when either creating a CipherOutputStream, or encrypting a buffer * to be written to disk.//from www . j a va 2 s .c o m * * @throws NoSuchAlgorithmException * @throws InvalidKeySpecException * @throws NoSuchPaddingException * @throws InvalidParameterSpecException * @throws IllegalBlockSizeException * @throws BadPaddingException * @throws UnsupportedEncodingException * @throws InvalidKeyException */ public void setupEncrypt() { try { SecretKeyFactory factory = null; SecretKey tmp = null; // crate secureRandom salt and store as member var for later use mSalt = new byte[SALT_LEN]; SecureRandom rnd = new SecureRandom(); rnd.nextBytes(mSalt); Db("generated salt :" + Hex.encodeHexString(mSalt)); factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1"); /* Derive the key, given password and salt. * * in order to do 256 bit crypto, you have to muck with the files for Java's "unlimted security" * The end user must also install them (not compiled in) so beware. * see here: http://www.javamex.com/tutorials/cryptography/unrestricted_policy_files.shtml */ KeySpec spec = new PBEKeySpec(mPassword.toCharArray(), mSalt, ITERATIONS, KEYLEN_BITS); tmp = factory.generateSecret(spec); SecretKey secret = new SecretKeySpec(tmp.getEncoded(), "AES"); /* Create the Encryption cipher object and store as a member variable */ mEcipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); mEcipher.init(Cipher.ENCRYPT_MODE, secret); AlgorithmParameters params = mEcipher.getParameters(); // get the initialization vectory and store as member var mInitVec = params.getParameterSpec(IvParameterSpec.class).getIV(); Db("mInitVec is :" + Hex.encodeHexString(mInitVec)); } catch (NoSuchAlgorithmException ex) { Logger.getLogger(Crypto.class.getName()).log(Level.SEVERE, null, ex); } catch (InvalidKeySpecException ex) { Logger.getLogger(Crypto.class.getName()).log(Level.SEVERE, null, ex); } catch (NoSuchPaddingException ex) { Logger.getLogger(Crypto.class.getName()).log(Level.SEVERE, null, ex); } catch (InvalidKeyException ex) { Logger.getLogger(Crypto.class.getName()).log(Level.SEVERE, null, ex); } catch (InvalidParameterSpecException ex) { Logger.getLogger(Crypto.class.getName()).log(Level.SEVERE, null, ex); } }
From source file:de.rrze.idmone.utils.jpwgen.RandomFactory.java
/** * Create a two pseudo random generator by utilizing the * <em>SecureRandom</em> class provided by SUN. Uses a two step procedure * for feeding the generator seed with two separate SecureRandom instances. * //from www . ja va 2 s.c om * @see http * ://java.sun.com/j2se/1.4.2/docs/api/java/security/SecureRandom.html * * @param algorithm * The algorithm used for creating the pseudo random generator * @param provider * the provider identifier * @return a seeded <em>SecureRandom</em> * @throws NoSuchAlgorithmException * @throws NoSuchProviderException */ private SecureRandom initSecureRandom(String algorithm, String provider) throws NoSuchAlgorithmException, NoSuchProviderException { logger.debug("Initializing random with: " + algorithm + " : " + provider); if (provider == null) provider = PROVIDER_DEFAULT; // Create a secure random number generator SecureRandom sr = SecureRandom.getInstance(algorithm, provider); // Get 1024 random bits byte[] bytes = new byte[1024 / 8]; sr.nextBytes(bytes); // Create two secure number generators with the same seed int seedByteCount = 10; byte[] seed = sr.generateSeed(seedByteCount); sr = SecureRandom.getInstance(algorithm, provider); sr.setSeed(seed); SecureRandom sr2 = SecureRandom.getInstance(algorithm, provider); sr2.setSeed(seed); return sr2; }
From source file:com.intel.chimera.CryptoCodecTest.java
private void cryptoCodecTestForInputStream(int count, String encCodecClass, String decCodecClass, byte[] iv) throws IOException { CryptoCodec encCodec = null;//from w w w . j ava 2 s . c o m try { encCodec = (CryptoCodec) ReflectionUtils.newInstance(ReflectionUtils.getClassByName(encCodecClass), props); } catch (ClassNotFoundException cnfe) { throw new IOException("Illegal crypto codec!"); } LOG.info("Created a Codec object of type: " + encCodecClass); // Generate data SecureRandom random = new SecureRandom(); byte[] originalData = new byte[count]; byte[] decryptedData = new byte[count]; random.nextBytes(originalData); LOG.info("Generated " + count + " records"); // Encrypt data ByteArrayOutputStream encryptedData = new ByteArrayOutputStream(); CryptoOutputStream out = new CryptoOutputStream(encryptedData, encCodec, bufferSize, key, iv); out.write(originalData, 0, originalData.length); out.flush(); out.close(); LOG.info("Finished encrypting data"); CryptoCodec decCodec = null; try { decCodec = (CryptoCodec) ReflectionUtils.newInstance(ReflectionUtils.getClassByName(decCodecClass), props); } catch (ClassNotFoundException cnfe) { throw new IOException("Illegal crypto codec!"); } LOG.info("Created a Codec object of type: " + decCodecClass); // Decrypt data CryptoInputStream in = new CryptoInputStream(new ByteArrayInputStream(encryptedData.toByteArray()), decCodec, bufferSize, key, iv); // Check int remainingToRead = count; int offset = 0; while (remainingToRead > 0) { int n = in.read(decryptedData, offset, decryptedData.length - offset); if (n >= 0) { remainingToRead -= n; offset += n; } } Assert.assertArrayEquals("originalData and decryptedData not equal", originalData, decryptedData); // Decrypt data byte-at-a-time in = new CryptoInputStream(new ByteArrayInputStream(encryptedData.toByteArray()), decCodec, bufferSize, key, iv); // Check DataInputStream originalIn = new DataInputStream( new BufferedInputStream(new ByteArrayInputStream(originalData))); int expected; do { expected = originalIn.read(); Assert.assertEquals("Decrypted stream read by byte does not match", expected, in.read()); } while (expected != -1); LOG.info("SUCCESS! Completed checking " + count + " records"); }
From source file:com.intel.chimera.CryptoCodecTest.java
private void cryptoCodecTestForReadableByteChannel(int count, String encCodecClass, String decCodecClass, byte[] iv) throws IOException { CryptoCodec encCodec = null;/*w ww . ja va2s . co m*/ try { encCodec = (CryptoCodec) ReflectionUtils.newInstance(ReflectionUtils.getClassByName(encCodecClass), props); } catch (ClassNotFoundException cnfe) { throw new IOException("Illegal crypto codec!"); } LOG.info("Created a Codec object of type: " + encCodecClass); // Generate data SecureRandom random = new SecureRandom(); byte[] originalData = new byte[count]; byte[] decryptedData = new byte[count]; random.nextBytes(originalData); LOG.info("Generated " + count + " records"); // Encrypt data ByteArrayOutputStream encryptedData = new ByteArrayOutputStream(); CryptoOutputStream out = new CryptoOutputStream(Channels.newChannel(encryptedData), encCodec, bufferSize, key, iv); out.write(originalData, 0, originalData.length); out.flush(); out.close(); LOG.info("Finished encrypting data"); CryptoCodec decCodec = null; try { decCodec = (CryptoCodec) ReflectionUtils.newInstance(ReflectionUtils.getClassByName(decCodecClass), props); } catch (ClassNotFoundException cnfe) { throw new IOException("Illegal crypto codec!"); } LOG.info("Created a Codec object of type: " + decCodecClass); // Decrypt data CryptoInputStream in = new CryptoInputStream( Channels.newChannel(new ByteArrayInputStream(encryptedData.toByteArray())), decCodec, bufferSize, key, iv); // Check int remainingToRead = count; int offset = 0; while (remainingToRead > 0) { int n = in.read(decryptedData, offset, decryptedData.length - offset); if (n >= 0) { remainingToRead -= n; offset += n; } } Assert.assertArrayEquals("originalData and decryptedData not equal", originalData, decryptedData); // Decrypt data byte-at-a-time in = new CryptoInputStream(Channels.newChannel(new ByteArrayInputStream(encryptedData.toByteArray())), decCodec, bufferSize, key, iv); // Check DataInputStream originalIn = new DataInputStream( new BufferedInputStream(new ByteArrayInputStream(originalData))); int expected; do { expected = originalIn.read(); Assert.assertEquals("Decrypted stream read by byte does not match", expected, in.read()); } while (expected != -1); LOG.info("SUCCESS! Completed checking " + count + " records"); }
From source file:test.unit.be.e_contract.dssp.client.DigitalSignatureServiceTestPort.java
@Override public SignResponse sign(SignRequest signRequest) { MessageContext messageContext = this.webServiceContext.getMessageContext(); Map<String, DataHandler> attachments = (Map<String, DataHandler>) messageContext .get(MessageContext.INBOUND_MESSAGE_ATTACHMENTS); LOG.debug("attachments: " + attachments.keySet()); if (attachments.size() != 0) { receivedAttachment = true;//from ww w . ja va 2s . c om } SignResponse signResponse = this.objectFactory.createSignResponse(); Result result = this.objectFactory.createResult(); signResponse.setResult(result); result.setResultMajor(DigitalSignatureServiceConstants.PENDING_RESULT_MAJOR); AnyType optionalOutputs = this.objectFactory.createAnyType(); signResponse.setOptionalOutputs(optionalOutputs); optionalOutputs.getAny().add(this.asyncObjectFactory.createResponseID("response identifier")); RequestSecurityTokenResponseCollectionType requestSecurityTokenResponseCollection = this.wstObjectFactory .createRequestSecurityTokenResponseCollectionType(); optionalOutputs.getAny().add(this.wstObjectFactory .createRequestSecurityTokenResponseCollection(requestSecurityTokenResponseCollection)); RequestSecurityTokenResponseType requestSecurityTokenResponse = this.wstObjectFactory .createRequestSecurityTokenResponseType(); requestSecurityTokenResponseCollection.getRequestSecurityTokenResponse().add(requestSecurityTokenResponse); RequestedSecurityTokenType requestedSecurityToken = this.wstObjectFactory .createRequestedSecurityTokenType(); requestSecurityTokenResponse.getAny() .add(this.wstObjectFactory.createRequestedSecurityToken(requestedSecurityToken)); SecurityContextTokenType securityContextToken = this.wsscObjectFactory.createSecurityContextTokenType(); requestedSecurityToken.setAny(this.wsscObjectFactory.createSecurityContextToken(securityContextToken)); securityContextToken.setId("token-reference"); securityContextToken.getAny().add(this.wsscObjectFactory.createIdentifier("token-identifier")); EntropyType entropy = this.wstObjectFactory.createEntropyType(); requestSecurityTokenResponse.getAny().add(this.wstObjectFactory.createEntropy(entropy)); BinarySecretType binarySecret = this.wstObjectFactory.createBinarySecretType(); entropy.getAny().add(this.wstObjectFactory.createBinarySecret(binarySecret)); byte[] nonce = new byte[256 / 8]; SecureRandom secureRandom = new SecureRandom(); secureRandom.nextBytes(nonce); binarySecret.setValue(nonce); return signResponse; }
From source file:org.wso2.carbon.identity.password.history.store.Impl.DefaultPasswordHistoryDataStore.java
/** * This private method returns a saltValue using SecureRandom. * * @return saltValue//from w w w. jav a 2s. c o m */ private String generateSaltValue() { String saltValue; try { SecureRandom secureRandom = SecureRandom.getInstance(SHA_1_PRNG); byte[] bytes = new byte[16]; //secureRandom is automatically seeded by calling nextBytes secureRandom.nextBytes(bytes); saltValue = Base64.encode(bytes); } catch (NoSuchAlgorithmException e) { throw new RuntimeException("SHA1PRNG algorithm could not be found."); } return saltValue; }
From source file:com.intel.chimera.StreamCipherTest.java
private void cryptoCipherTestForInputStream(int count, String encCipherClass, String decCipherClass, byte[] iv) throws IOException { Cipher encCipher = null;//from w w w . j a va2s .co m try { encCipher = (Cipher) ReflectionUtils.newInstance(ReflectionUtils.getClassByName(encCipherClass), props, transformation); } catch (ClassNotFoundException cnfe) { throw new IOException("Illegal crypto cipher!"); } LOG.info("Created a cipher object of type: " + encCipherClass); // Generate data SecureRandom random = new SecureRandom(); byte[] originalData = new byte[count]; byte[] decryptedData = new byte[count]; random.nextBytes(originalData); LOG.info("Generated " + count + " records"); // Encrypt data ByteArrayOutputStream encryptedData = new ByteArrayOutputStream(); CTRCryptoOutputStream out = new CTRCryptoOutputStream(encryptedData, encCipher, bufferSize, key, iv); out.write(originalData, 0, originalData.length); out.flush(); out.close(); LOG.info("Finished encrypting data"); Cipher decCipher = null; try { decCipher = (Cipher) ReflectionUtils.newInstance(ReflectionUtils.getClassByName(decCipherClass), props, transformation); } catch (ClassNotFoundException cnfe) { throw new IOException("Illegal crypto cipher!"); } LOG.info("Created a cipher object of type: " + decCipherClass); // Decrypt data CTRCryptoInputStream in = new CTRCryptoInputStream(new ByteArrayInputStream(encryptedData.toByteArray()), decCipher, bufferSize, key, iv); // Check int remainingToRead = count; int offset = 0; while (remainingToRead > 0) { int n = in.read(decryptedData, offset, decryptedData.length - offset); if (n >= 0) { remainingToRead -= n; offset += n; } } Assert.assertArrayEquals("originalData and decryptedData not equal", originalData, decryptedData); // Decrypt data byte-at-a-time in = new CTRCryptoInputStream(new ByteArrayInputStream(encryptedData.toByteArray()), decCipher, bufferSize, key, iv); // Check DataInputStream originalIn = new DataInputStream( new BufferedInputStream(new ByteArrayInputStream(originalData))); int expected; do { expected = originalIn.read(); Assert.assertEquals("Decrypted stream read by byte does not match", expected, in.read()); } while (expected != -1); LOG.info("SUCCESS! Completed checking " + count + " records"); }