Java Code Examples for sun.security.jca.JCAUtil#getSecureRandom()

The following examples show how to use sun.security.jca.JCAUtil#getSecureRandom() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: DSAKeyPairGenerator.java    From jdk8u-jdk with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Generates a pair of keys usable by any JavaSecurity compliant
 * DSA implementation.
 */
public KeyPair generateKeyPair() {
    if (random == null) {
        random = JCAUtil.getSecureRandom();
    }
    DSAParameterSpec spec;
    try {
        if (forceNewParameters) {
            // generate new parameters each time
            spec = ParameterCache.getNewDSAParameterSpec(plen, qlen, random);
        } else {
            if (params == null) {
                params =
                    ParameterCache.getDSAParameterSpec(plen, qlen, random);
            }
            spec = params;
        }
    } catch (GeneralSecurityException e) {
        throw new ProviderException(e);
    }
    return generateKeyPair(spec.getP(), spec.getQ(), spec.getG(), random);
}
 
Example 2
Source File: DSAKeyPairGenerator.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Generates a pair of keys usable by any JavaSecurity compliant
 * DSA implementation.
 */
public KeyPair generateKeyPair() {
    if (random == null) {
        random = JCAUtil.getSecureRandom();
    }
    DSAParameterSpec spec;
    try {
        if (forceNewParameters) {
            // generate new parameters each time
            spec = ParameterCache.getNewDSAParameterSpec(plen, qlen, random);
        } else {
            if (params == null) {
                params =
                    ParameterCache.getDSAParameterSpec(plen, qlen, random);
            }
            spec = params;
        }
    } catch (GeneralSecurityException e) {
        throw new ProviderException(e);
    }
    return generateKeyPair(spec.getP(), spec.getQ(), spec.getG(), random);
}
 
Example 3
Source File: ECDSASignature.java    From jdk8u-dev-jdk with GNU General Public License v2.0 6 votes vote down vote up
@Override
protected byte[] engineSign() throws SignatureException {
    byte[] s = privateKey.getS().toByteArray();
    ECParameterSpec params = privateKey.getParams();
    // DER OID
    byte[] encodedParams = ECUtil.encodeECParameterSpec(null, params);
    int keySize = params.getCurve().getField().getFieldSize();

    // seed is twice the key size (in bytes) plus 1
    byte[] seed = new byte[(((keySize + 7) >> 3) + 1) * 2];
    if (random == null) {
        random = JCAUtil.getSecureRandom();
    }
    random.nextBytes(seed);

    try {

        return encodeSignature(
            signDigest(getDigestValue(), s, encodedParams, seed));

    } catch (GeneralSecurityException e) {
        throw new SignatureException("Could not sign data", e);
    }
}
 
Example 4
Source File: DSAKeyPairGenerator.java    From jdk8u-dev-jdk with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Generates a pair of keys usable by any JavaSecurity compliant
 * DSA implementation.
 */
public KeyPair generateKeyPair() {
    if (random == null) {
        random = JCAUtil.getSecureRandom();
    }
    DSAParameterSpec spec;
    try {
        if (forceNewParameters) {
            // generate new parameters each time
            spec = ParameterCache.getNewDSAParameterSpec(plen, qlen, random);
        } else {
            if (params == null) {
                params =
                    ParameterCache.getDSAParameterSpec(plen, qlen, random);
            }
            spec = params;
        }
    } catch (GeneralSecurityException e) {
        throw new ProviderException(e);
    }
    return generateKeyPair(spec.getP(), spec.getQ(), spec.getG(), random);
}
 
Example 5
Source File: ECDSASignature.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
@Override
protected byte[] engineSign() throws SignatureException {

    if (random == null) {
        random = JCAUtil.getSecureRandom();
    }

    byte[] digest = getDigestValue();
    Optional<byte[]> sigOpt = signDigestImpl(privateKey, digest, random);
    byte[] sig;
    if (sigOpt.isPresent()) {
        sig = sigOpt.get();
    } else {
        sig = signDigestNative(privateKey, digest, random);
    }

    return ECUtil.encodeSignature(sig);
}
 
Example 6
Source File: ECDSASignature.java    From jdk8u-jdk with GNU General Public License v2.0 6 votes vote down vote up
@Override
protected byte[] engineSign() throws SignatureException {
    byte[] s = privateKey.getS().toByteArray();
    ECParameterSpec params = privateKey.getParams();
    // DER OID
    byte[] encodedParams = ECUtil.encodeECParameterSpec(null, params);
    int keySize = params.getCurve().getField().getFieldSize();

    // seed is twice the key size (in bytes) plus 1
    byte[] seed = new byte[(((keySize + 7) >> 3) + 1) * 2];
    if (random == null) {
        random = JCAUtil.getSecureRandom();
    }
    random.nextBytes(seed);

    try {

        return encodeSignature(
            signDigest(getDigestValue(), s, encodedParams, seed));

    } catch (GeneralSecurityException e) {
        throw new SignatureException("Could not sign data", e);
    }
}
 
Example 7
Source File: Token.java    From dragonwell8_jdk with GNU General Public License v2.0 5 votes vote down vote up
boolean supportsRawSecretKeyImport() {
    if (supportsRawSecretKeyImport == null) {
        SecureRandom random = JCAUtil.getSecureRandom();
        byte[] encoded = new byte[48];
        random.nextBytes(encoded);

        CK_ATTRIBUTE[] attributes = new CK_ATTRIBUTE[3];
        attributes[0] = new CK_ATTRIBUTE(CKA_CLASS, CKO_SECRET_KEY);
        attributes[1] = new CK_ATTRIBUTE(CKA_KEY_TYPE, CKK_GENERIC_SECRET);
        attributes[2] = new CK_ATTRIBUTE(CKA_VALUE, encoded);

        Session session = null;
        try {
            attributes = getAttributes(O_IMPORT,
                    CKO_SECRET_KEY, CKK_GENERIC_SECRET, attributes);
            session = getObjSession();
            long keyID = p11.C_CreateObject(session.id(), attributes);

            supportsRawSecretKeyImport = Boolean.TRUE;
        } catch (PKCS11Exception e) {
            supportsRawSecretKeyImport = Boolean.FALSE;
        } finally {
            releaseSession(session);
        }
    }

    return supportsRawSecretKeyImport;
}
 
Example 8
Source File: DSA.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
protected SecureRandom getSigningRandom() {
    if (signingRandom == null) {
        if (appRandom != null) {
            signingRandom = appRandom;
        } else {
            signingRandom = JCAUtil.getSecureRandom();
        }
    }
    return signingRandom;
}
 
Example 9
Source File: Token.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
private synchronized byte[] getTokenId() {
    if (tokenId == null) {
        SecureRandom random = JCAUtil.getSecureRandom();
        tokenId = new byte[20];
        random.nextBytes(tokenId);
        serializedTokens.add(new WeakReference<Token>(this));
    }
    return tokenId;
}
 
Example 10
Source File: RSAPadding.java    From openjdk-8 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * PKCS#1 v1.5 padding (blocktype 1 and 2).
 */
private byte[] padV15(byte[] data) throws BadPaddingException {
    byte[] padded = new byte[paddedSize];
    System.arraycopy(data, 0, padded, paddedSize - data.length, data.length);
    int psSize = paddedSize - 3 - data.length;
    int k = 0;
    padded[k++] = 0;
    padded[k++] = (byte)type;
    if (type == PAD_BLOCKTYPE_1) {
        // blocktype 1: all padding bytes are 0xff
        while (psSize-- > 0) {
            padded[k++] = (byte)0xff;
        }
    } else {
        // blocktype 2: padding bytes are random non-zero bytes
        if (random == null) {
            random = JCAUtil.getSecureRandom();
        }
        // generate non-zero padding bytes
        // use a buffer to reduce calls to SecureRandom
        byte[] r = new byte[64];
        int i = -1;
        while (psSize-- > 0) {
            int b;
            do {
                if (i < 0) {
                    random.nextBytes(r);
                    i = r.length - 1;
                }
                b = r[i--] & 0xff;
            } while (b == 0);
            padded[k++] = (byte)b;
        }
    }
    return padded;
}
 
Example 11
Source File: ECKeyPairGenerator.java    From jdk8u60 with GNU General Public License v2.0 5 votes vote down vote up
@Override
public KeyPair generateKeyPair() {

    byte[] encodedParams =
        ECUtil.encodeECParameterSpec(null, (ECParameterSpec)params);

    // seed is twice the key size (in bytes) plus 1
    byte[] seed = new byte[(((keySize + 7) >> 3) + 1) * 2];
    if (random == null) {
        random = JCAUtil.getSecureRandom();
    }
    random.nextBytes(seed);

    try {

        Object[] keyBytes = generateECKeyPair(keySize, encodedParams, seed);

        // The 'params' object supplied above is equivalent to the native
        // one so there is no need to fetch it.
        // keyBytes[0] is the encoding of the native private key
        BigInteger s = new BigInteger(1, (byte[])keyBytes[0]);

        PrivateKey privateKey =
            new ECPrivateKeyImpl(s, (ECParameterSpec)params);

        // keyBytes[1] is the encoding of the native public key
        ECPoint w = ECUtil.decodePoint((byte[])keyBytes[1],
            ((ECParameterSpec)params).getCurve());
        PublicKey publicKey =
            new ECPublicKeyImpl(w, (ECParameterSpec)params);

        return new KeyPair(publicKey, privateKey);

    } catch (Exception e) {
        throw new ProviderException(e);
    }
}
 
Example 12
Source File: DSA.java    From dragonwell8_jdk with GNU General Public License v2.0 5 votes vote down vote up
protected SecureRandom getSigningRandom() {
    if (signingRandom == null) {
        if (appRandom != null) {
            signingRandom = appRandom;
        } else {
            signingRandom = JCAUtil.getSecureRandom();
        }
    }
    return signingRandom;
}
 
Example 13
Source File: Token.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 5 votes vote down vote up
private synchronized byte[] getTokenId() {
    if (tokenId == null) {
        SecureRandom random = JCAUtil.getSecureRandom();
        tokenId = new byte[20];
        random.nextBytes(tokenId);
        serializedTokens.add(new WeakReference<Token>(this));
    }
    return tokenId;
}
 
Example 14
Source File: RSAPSSSignature.java    From jdk8u_jdk with GNU General Public License v2.0 5 votes vote down vote up
@Override
protected void engineInitSign(PrivateKey privateKey, SecureRandom random)
        throws InvalidKeyException {
    if (!(privateKey instanceof RSAPrivateKey)) {
        throw new InvalidKeyException("key must be RSAPrivateKey");
    }
    this.privKey = (RSAPrivateKey) isValid((RSAKey)privateKey);
    this.pubKey = null;
    this.random =
        (random == null? JCAUtil.getSecureRandom() : random);
    resetDigest();
}
 
Example 15
Source File: RSAPadding.java    From hottub with GNU General Public License v2.0 4 votes vote down vote up
/**
 * PKCS#1 v2.0 OAEP padding (MGF1).
 * Paragraph references refer to PKCS#1 v2.1 (June 14, 2002)
 */
private byte[] padOAEP(byte[] M) throws BadPaddingException {
    if (random == null) {
        random = JCAUtil.getSecureRandom();
    }
    int hLen = lHash.length;

    // 2.d: generate a random octet string seed of length hLen
    // if necessary
    byte[] seed = new byte[hLen];
    random.nextBytes(seed);

    // buffer for encoded message EM
    byte[] EM = new byte[paddedSize];

    // start and length of seed (as index into EM)
    int seedStart = 1;
    int seedLen = hLen;

    // copy seed into EM
    System.arraycopy(seed, 0, EM, seedStart, seedLen);

    // start and length of data block DB in EM
    // we place it inside of EM to reduce copying
    int dbStart = hLen + 1;
    int dbLen = EM.length - dbStart;

    // start of message M in EM
    int mStart = paddedSize - M.length;

    // build DB
    // 2.b: Concatenate lHash, PS, a single octet with hexadecimal value
    // 0x01, and the message M to form a data block DB of length
    // k - hLen -1 octets as DB = lHash || PS || 0x01 || M
    // (note that PS is all zeros)
    System.arraycopy(lHash, 0, EM, dbStart, hLen);
    EM[mStart - 1] = 1;
    System.arraycopy(M, 0, EM, mStart, M.length);

    // produce maskedDB
    mgf1(EM, seedStart, seedLen, EM, dbStart, dbLen);

    // produce maskSeed
    mgf1(EM, dbStart, dbLen, EM, seedStart, seedLen);

    return EM;
}
 
Example 16
Source File: RSAPadding.java    From openjdk-jdk9 with GNU General Public License v2.0 4 votes vote down vote up
/**
 * PKCS#1 v2.0 OAEP padding (MGF1).
 * Paragraph references refer to PKCS#1 v2.1 (June 14, 2002)
 */
private byte[] padOAEP(byte[] M) throws BadPaddingException {
    if (random == null) {
        random = JCAUtil.getSecureRandom();
    }
    int hLen = lHash.length;

    // 2.d: generate a random octet string seed of length hLen
    // if necessary
    byte[] seed = new byte[hLen];
    random.nextBytes(seed);

    // buffer for encoded message EM
    byte[] EM = new byte[paddedSize];

    // start and length of seed (as index into EM)
    int seedStart = 1;
    int seedLen = hLen;

    // copy seed into EM
    System.arraycopy(seed, 0, EM, seedStart, seedLen);

    // start and length of data block DB in EM
    // we place it inside of EM to reduce copying
    int dbStart = hLen + 1;
    int dbLen = EM.length - dbStart;

    // start of message M in EM
    int mStart = paddedSize - M.length;

    // build DB
    // 2.b: Concatenate lHash, PS, a single octet with hexadecimal value
    // 0x01, and the message M to form a data block DB of length
    // k - hLen -1 octets as DB = lHash || PS || 0x01 || M
    // (note that PS is all zeros)
    System.arraycopy(lHash, 0, EM, dbStart, hLen);
    EM[mStart - 1] = 1;
    System.arraycopy(M, 0, EM, mStart, M.length);

    // produce maskedDB
    mgf1(EM, seedStart, seedLen, EM, dbStart, dbLen);

    // produce maskSeed
    mgf1(EM, dbStart, dbLen, EM, seedStart, seedLen);

    return EM;
}
 
Example 17
Source File: RSACore.java    From openjdk-jdk8u with GNU General Public License v2.0 4 votes vote down vote up
BlindingParameters(BigInteger e, BigInteger d, BigInteger n) {
    this.u = null;
    this.v = null;
    this.e = e;
    this.d = d;

    int len = n.bitLength();
    SecureRandom random = JCAUtil.getSecureRandom();
    u = new BigInteger(len, random).mod(n);
    // Although the possibility is very much limited that u is zero
    // or is not relatively prime to n, we still want to be careful
    // about the special value.
    //
    // Secure random generation is expensive, try to use BigInteger.ONE
    // this time if this new generated random number is zero or is not
    // relatively prime to n.  Next time, new generated secure random
    // number will be used instead.
    if (u.equals(BigInteger.ZERO)) {
        u = BigInteger.ONE;     // use 1 this time
    }

    try {
        // The call to BigInteger.modInverse() checks that u is
        // relatively prime to n.  Otherwise, ArithmeticException is
        // thrown.
        v = u.modInverse(n);
    } catch (ArithmeticException ae) {
        // if u is not relatively prime to n, use 1 this time
        u = BigInteger.ONE;
        v = BigInteger.ONE;
    }

    if (e != null) {
        u = u.modPow(e, n);   // e: the public exponent
                              // u: random ^ e
                              // v: random ^ (-1)
    } else {
        v = v.modPow(d, n);   // d: the private exponent
                              // u: random
                              // v: random ^ (-d)
    }
}
 
Example 18
Source File: RSAPadding.java    From jdk8u_jdk with GNU General Public License v2.0 4 votes vote down vote up
/**
 * PKCS#1 v2.0 OAEP padding (MGF1).
 * Paragraph references refer to PKCS#1 v2.1 (June 14, 2002)
 */
private byte[] padOAEP(byte[] M) throws BadPaddingException {
    if (random == null) {
        random = JCAUtil.getSecureRandom();
    }
    int hLen = lHash.length;

    // 2.d: generate a random octet string seed of length hLen
    // if necessary
    byte[] seed = new byte[hLen];
    random.nextBytes(seed);

    // buffer for encoded message EM
    byte[] EM = new byte[paddedSize];

    // start and length of seed (as index into EM)
    int seedStart = 1;
    int seedLen = hLen;

    // copy seed into EM
    System.arraycopy(seed, 0, EM, seedStart, seedLen);

    // start and length of data block DB in EM
    // we place it inside of EM to reduce copying
    int dbStart = hLen + 1;
    int dbLen = EM.length - dbStart;

    // start of message M in EM
    int mStart = paddedSize - M.length;

    // build DB
    // 2.b: Concatenate lHash, PS, a single octet with hexadecimal value
    // 0x01, and the message M to form a data block DB of length
    // k - hLen -1 octets as DB = lHash || PS || 0x01 || M
    // (note that PS is all zeros)
    System.arraycopy(lHash, 0, EM, dbStart, hLen);
    EM[mStart - 1] = 1;
    System.arraycopy(M, 0, EM, mStart, M.length);

    // produce maskedDB
    mgf.generateAndXor(EM, seedStart, seedLen, dbLen, EM, dbStart);

    // produce maskSeed
    mgf.generateAndXor(EM, dbStart, dbLen, seedLen, EM, seedStart);

    return EM;
}
 
Example 19
Source File: KeyUtil.java    From jdk8u_jdk with GNU General Public License v2.0 3 votes vote down vote up
/**
 * Check the format of TLS PreMasterSecret.
 * <P>
 * To avoid vulnerabilities described by section 7.4.7.1, RFC 5246,
 * treating incorrectly formatted message blocks and/or mismatched
 * version numbers in a manner indistinguishable from correctly
 * formatted RSA blocks.
 *
 * RFC 5246 describes the approach as :
 *
 *  1. Generate a string R of 48 random bytes
 *
 *  2. Decrypt the message to recover the plaintext M
 *
 *  3. If the PKCS#1 padding is not correct, or the length of message
 *     M is not exactly 48 bytes:
 *        pre_master_secret = R
 *     else If ClientHello.client_version <= TLS 1.0, and version
 *     number check is explicitly disabled:
 *        premaster secret = M
 *     else If M[0..1] != ClientHello.client_version:
 *        premaster secret = R
 *     else:
 *        premaster secret = M
 *
 * Note that #2 should have completed before the call to this method.
 *
 * @param  clientVersion the version of the TLS protocol by which the
 *         client wishes to communicate during this session
 * @param  serverVersion the negotiated version of the TLS protocol which
 *         contains the lower of that suggested by the client in the client
 *         hello and the highest supported by the server.
 * @param  encoded the encoded key in its "RAW" encoding format
 * @param  isFailover whether or not the previous decryption of the
 *         encrypted PreMasterSecret message run into problem
 * @return the polished PreMasterSecret key in its "RAW" encoding format
 */
public static byte[] checkTlsPreMasterSecretKey(
        int clientVersion, int serverVersion, SecureRandom random,
        byte[] encoded, boolean isFailOver) {

    if (random == null) {
        random = JCAUtil.getSecureRandom();
    }
    byte[] replacer = new byte[48];
    random.nextBytes(replacer);

    if (!isFailOver && (encoded != null)) {
        // check the length
        if (encoded.length != 48) {
            // private, don't need to clone the byte array.
            return replacer;
        }

        int encodedVersion =
                ((encoded[0] & 0xFF) << 8) | (encoded[1] & 0xFF);
        if (clientVersion != encodedVersion) {
            if (clientVersion > 0x0301 ||               // 0x0301: TLSv1
                   serverVersion != encodedVersion) {
                encoded = replacer;
            }   // Otherwise, For compatibility, we maintain the behavior
                // that the version in pre_master_secret can be the
                // negotiated version for TLS v1.0 and SSL v3.0.
        }

        // private, don't need to clone the byte array.
        return encoded;
    }

    // private, don't need to clone the byte array.
    return replacer;
}
 
Example 20
Source File: KeyUtil.java    From hottub with GNU General Public License v2.0 3 votes vote down vote up
/**
 * Check the format of TLS PreMasterSecret.
 * <P>
 * To avoid vulnerabilities described by section 7.4.7.1, RFC 5246,
 * treating incorrectly formatted message blocks and/or mismatched
 * version numbers in a manner indistinguishable from correctly
 * formatted RSA blocks.
 *
 * RFC 5246 describes the approach as :
 *
 *  1. Generate a string R of 48 random bytes
 *
 *  2. Decrypt the message to recover the plaintext M
 *
 *  3. If the PKCS#1 padding is not correct, or the length of message
 *     M is not exactly 48 bytes:
 *        pre_master_secret = R
 *     else If ClientHello.client_version <= TLS 1.0, and version
 *     number check is explicitly disabled:
 *        premaster secret = M
 *     else If M[0..1] != ClientHello.client_version:
 *        premaster secret = R
 *     else:
 *        premaster secret = M
 *
 * Note that #2 should have completed before the call to this method.
 *
 * @param  clientVersion the version of the TLS protocol by which the
 *         client wishes to communicate during this session
 * @param  serverVersion the negotiated version of the TLS protocol which
 *         contains the lower of that suggested by the client in the client
 *         hello and the highest supported by the server.
 * @param  encoded the encoded key in its "RAW" encoding format
 * @param  isFailover whether or not the previous decryption of the
 *         encrypted PreMasterSecret message run into problem
 * @return the polished PreMasterSecret key in its "RAW" encoding format
 */
public static byte[] checkTlsPreMasterSecretKey(
        int clientVersion, int serverVersion, SecureRandom random,
        byte[] encoded, boolean isFailOver) {

    if (random == null) {
        random = JCAUtil.getSecureRandom();
    }
    byte[] replacer = new byte[48];
    random.nextBytes(replacer);

    if (!isFailOver && (encoded != null)) {
        // check the length
        if (encoded.length != 48) {
            // private, don't need to clone the byte array.
            return replacer;
        }

        int encodedVersion =
                ((encoded[0] & 0xFF) << 8) | (encoded[1] & 0xFF);
        if (clientVersion != encodedVersion) {
            if (clientVersion > 0x0301 ||               // 0x0301: TLSv1
                   serverVersion != encodedVersion) {
                encoded = replacer;
            }   // Otherwise, For compatibility, we maintain the behavior
                // that the version in pre_master_secret can be the
                // negotiated version for TLS v1.0 and SSL v3.0.
        }

        // private, don't need to clone the byte array.
        return encoded;
    }

    // private, don't need to clone the byte array.
    return replacer;
}