Search in sources :

Example 41 with SecureRandom

use of java.security.SecureRandom in project conceal by facebook.

the class AESCipher method getInstance.

public static AESCipher getInstance() {
    byte[] iv = new byte[16];
    byte[] key = new byte[16];
    SecureRandom random = new SecureRandom();
    random.nextBytes(iv);
    random.nextBytes(key);
    AlgorithmParameterSpec spec = new IvParameterSpec(iv);
    return new AESCipher(spec, new SecretKeySpec(key, "AES"));
}
Also used : SecretKeySpec(javax.crypto.spec.SecretKeySpec) SecureRandom(java.security.SecureRandom) IvParameterSpec(javax.crypto.spec.IvParameterSpec) AlgorithmParameterSpec(java.security.spec.AlgorithmParameterSpec)

Example 42 with SecureRandom

use of java.security.SecureRandom in project conceal by facebook.

the class NativeGCMCipherHelper method getInstance.

public static NativeGCMCipherHelper getInstance() {
    byte[] key = new byte[CryptoConfig.KEY_128.keyLength];
    byte[] iv = new byte[CryptoConfig.KEY_128.ivLength];
    new SecureRandom().nextBytes(key);
    new SecureRandom().nextBytes(iv);
    return new NativeGCMCipherHelper(key, iv, CryptoConfig.KEY_128.tagLength);
}
Also used : SecureRandom(java.security.SecureRandom)

Example 43 with SecureRandom

use of java.security.SecureRandom in project gitblit by gitblit.

the class X509Utils method newClientCertificate.

/**
	 * Creates a new client certificate PKCS#12 and PEM store.  Any existing
	 * stores are destroyed.
	 *
	 * @param clientMetadata a container for dynamic parameters needed for generation
	 * @param caKeystoreFile
	 * @param caKeystorePassword
	 * @param targetFolder
	 * @return
	 */
public static X509Certificate newClientCertificate(X509Metadata clientMetadata, PrivateKey caPrivateKey, X509Certificate caCert, File targetFolder) {
    try {
        KeyPair pair = newKeyPair();
        X500Name userDN = buildDistinguishedName(clientMetadata);
        X500Name issuerDN = new X500Name(PrincipalUtil.getIssuerX509Principal(caCert).getName());
        // create a new certificate signed by the Gitblit CA certificate
        X509v3CertificateBuilder certBuilder = new JcaX509v3CertificateBuilder(issuerDN, BigInteger.valueOf(System.currentTimeMillis()), clientMetadata.notBefore, clientMetadata.notAfter, userDN, pair.getPublic());
        JcaX509ExtensionUtils extUtils = new JcaX509ExtensionUtils();
        certBuilder.addExtension(X509Extension.subjectKeyIdentifier, false, extUtils.createSubjectKeyIdentifier(pair.getPublic()));
        certBuilder.addExtension(X509Extension.basicConstraints, false, new BasicConstraints(false));
        certBuilder.addExtension(X509Extension.authorityKeyIdentifier, false, extUtils.createAuthorityKeyIdentifier(caCert.getPublicKey()));
        certBuilder.addExtension(X509Extension.keyUsage, true, new KeyUsage(KeyUsage.keyEncipherment | KeyUsage.digitalSignature));
        if (!StringUtils.isEmpty(clientMetadata.emailAddress)) {
            GeneralNames subjectAltName = new GeneralNames(new GeneralName(GeneralName.rfc822Name, clientMetadata.emailAddress));
            certBuilder.addExtension(X509Extension.subjectAlternativeName, false, subjectAltName);
        }
        ContentSigner signer = new JcaContentSignerBuilder(SIGNING_ALGORITHM).setProvider(BC).build(caPrivateKey);
        X509Certificate userCert = new JcaX509CertificateConverter().setProvider(BC).getCertificate(certBuilder.build(signer));
        PKCS12BagAttributeCarrier bagAttr = (PKCS12BagAttributeCarrier) pair.getPrivate();
        bagAttr.setBagAttribute(PKCSObjectIdentifiers.pkcs_9_at_localKeyId, extUtils.createSubjectKeyIdentifier(pair.getPublic()));
        // confirm the validity of the user certificate
        userCert.checkValidity();
        userCert.verify(caCert.getPublicKey());
        userCert.getIssuerDN().equals(caCert.getSubjectDN());
        // verify user certificate chain
        verifyChain(userCert, caCert);
        targetFolder.mkdirs();
        // save certificate, stamped with unique name
        String date = new SimpleDateFormat("yyyyMMdd").format(new Date());
        String id = date;
        File certFile = new File(targetFolder, id + ".cer");
        int count = 0;
        while (certFile.exists()) {
            id = date + "_" + Character.toString((char) (0x61 + count));
            certFile = new File(targetFolder, id + ".cer");
            count++;
        }
        // save user private key, user certificate and CA certificate to a PKCS#12 store
        File p12File = new File(targetFolder, clientMetadata.commonName + ".p12");
        if (p12File.exists()) {
            p12File.delete();
        }
        KeyStore userStore = openKeyStore(p12File, clientMetadata.password);
        userStore.setKeyEntry(MessageFormat.format("Gitblit ({0}) {1} {2}", clientMetadata.serverHostname, clientMetadata.userDisplayname, id), pair.getPrivate(), null, new Certificate[] { userCert });
        userStore.setCertificateEntry(MessageFormat.format("Gitblit ({0}) Certificate Authority", clientMetadata.serverHostname), caCert);
        saveKeyStore(p12File, userStore, clientMetadata.password);
        // save user private key, user certificate, and CA certificate to a PEM store
        File pemFile = new File(targetFolder, clientMetadata.commonName + ".pem");
        if (pemFile.exists()) {
            pemFile.delete();
        }
        JcePEMEncryptorBuilder builder = new JcePEMEncryptorBuilder("DES-EDE3-CBC");
        builder.setSecureRandom(new SecureRandom());
        PEMEncryptor pemEncryptor = builder.build(clientMetadata.password.toCharArray());
        JcaPEMWriter pemWriter = new JcaPEMWriter(new FileWriter(pemFile));
        pemWriter.writeObject(pair.getPrivate(), pemEncryptor);
        pemWriter.writeObject(userCert);
        pemWriter.writeObject(caCert);
        pemWriter.flush();
        pemWriter.close();
        // save certificate after successfully creating the key stores
        saveCertificate(userCert, certFile);
        // update serial number in metadata object
        clientMetadata.serialNumber = userCert.getSerialNumber().toString();
        return userCert;
    } catch (Throwable t) {
        throw new RuntimeException("Failed to generate client certificate!", t);
    }
}
Also used : JcaX509ExtensionUtils(org.bouncycastle.cert.jcajce.JcaX509ExtensionUtils) JcaContentSignerBuilder(org.bouncycastle.operator.jcajce.JcaContentSignerBuilder) FileWriter(java.io.FileWriter) KeyUsage(org.bouncycastle.asn1.x509.KeyUsage) X500Name(org.bouncycastle.asn1.x500.X500Name) PKCS12BagAttributeCarrier(org.bouncycastle.jce.interfaces.PKCS12BagAttributeCarrier) PEMEncryptor(org.bouncycastle.openssl.PEMEncryptor) JcaX509CertificateConverter(org.bouncycastle.cert.jcajce.JcaX509CertificateConverter) JcaX509v3CertificateBuilder(org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder) JcePEMEncryptorBuilder(org.bouncycastle.openssl.jcajce.JcePEMEncryptorBuilder) KeyPair(java.security.KeyPair) ContentSigner(org.bouncycastle.operator.ContentSigner) SecureRandom(java.security.SecureRandom) KeyStore(java.security.KeyStore) X509Certificate(java.security.cert.X509Certificate) Date(java.util.Date) GeneralNames(org.bouncycastle.asn1.x509.GeneralNames) JcaX509v3CertificateBuilder(org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder) X509v3CertificateBuilder(org.bouncycastle.cert.X509v3CertificateBuilder) GeneralName(org.bouncycastle.asn1.x509.GeneralName) JcaPEMWriter(org.bouncycastle.openssl.jcajce.JcaPEMWriter) BasicConstraints(org.bouncycastle.asn1.x509.BasicConstraints) SimpleDateFormat(java.text.SimpleDateFormat) File(java.io.File)

Example 44 with SecureRandom

use of java.security.SecureRandom in project gitblit by gitblit.

the class X509Utils method newKeyPair.

/**
	 * Generate a new keypair.
	 *
	 * @return a keypair
	 * @throws Exception
	 */
private static KeyPair newKeyPair() throws Exception {
    KeyPairGenerator kpGen = KeyPairGenerator.getInstance(KEY_ALGORITHM, BC);
    kpGen.initialize(KEY_LENGTH, new SecureRandom());
    return kpGen.generateKeyPair();
}
Also used : SecureRandom(java.security.SecureRandom) KeyPairGenerator(java.security.KeyPairGenerator)

Example 45 with SecureRandom

use of java.security.SecureRandom in project XobotOS by xamarin.

the class SHA1withDSA_SignatureImpl method engineSign.

/**
     * Returns signature bytes as byte array containing
     * ASN1 representation for two BigInteger objects
     * which is SEQUENCE of two INTEGERS.
     * Length of sequence varies from less than 46 to 48.
     *
     * Resets object to the state it was in
     * when previous call to either "initSign" method was called.
     *
     * @return
     *    byte array containing signature in ASN1 representation
     * @throws
     *    SignatureException if object's state is not SIGN or
     *                       signature algorithm cannot process data
     */
protected byte[] engineSign() throws SignatureException {
    // names of below BigIntegers are the same as they are defined in DSA standard
    BigInteger r = null;
    BigInteger s = null;
    BigInteger k = null;
    // parameters and private key
    BigInteger p, q, g, x;
    // BigInteger for message digest
    BigInteger digestBI;
    // various byte array being used in computing signature
    byte[] randomBytes;
    byte[] rBytes;
    byte[] sBytes;
    byte[] signature;
    int n, n1, n2;
    DSAParams params;
    if (appRandom == null) {
        appRandom = new SecureRandom();
    }
    params = dsaKey.getParams();
    p = params.getP();
    q = params.getQ();
    g = params.getG();
    x = ((DSAPrivateKey) dsaKey).getX();
    // forming signature according algorithm described in chapter 5 of DSA standard
    digestBI = new BigInteger(1, msgDigest.digest());
    randomBytes = new byte[20];
    for (; ; ) {
        appRandom.nextBytes(randomBytes);
        k = new BigInteger(1, randomBytes);
        if (k.compareTo(q) != -1) {
            continue;
        }
        r = g.modPow(k, p).mod(q);
        if (r.signum() == 0) {
            continue;
        }
        s = k.modInverse(q).multiply(digestBI.add(x.multiply(r)).mod(q)).mod(q);
        if (s.signum() != 0) {
            break;
        }
    }
    // forming signature's ASN1 representation which is SEQUENCE of two INTEGERs
    //
    rBytes = r.toByteArray();
    n1 = rBytes.length;
    if ((rBytes[0] & 0x80) != 0) {
        n1++;
    }
    sBytes = s.toByteArray();
    n2 = sBytes.length;
    if ((sBytes[0] & 0x80) != 0) {
        n2++;
    }
    // 48 is max. possible length of signature
    signature = new byte[6 + n1 + n2];
    // ASN1 SEQUENCE tag
    signature[0] = (byte) 0x30;
    // total length of two INTEGERs
    signature[1] = (byte) (4 + n1 + n2);
    // ASN1 INTEGER tag
    signature[2] = (byte) 0x02;
    // length of r
    signature[3] = (byte) n1;
    // ASN1 INTEGER tag
    signature[4 + n1] = (byte) 0x02;
    // length of s
    signature[5 + n1] = (byte) n2;
    if (n1 == rBytes.length) {
        n = 4;
    } else {
        n = 5;
    }
    System.arraycopy(rBytes, 0, signature, n, rBytes.length);
    if (n2 == sBytes.length) {
        n = 6 + n1;
    } else {
        n = 7 + n1;
    }
    System.arraycopy(sBytes, 0, signature, n, sBytes.length);
    return signature;
}
Also used : BigInteger(java.math.BigInteger) SecureRandom(java.security.SecureRandom) DSAParams(java.security.interfaces.DSAParams)

Aggregations

SecureRandom (java.security.SecureRandom)720 SSLContext (javax.net.ssl.SSLContext)106 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)97 IOException (java.io.IOException)87 Test (org.junit.Test)76 SecretKey (javax.crypto.SecretKey)62 X509Certificate (java.security.cert.X509Certificate)61 KeyGenerator (javax.crypto.KeyGenerator)57 TrustManager (javax.net.ssl.TrustManager)56 X509TrustManager (javax.net.ssl.X509TrustManager)47 Cipher (javax.crypto.Cipher)46 KeyPairGenerator (java.security.KeyPairGenerator)44 BigInteger (java.math.BigInteger)42 CertificateException (java.security.cert.CertificateException)40 InvalidKeyException (java.security.InvalidKeyException)35 KeyPair (java.security.KeyPair)34 KeyStore (java.security.KeyStore)34 SecretKeySpec (javax.crypto.spec.SecretKeySpec)30 InvalidAlgorithmParameterException (java.security.InvalidAlgorithmParameterException)28 KeyManagementException (java.security.KeyManagementException)28