Example usage for java.security SecureRandom nextBytes

List of usage examples for java.security SecureRandom nextBytes

Introduction

In this page you can find the example usage for java.security SecureRandom nextBytes.

Prototype

@Override
public void nextBytes(byte[] bytes) 

Source Link

Document

Generates a user-specified number of random bytes.

Usage

From source file:test.integ.be.fedict.commons.eid.client.SSLTest.java

private X509Certificate generateCACertificate(final KeyPair keyPair, final String subject,
        final DateTime notBefore, final DateTime notAfter) throws Exception {
    LOG.debug("generate CA certificate: " + subject);

    final X500Name issuer = new X500Name(subject);
    final X500Name subjectX500Name = new X500Name(subject);

    final SubjectPublicKeyInfo publicKeyInfo = SubjectPublicKeyInfo
            .getInstance(keyPair.getPublic().getEncoded());

    final SecureRandom secureRandom = new SecureRandom();
    final byte[] serialValue = new byte[8];
    secureRandom.nextBytes(serialValue);
    final BigInteger serial = new BigInteger(serialValue);

    final X509v3CertificateBuilder x509v3CertificateBuilder = new X509v3CertificateBuilder(issuer, serial,
            notBefore.toDate(), notAfter.toDate(), subjectX500Name, publicKeyInfo);

    try {//from w w w.  ja  v a2s.  co m
        final JcaX509ExtensionUtils extensionUtils = new JcaX509ExtensionUtils();
        x509v3CertificateBuilder.addExtension(X509Extension.subjectKeyIdentifier, false,
                extensionUtils.createSubjectKeyIdentifier(keyPair.getPublic()));
        x509v3CertificateBuilder.addExtension(X509Extension.authorityKeyIdentifier, false,
                extensionUtils.createAuthorityKeyIdentifier(keyPair.getPublic()));

        x509v3CertificateBuilder.addExtension(MiscObjectIdentifiers.netscapeCertType, false,
                new NetscapeCertType(
                        NetscapeCertType.sslCA | NetscapeCertType.smimeCA | NetscapeCertType.objectSigningCA));

        x509v3CertificateBuilder.addExtension(X509Extension.keyUsage, true,
                new KeyUsage(KeyUsage.keyCertSign | KeyUsage.cRLSign));

        x509v3CertificateBuilder.addExtension(X509Extension.basicConstraints, true,
                new BasicConstraints(2147483647));

    } catch (final Exception e) {
        throw new RuntimeException(e);
    }

    final AlgorithmIdentifier sigAlgId = new DefaultSignatureAlgorithmIdentifierFinder().find("SHA1withRSA");
    final AlgorithmIdentifier digAlgId = new DefaultDigestAlgorithmIdentifierFinder().find(sigAlgId);
    AsymmetricKeyParameter asymmetricKeyParameter;
    try {
        asymmetricKeyParameter = PrivateKeyFactory.createKey(keyPair.getPrivate().getEncoded());
    } catch (final IOException e) {
        throw new RuntimeException(e);
    }
    ContentSigner contentSigner;
    try {
        contentSigner = new BcRSAContentSignerBuilder(sigAlgId, digAlgId).build(asymmetricKeyParameter);
    } catch (final OperatorCreationException e) {
        throw new RuntimeException(e);
    }
    final X509CertificateHolder x509CertificateHolder = x509v3CertificateBuilder.build(contentSigner);

    byte[] encodedCertificate;
    try {
        encodedCertificate = x509CertificateHolder.getEncoded();
    } catch (final IOException e) {
        throw new RuntimeException(e);
    }

    CertificateFactory certificateFactory;
    try {
        certificateFactory = CertificateFactory.getInstance("X.509");
    } catch (final CertificateException e) {
        throw new RuntimeException(e);
    }
    X509Certificate certificate;
    try {
        certificate = (X509Certificate) certificateFactory
                .generateCertificate(new ByteArrayInputStream(encodedCertificate));
    } catch (final CertificateException e) {
        throw new RuntimeException(e);
    }
    return certificate;
}

From source file:org.wso2.carbon.apimgt.gateway.mediators.DigestAuthMediator.java

/**
 * This method is used to randomly generate the client nonce
 *
 * @return The randomly generated client nonce which is a 16 digit hexadecimal value
 *//*from www .  j  a v  a2 s . com*/
public String generateClientNonce() {

    SecureRandom secRandom = new SecureRandom();
    byte[] result = new byte[32];
    secRandom.nextBytes(result);
    return new String(Hex.encodeHex(result));
}

From source file:org.apache.pdfbox.pdmodel.encryption.SecurityHandler.java

/**
 * Encrypt or decrypt data with AES256.//  w  ww  .  j  a v a 2 s.  co  m
 *
 * @param data The data to encrypt.
 * @param output The output to write the encrypted data to.
 * @param decrypt true to decrypt the data, false to encrypt it.
 *
 * @throws IOException If there is an error reading the data.
 */
private void encryptDataAES256(InputStream data, OutputStream output, boolean decrypt) throws IOException {
    byte[] iv = new byte[16];

    if (decrypt) {
        // read IV from stream
        data.read(iv);
    } else {
        // generate random IV and write to stream
        SecureRandom rnd = new SecureRandom();
        rnd.nextBytes(iv);
        output.write(iv);
    }

    Cipher cipher;
    try {
        cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        SecretKeySpec keySpec = new SecretKeySpec(encryptionKey, "AES");
        IvParameterSpec ivSpec = new IvParameterSpec(iv);
        cipher.init(decrypt ? Cipher.DECRYPT_MODE : Cipher.ENCRYPT_MODE, keySpec, ivSpec);
    } catch (GeneralSecurityException e) {
        throw new IOException(e);
    }

    CipherInputStream cis = new CipherInputStream(data, cipher);
    try {
        IOUtils.copy(cis, output);
    } catch (IOException exception) {
        // starting with java 8 the JVM wraps an IOException around a GeneralSecurityException
        // it should be safe to swallow a GeneralSecurityException
        if (!(exception.getCause() instanceof GeneralSecurityException)) {
            throw exception;
        }
        LOG.debug("A GeneralSecurityException occured when decrypting some stream data", exception);
    } finally {
        cis.close();
    }
}

From source file:de.hybris.platform.cuppytrail.impl.DefaultSecureTokenService.java

private byte[] generatePadding(final int length, final SecureRandom random) {
    if (length < 0 || length > 7) {
        throw new IllegalArgumentException("length must be in range 0 to 7. Actual value: " + length);
    }//from  w  ww  . jav  a 2s  . c  o  m

    final byte[] block = new byte[length + 1];

    // Fill with random data
    random.nextBytes(block);

    // Overwrite the bottom 3 bits of the first byte with the length
    final byte firstByte = (byte) ((block[0] & 0x00F8) | (length & 0x0007));
    block[0] = firstByte;

    return block;
}

From source file:org.sufficientlysecure.keychain.ui.PassphraseWizardActivity.java

private void write(Tag tag) throws IOException, FormatException {
    //generate new random key and write them on the tag
    SecureRandom sr = new SecureRandom();
    sr.nextBytes(output);
    NdefRecord[] records = { createRecord(output.toString()) };
    NdefMessage message = new NdefMessage(records);
    Ndef ndef = Ndef.get(tag);//  w w w . j a va  2s .  co m
    ndef.connect();
    ndef.writeNdefMessage(message);
    ndef.close();
}

From source file:com.intel.chimera.stream.AbstractCryptoStreamTest.java

private void doReadWriteTestForInputStream(int count, String encCipherClass, String decCipherClass, byte[] iv)
        throws IOException {
    Cipher encCipher = getCipher(encCipherClass);
    LOG.debug("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.debug("Generated " + count + " records");

    // Encrypt data
    ByteArrayOutputStream encryptedData = new ByteArrayOutputStream();
    CryptoOutputStream out = getCryptoOutputStream(encryptedData, encCipher, defaultBufferSize, iv, false);
    out.write(originalData, 0, originalData.length);
    out.flush();//from   w ww.ja  v  a  2  s .com
    out.close();
    LOG.debug("Finished encrypting data");

    Cipher decCipher = getCipher(decCipherClass);
    LOG.debug("Created a cipher object of type: " + decCipherClass);

    // Decrypt data
    CryptoInputStream in = getCryptoInputStream(new ByteArrayInputStream(encryptedData.toByteArray()),
            decCipher, defaultBufferSize, iv, false);

    // 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 = getCryptoInputStream(new ByteArrayInputStream(encryptedData.toByteArray()), decCipher,
            defaultBufferSize, iv, false);

    // 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.debug("SUCCESS! Completed checking " + count + " records");
}

From source file:com.intel.chimera.stream.AbstractCryptoStreamTest.java

private void doReadWriteTestForReadableByteChannel(int count, String encCipherClass, String decCipherClass,
        byte[] iv) throws IOException {
    Cipher encCipher = getCipher(encCipherClass);
    LOG.debug("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.debug("Generated " + count + " records");

    // Encrypt data
    ByteArrayOutputStream encryptedData = new ByteArrayOutputStream();
    CryptoOutputStream out = getCryptoOutputStream(encryptedData, encCipher, defaultBufferSize, iv, true);
    out.write(originalData, 0, originalData.length);
    out.flush();/*from w  ww. j  a  v a  2s . com*/
    out.close();
    LOG.debug("Finished encrypting data");

    Cipher decCipher = getCipher(decCipherClass);
    LOG.debug("Created a cipher object of type: " + decCipherClass);

    // Decrypt data
    CryptoInputStream in = getCryptoInputStream(new ByteArrayInputStream(encryptedData.toByteArray()),
            decCipher, defaultBufferSize, iv, true);

    // 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 = getCryptoInputStream(new ByteArrayInputStream(encryptedData.toByteArray()), decCipher,
            defaultBufferSize, iv, true);

    // 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.debug("SUCCESS! Completed checking " + count + " records");
}

From source file:org.zuinnote.hadoop.office.format.common.parser.msexcel.internal.EncryptedCachedDiskStringsTable.java

/***
 * Create a new encrypted cached string table
 * // w ww.j ava2s  . c o m
 * @param part             package part with Shared String Table
 * @param cacheSize        cache = -1 means all is in memory, cache = 0 means
 *                         nothing is in memory, positive means only that
 *                         fractions is kept in-memory
 * @param compressTempFile true, if temporary file storage for shared string
 *                         table should be gzip compressed, false if not
 * @param                  ca, cipher algorithm leave it null for disabling
 *                         encryption (not recommended if source document is
 *                         encrypted)
 * @param                  cm, chaining mode, only need to be specified if
 *                         cipher algorithm is specified
 * @throws IOException
 */

public EncryptedCachedDiskStringsTable(PackagePart part, int cacheSize, boolean compressTempFile,
        CipherAlgorithm ca, ChainingMode cm) throws IOException {
    this.cacheSize = cacheSize;
    this.count = 0;
    if (this.cacheSize > 0) {

        this.cache = new LRUCache<>(((int) Math.ceil(this.cacheSize / 0.75)) + 1); // based on recommendations of
        // the Javadoc of HashMap
        this.stringPositionInFileList = new ArrayList<>(this.cacheSize);
    } else {
        this.cache = new LRUCache<>();
        this.stringPositionInFileList = new ArrayList<>();
    }
    this.stringPositionInFileList = new ArrayList<>();
    this.compressTempFile = compressTempFile;
    this.tempFile = TempFile.createTempFile("hadooffice-poi-temp-sst", ".tmp");
    this.tempFileSize = 0L;
    // generate random key for temnporary files
    if (ca != null) {
        SecureRandom sr = new SecureRandom();
        byte[] iv = new byte[ca.blockSize];
        byte[] key = new byte[ca.defaultKeySize / 8];
        sr.nextBytes(iv);
        sr.nextBytes(key);
        SecretKeySpec skeySpec = new SecretKeySpec(key, ca.jceId);
        this.ca = ca;
        this.cm = cm;
        if (this.cm.jceId.equals(ChainingMode.ecb.jceId)) { // does not work with Crpyto Functions since it does not require IV
            this.cm = ChainingMode.cbc;
        }
        this.ciEncrypt = CryptoFunctions.getCipher(skeySpec, this.ca, this.cm, iv, Cipher.ENCRYPT_MODE,
                "PKCS5Padding");
        this.ciDecrypt = CryptoFunctions.getCipher(skeySpec, this.ca, this.cm, iv, Cipher.DECRYPT_MODE,
                "PKCS5Padding");
    }
    this.originalIS = part.getInputStream();
    this.readFrom(this.originalIS);
}

From source file:com.sonicle.webtop.core.sdk.UserProfile.java

private String generateSecretKey() throws NoSuchAlgorithmException {
    byte[] buffer = new byte[80 / 8];
    SecureRandom sr = SecureRandom.getInstance("SHA1PRNG");
    sr.nextBytes(buffer);
    byte[] secretKey = Arrays.copyOf(buffer, 80 / 8);
    byte[] encodedKey = new Base32().encode(secretKey);
    return new String(encodedKey);
}

From source file:org.sakaiproject.tool.impl.SessionComponent.java

/**
 * Final initialization, once all dependencies are set.
 *//*from w  w w .  j a v  a  2s .  c  o m*/
public void init() {
    // start the maintenance thread
    if (m_checkEvery > 0) {
        m_maintenance = new Maintenance();
        m_maintenance.start();
    }

    // Salt generation 64 bits long

    salt = new byte[8];
    SecureRandom random;
    try {
        random = SecureRandom.getInstance("SHA1PRNG");
        random.nextBytes(salt);
    } catch (NoSuchAlgorithmException e) {
        M_log.warn("Random number generator not available - using time randomness");
        salt = String.valueOf(System.currentTimeMillis()).getBytes();
    }

    M_log.info("init(): interval: " + m_defaultInactiveInterval + " refresh: " + m_checkEvery);
}