Search in sources :

Example 86 with SecureRandom

use of java.security.SecureRandom in project cas by apereo.

the class Beans method newPasswordEncoder.

/**
     * New password encoder password encoder.
     *
     * @param properties the properties
     * @return the password encoder
     */
public static PasswordEncoder newPasswordEncoder(final PasswordEncoderProperties properties) {
    final String type = properties.getType();
    if (StringUtils.isBlank(type)) {
        LOGGER.debug("No password encoder type is defined, and so none shall be created");
        return NoOpPasswordEncoder.getInstance();
    }
    if (type.contains(".")) {
        try {
            LOGGER.debug("Configuration indicates use of a custom password encoder [{}]", type);
            final Class<PasswordEncoder> clazz = (Class<PasswordEncoder>) Class.forName(type);
            return clazz.newInstance();
        } catch (final Exception e) {
            LOGGER.error("Falling back to a no-op password encoder as CAS has failed to create " + "an instance of the custom password encoder class " + type, e);
            return NoOpPasswordEncoder.getInstance();
        }
    }
    final PasswordEncoderProperties.PasswordEncoderTypes encoderType = PasswordEncoderProperties.PasswordEncoderTypes.valueOf(type);
    switch(encoderType) {
        case DEFAULT:
            LOGGER.debug("Creating default password encoder with encoding alg [{}] and character encoding [{}]", properties.getEncodingAlgorithm(), properties.getCharacterEncoding());
            return new DefaultPasswordEncoder(properties.getEncodingAlgorithm(), properties.getCharacterEncoding());
        case STANDARD:
            LOGGER.debug("Creating standard password encoder with the secret defined in the configuration");
            return new StandardPasswordEncoder(properties.getSecret());
        case BCRYPT:
            LOGGER.debug("Creating BCRYPT password encoder given the strength [{}] and secret in the configuration", properties.getStrength());
            if (StringUtils.isBlank(properties.getSecret())) {
                LOGGER.debug("Creating BCRYPT encoder without secret");
                return new BCryptPasswordEncoder(properties.getStrength());
            }
            LOGGER.debug("Creating BCRYPT encoder with secret");
            return new BCryptPasswordEncoder(properties.getStrength(), new SecureRandom(properties.getSecret().getBytes(StandardCharsets.UTF_8)));
        case SCRYPT:
            LOGGER.debug("Creating SCRYPT encoder");
            return new SCryptPasswordEncoder();
        case PBKDF2:
            if (StringUtils.isBlank(properties.getSecret())) {
                LOGGER.debug("Creating PBKDF2 encoder without secret");
                return new Pbkdf2PasswordEncoder();
            }
            final int hashWidth = 256;
            return new Pbkdf2PasswordEncoder(properties.getSecret(), properties.getStrength(), hashWidth);
        case NONE:
        default:
            LOGGER.debug("No password encoder shall be created given the requested encoder type [{}]", type);
            return NoOpPasswordEncoder.getInstance();
    }
}
Also used : StandardPasswordEncoder(org.springframework.security.crypto.password.StandardPasswordEncoder) DefaultPasswordEncoder(org.apereo.cas.util.crypto.DefaultPasswordEncoder) BCryptPasswordEncoder(org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder) StandardPasswordEncoder(org.springframework.security.crypto.password.StandardPasswordEncoder) Pbkdf2PasswordEncoder(org.springframework.security.crypto.password.Pbkdf2PasswordEncoder) NoOpPasswordEncoder(org.springframework.security.crypto.password.NoOpPasswordEncoder) SCryptPasswordEncoder(org.springframework.security.crypto.scrypt.SCryptPasswordEncoder) PasswordEncoder(org.springframework.security.crypto.password.PasswordEncoder) SecureRandom(java.security.SecureRandom) Pbkdf2PasswordEncoder(org.springframework.security.crypto.password.Pbkdf2PasswordEncoder) BeanCreationException(org.springframework.beans.factory.BeanCreationException) SCryptPasswordEncoder(org.springframework.security.crypto.scrypt.SCryptPasswordEncoder) PasswordEncoderProperties(org.apereo.cas.configuration.model.core.authentication.PasswordEncoderProperties) DefaultPasswordEncoder(org.apereo.cas.util.crypto.DefaultPasswordEncoder) BCryptPasswordEncoder(org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder)

Example 87 with SecureRandom

use of java.security.SecureRandom in project kafka by apache.

the class TestSslUtils method generateCertificate.

/**
     * Create a self-signed X.509 Certificate.
     * From http://bfo.com/blog/2011/03/08/odds_and_ends_creating_a_new_x_509_certificate.html.
     *
     * @param dn the X.509 Distinguished Name, eg "CN=Test, L=London, C=GB"
     * @param pair the KeyPair
     * @param days how many days from now the Certificate is valid for
     * @param algorithm the signing algorithm, eg "SHA1withRSA"
     * @return the self-signed certificate
     * @throws CertificateException thrown if a security error or an IO error occurred.
     */
public static X509Certificate generateCertificate(String dn, KeyPair pair, int days, String algorithm) throws CertificateException {
    try {
        Security.addProvider(new BouncyCastleProvider());
        AlgorithmIdentifier sigAlgId = new DefaultSignatureAlgorithmIdentifierFinder().find(algorithm);
        AlgorithmIdentifier digAlgId = new DefaultDigestAlgorithmIdentifierFinder().find(sigAlgId);
        AsymmetricKeyParameter privateKeyAsymKeyParam = PrivateKeyFactory.createKey(pair.getPrivate().getEncoded());
        SubjectPublicKeyInfo subPubKeyInfo = SubjectPublicKeyInfo.getInstance(pair.getPublic().getEncoded());
        ContentSigner sigGen = new BcRSAContentSignerBuilder(sigAlgId, digAlgId).build(privateKeyAsymKeyParam);
        X500Name name = new X500Name(dn);
        Date from = new Date();
        Date to = new Date(from.getTime() + days * 86400000L);
        BigInteger sn = new BigInteger(64, new SecureRandom());
        X509v1CertificateBuilder v1CertGen = new X509v1CertificateBuilder(name, sn, from, to, name, subPubKeyInfo);
        X509CertificateHolder certificateHolder = v1CertGen.build(sigGen);
        return new JcaX509CertificateConverter().setProvider("BC").getCertificate(certificateHolder);
    } catch (CertificateException ce) {
        throw ce;
    } catch (Exception e) {
        throw new CertificateException(e);
    }
}
Also used : ContentSigner(org.bouncycastle.operator.ContentSigner) SecureRandom(java.security.SecureRandom) CertificateException(java.security.cert.CertificateException) X500Name(org.bouncycastle.asn1.x500.X500Name) DefaultDigestAlgorithmIdentifierFinder(org.bouncycastle.operator.DefaultDigestAlgorithmIdentifierFinder) SubjectPublicKeyInfo(org.bouncycastle.asn1.x509.SubjectPublicKeyInfo) Date(java.util.Date) GeneralSecurityException(java.security.GeneralSecurityException) IOException(java.io.IOException) CertificateException(java.security.cert.CertificateException) EOFException(java.io.EOFException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) AlgorithmIdentifier(org.bouncycastle.asn1.x509.AlgorithmIdentifier) DefaultSignatureAlgorithmIdentifierFinder(org.bouncycastle.operator.DefaultSignatureAlgorithmIdentifierFinder) BcRSAContentSignerBuilder(org.bouncycastle.operator.bc.BcRSAContentSignerBuilder) AsymmetricKeyParameter(org.bouncycastle.crypto.params.AsymmetricKeyParameter) JcaX509CertificateConverter(org.bouncycastle.cert.jcajce.JcaX509CertificateConverter) X509CertificateHolder(org.bouncycastle.cert.X509CertificateHolder) BigInteger(java.math.BigInteger) X509v1CertificateBuilder(org.bouncycastle.cert.X509v1CertificateBuilder) BouncyCastleProvider(org.bouncycastle.jce.provider.BouncyCastleProvider)

Example 88 with SecureRandom

use of java.security.SecureRandom in project hudson-2.x by hudson.

the class Launcher method runWithStdinStdout.

private void runWithStdinStdout() throws IOException, InterruptedException {
    // use stdin/stdout for channel communication
    ttyCheck();
    if (isWindows()) {
        /*
                To prevent the dead lock between GetFileType from _ioinit in C runtime and blocking read that ChannelReaderThread
                would do on stdin, load the crypto DLL first.

                This is a band-aid solution to the problem. Still searching for more fundamental fix. 

                02f1e750 7c90d99a ntdll!KiFastSystemCallRet
                02f1e754 7c810f63 ntdll!NtQueryVolumeInformationFile+0xc
                02f1e784 77c2c9f9 kernel32!GetFileType+0x7e
                02f1e7e8 77c1f01d msvcrt!_ioinit+0x19f
                02f1e88c 7c90118a msvcrt!__CRTDLL_INIT+0xac
                02f1e8ac 7c91c4fa ntdll!LdrpCallInitRoutine+0x14
                02f1e9b4 7c916371 ntdll!LdrpRunInitializeRoutines+0x344
                02f1ec60 7c9164d3 ntdll!LdrpLoadDll+0x3e5
                02f1ef08 7c801bbd ntdll!LdrLoadDll+0x230
                02f1ef70 7c801d72 kernel32!LoadLibraryExW+0x18e
                02f1ef84 7c801da8 kernel32!LoadLibraryExA+0x1f
                02f1efa0 77de8830 kernel32!LoadLibraryA+0x94
                02f1f05c 6d3eb1be ADVAPI32!CryptAcquireContextA+0x512
                WARNING: Stack unwind information not available. Following frames may be wrong.
                02f1f13c 6d99c844 java_6d3e0000!Java_sun_security_provider_NativeSeedGenerator_nativeGenerateSeed+0x6e

                see http://weblogs.java.net/blog/kohsuke/archive/2009/09/28/reading-stdin-may-cause-your-jvm-hang
                for more details
             */
        new SecureRandom().nextBoolean();
    }
    // this will prevent programs from accidentally writing to System.out
    // and messing up the stream.
    OutputStream os = System.out;
    System.setOut(System.err);
    main(System.in, os, mode, ping);
}
Also used : BufferedOutputStream(java.io.BufferedOutputStream) OutputStream(java.io.OutputStream) SecureRandom(java.security.SecureRandom)

Example 89 with SecureRandom

use of java.security.SecureRandom in project hudson-2.x by hudson.

the class SecretTest method setUp.

@Override
protected void setUp() throws Exception {
    SecureRandom sr = new SecureRandom();
    byte[] random = new byte[32];
    sr.nextBytes(random);
    Secret.SECRET = Util.toHexString(random);
}
Also used : SecureRandom(java.security.SecureRandom)

Example 90 with SecureRandom

use of java.security.SecureRandom in project head by mifos.

the class PasswordHashing method generateRandomBytes.

/**
     * This function generate and returns the random no of bytes
     *
     * @return randomBytes
     */
public byte[] generateRandomBytes() {
    byte[] randomBytes = new byte[12];
    SecureRandom secureRandom = new SecureRandom();
    secureRandom.nextBytes(randomBytes);
    return randomBytes;
}
Also used : SecureRandom(java.security.SecureRandom)

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