sun.security.util.KeyUtil Java Examples

The following examples show how to use sun.security.util.KeyUtil. 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: ShortRSAKeyWithinTLS.java    From jdk8u_jdk with GNU General Public License v2.0 7 votes vote down vote up
private void checkKeySize(KeyStore ks) throws Exception {
    PrivateKey privateKey = null;
    PublicKey publicKey = null;

    if (ks.containsAlias(keyAlias)) {
        System.out.println("Loaded entry: " + keyAlias);
        privateKey = (PrivateKey)ks.getKey(keyAlias, null);
        publicKey = (PublicKey)ks.getCertificate(keyAlias).getPublicKey();

        int privateKeySize = KeyUtil.getKeySize(privateKey);
        if (privateKeySize != keySize) {
            throw new Exception("Expected key size is " + keySize +
                    ", but the private key size is " + privateKeySize);
        }

        int publicKeySize = KeyUtil.getKeySize(publicKey);
        if (publicKeySize != keySize) {
            throw new Exception("Expected key size is " + keySize +
                    ", but the public key size is " + publicKeySize);
        }
    }
}
 
Example #2
Source File: HandshakeMessage.java    From jdk8u60 with GNU General Public License v2.0 6 votes vote down vote up
DH_ServerKeyExchange(HandshakeInStream input,
        ProtocolVersion protocolVersion)
        throws IOException, GeneralSecurityException {

    this.protocolVersion = protocolVersion;
    this.preferableSignatureAlgorithm = null;

    dh_p = input.getBytes16();
    dh_g = input.getBytes16();
    dh_Ys = input.getBytes16();
    KeyUtil.validate(new DHPublicKeySpec(new BigInteger(1, dh_Ys),
                                         new BigInteger(1, dh_p),
                                         new BigInteger(1, dh_g)));

    signature = null;
}
 
Example #3
Source File: HandshakeMessage.java    From jdk8u-jdk with GNU General Public License v2.0 6 votes vote down vote up
DH_ServerKeyExchange(HandshakeInStream input,
        ProtocolVersion protocolVersion)
        throws IOException, GeneralSecurityException {

    this.protocolVersion = protocolVersion;
    this.preferableSignatureAlgorithm = null;

    dh_p = input.getBytes16();
    dh_g = input.getBytes16();
    dh_Ys = input.getBytes16();
    KeyUtil.validate(new DHPublicKeySpec(new BigInteger(1, dh_Ys),
                                         new BigInteger(1, dh_p),
                                         new BigInteger(1, dh_g)));

    signature = null;
}
 
Example #4
Source File: HandshakeMessage.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
DH_ServerKeyExchange(HandshakeInStream input,
        ProtocolVersion protocolVersion)
        throws IOException, GeneralSecurityException {

    this.protocolVersion = protocolVersion;
    this.preferableSignatureAlgorithm = null;

    dh_p = input.getBytes16();
    dh_g = input.getBytes16();
    dh_Ys = input.getBytes16();
    KeyUtil.validate(new DHPublicKeySpec(new BigInteger(1, dh_Ys),
                                         new BigInteger(1, dh_p),
                                         new BigInteger(1, dh_g)));

    signature = null;
}
 
Example #5
Source File: CSignature.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
@Override
protected void engineInitVerify(PublicKey key) throws InvalidKeyException {
    if (key == null) {
        throw new InvalidKeyException("Key cannot be null");
    }
    // This signature accepts only ECPublicKey
    if ((key instanceof ECPublicKey) == false) {
        throw new InvalidKeyException("Key type not supported: "
                + key.getClass());
    }

    if ((key instanceof CPublicKey) == false) {
        try {
            publicKey = importECPublicKey("EC",
                    CKey.generateECBlob(key),
                    KeyUtil.getKeySize(key));
        } catch (KeyStoreException e) {
            throw new InvalidKeyException(e);
        }
    } else {
        publicKey = (CPublicKey) key;
    }

    this.privateKey = null;
    resetDigest();
}
 
Example #6
Source File: HandshakeMessage.java    From jdk8u_jdk with GNU General Public License v2.0 6 votes vote down vote up
DH_ServerKeyExchange(HandshakeInStream input,
        ProtocolVersion protocolVersion)
        throws IOException, GeneralSecurityException {

    this.protocolVersion = protocolVersion;
    this.preferableSignatureAlgorithm = null;

    dh_p = input.getBytes16();
    dh_g = input.getBytes16();
    dh_Ys = input.getBytes16();
    KeyUtil.validate(new DHPublicKeySpec(new BigInteger(1, dh_Ys),
                                         new BigInteger(1, dh_p),
                                         new BigInteger(1, dh_g)));

    signature = null;
}
 
Example #7
Source File: HandshakeMessage.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 6 votes vote down vote up
DH_ServerKeyExchange(HandshakeInStream input,
        ProtocolVersion protocolVersion)
        throws IOException, GeneralSecurityException {

    this.protocolVersion = protocolVersion;
    this.preferableSignatureAlgorithm = null;

    dh_p = input.getBytes16();
    dh_g = input.getBytes16();
    dh_Ys = input.getBytes16();
    KeyUtil.validate(new DHPublicKeySpec(new BigInteger(1, dh_Ys),
                                         new BigInteger(1, dh_p),
                                         new BigInteger(1, dh_g)));

    signature = null;
}
 
Example #8
Source File: ShortRSAKeyWithinTLS.java    From dragonwell8_jdk with GNU General Public License v2.0 6 votes vote down vote up
private void checkKeySize(KeyStore ks) throws Exception {
    PrivateKey privateKey = null;
    PublicKey publicKey = null;

    if (ks.containsAlias(keyAlias)) {
        System.out.println("Loaded entry: " + keyAlias);
        privateKey = (PrivateKey)ks.getKey(keyAlias, null);
        publicKey = (PublicKey)ks.getCertificate(keyAlias).getPublicKey();

        int privateKeySize = KeyUtil.getKeySize(privateKey);
        if (privateKeySize != keySize) {
            throw new Exception("Expected key size is " + keySize +
                    ", but the private key size is " + privateKeySize);
        }

        int publicKeySize = KeyUtil.getKeySize(publicKey);
        if (publicKeySize != keySize) {
            throw new Exception("Expected key size is " + keySize +
                    ", but the public key size is " + publicKeySize);
        }
    }
}
 
Example #9
Source File: P11Signature.java    From openjdk-8-source with GNU General Public License v2.0 6 votes vote down vote up
private byte[] asn1ToECDSA(byte[] signature) throws SignatureException {
    try {
        DerInputStream in = new DerInputStream(signature);
        DerValue[] values = in.getSequence(2);
        BigInteger r = values[0].getPositiveBigInteger();
        BigInteger s = values[1].getPositiveBigInteger();
        // trim leading zeroes
        byte[] br = KeyUtil.trimZeroes(r.toByteArray());
        byte[] bs = KeyUtil.trimZeroes(s.toByteArray());
        int k = Math.max(br.length, bs.length);
        // r and s each occupy half the array
        byte[] res = new byte[k << 1];
        System.arraycopy(br, 0, res, k - br.length, br.length);
        System.arraycopy(bs, 0, res, res.length - bs.length, bs.length);
        return res;
    } catch (Exception e) {
        throw new SignatureException("invalid encoding for signature", e);
    }
}
 
Example #10
Source File: ShortRSAKeyWithinTLS.java    From hottub with GNU General Public License v2.0 6 votes vote down vote up
private void checkKeySize(KeyStore ks) throws Exception {
    PrivateKey privateKey = null;
    PublicKey publicKey = null;

    if (ks.containsAlias(keyAlias)) {
        System.out.println("Loaded entry: " + keyAlias);
        privateKey = (PrivateKey)ks.getKey(keyAlias, null);
        publicKey = (PublicKey)ks.getCertificate(keyAlias).getPublicKey();

        int privateKeySize = KeyUtil.getKeySize(privateKey);
        if (privateKeySize != keySize) {
            throw new Exception("Expected key size is " + keySize +
                    ", but the private key size is " + privateKeySize);
        }

        int publicKeySize = KeyUtil.getKeySize(publicKey);
        if (publicKeySize != keySize) {
            throw new Exception("Expected key size is " + keySize +
                    ", but the public key size is " + publicKeySize);
        }
    }
}
 
Example #11
Source File: ShortRSAKeyWithinTLS.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
private void checkKeySize(KeyStore ks) throws Exception {
    PrivateKey privateKey = null;
    PublicKey publicKey = null;

    if (ks.containsAlias(keyAlias)) {
        System.out.println("Loaded entry: " + keyAlias);
        privateKey = (PrivateKey)ks.getKey(keyAlias, null);
        publicKey = (PublicKey)ks.getCertificate(keyAlias).getPublicKey();

        int privateKeySize = KeyUtil.getKeySize(privateKey);
        if (privateKeySize != keySize) {
            throw new Exception("Expected key size is " + keySize +
                    ", but the private key size is " + privateKeySize);
        }

        int publicKeySize = KeyUtil.getKeySize(publicKey);
        if (publicKeySize != keySize) {
            throw new Exception("Expected key size is " + keySize +
                    ", but the public key size is " + publicKeySize);
        }
    }
}
 
Example #12
Source File: HandshakeMessage.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
DH_ServerKeyExchange(HandshakeInStream input,
        ProtocolVersion protocolVersion)
        throws IOException, GeneralSecurityException {

    this.protocolVersion = protocolVersion;
    this.preferableSignatureAlgorithm = null;

    dh_p = input.getBytes16();
    dh_g = input.getBytes16();
    dh_Ys = input.getBytes16();
    KeyUtil.validate(new DHPublicKeySpec(new BigInteger(1, dh_Ys),
                                         new BigInteger(1, dh_p),
                                         new BigInteger(1, dh_g)));

    signature = null;
}
 
Example #13
Source File: DOMSignatureMethod.java    From jdk8u_jdk with GNU General Public License v2.0 6 votes vote down vote up
/**
 * If secure validation mode is enabled, checks that the key size is
 * restricted.
 *
 * @param context the context
 * @param key the key to check
 * @throws XMLSignatureException if the key size is restricted
 */
private static void checkKeySize(XMLCryptoContext context, Key key)
    throws XMLSignatureException {
    if (Utils.secureValidation(context)) {
        int size = KeyUtil.getKeySize(key);
        if (size == -1) {
            // key size cannot be determined, so we cannot check against
            // restrictions. Note that a DSA key w/o params will be
            // rejected later if the certificate chain is validated.
            if (log.isLoggable(java.util.logging.Level.FINE)) {
                log.log(java.util.logging.Level.FINE, "Size for " +
                        key.getAlgorithm() + " key cannot be determined");
            }
            return;
        }
        if (Policy.restrictKey(key.getAlgorithm(), size)) {
            throw new XMLSignatureException(key.getAlgorithm() +
                " keys less than " +
                Policy.minKeySize(key.getAlgorithm()) + " bits are" +
                " forbidden when secure validation is enabled");
        }
    }
}
 
Example #14
Source File: ShortRSAKeyWithinTLS.java    From jdk8u-jdk with GNU General Public License v2.0 6 votes vote down vote up
private void checkKeySize(KeyStore ks) throws Exception {
    PrivateKey privateKey = null;
    PublicKey publicKey = null;

    if (ks.containsAlias(keyAlias)) {
        System.out.println("Loaded entry: " + keyAlias);
        privateKey = (PrivateKey)ks.getKey(keyAlias, null);
        publicKey = (PublicKey)ks.getCertificate(keyAlias).getPublicKey();

        int privateKeySize = KeyUtil.getKeySize(privateKey);
        if (privateKeySize != keySize) {
            throw new Exception("Expected key size is " + keySize +
                    ", but the private key size is " + privateKeySize);
        }

        int publicKeySize = KeyUtil.getKeySize(publicKey);
        if (publicKeySize != keySize) {
            throw new Exception("Expected key size is " + keySize +
                    ", but the public key size is " + publicKeySize);
        }
    }
}
 
Example #15
Source File: CSignature.java    From jdk8u_jdk with GNU General Public License v2.0 6 votes vote down vote up
@Override
protected void engineInitVerify(PublicKey key) throws InvalidKeyException {
    if (key == null) {
        throw new InvalidKeyException("Key cannot be null");
    }
    // This signature accepts only ECPublicKey
    if ((key instanceof ECPublicKey) == false) {
        throw new InvalidKeyException("Key type not supported: "
                + key.getClass());
    }

    if ((key instanceof CPublicKey) == false) {
        try {
            publicKey = importECPublicKey("EC",
                    CKey.generateECBlob(key),
                    KeyUtil.getKeySize(key));
        } catch (KeyStoreException e) {
            throw new InvalidKeyException(e);
        }
    } else {
        publicKey = (CPublicKey) key;
    }

    this.privateKey = null;
    resetDigest();
}
 
Example #16
Source File: DOMSignatureMethod.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * If secure validation mode is enabled, checks that the key size is
 * restricted.
 *
 * @param context the context
 * @param key the key to check
 * @throws XMLSignatureException if the key size is restricted
 */
private static void checkKeySize(XMLCryptoContext context, Key key)
    throws XMLSignatureException {
    if (Utils.secureValidation(context)) {
        int size = KeyUtil.getKeySize(key);
        if (size == -1) {
            // key size cannot be determined, so we cannot check against
            // restrictions. Note that a DSA key w/o params will be
            // rejected later if the certificate chain is validated.
            if (log.isLoggable(java.util.logging.Level.FINE)) {
                log.log(java.util.logging.Level.FINE, "Size for " +
                        key.getAlgorithm() + " key cannot be determined");
            }
            return;
        }
        if (Policy.restrictKey(key.getAlgorithm(), size)) {
            throw new XMLSignatureException(key.getAlgorithm() +
                " keys less than " +
                Policy.minKeySize(key.getAlgorithm()) + " bits are" +
                " forbidden when secure validation is enabled");
        }
    }
}
 
Example #17
Source File: P11Signature.java    From jdk8u60 with GNU General Public License v2.0 6 votes vote down vote up
private byte[] asn1ToECDSA(byte[] signature) throws SignatureException {
    try {
        DerInputStream in = new DerInputStream(signature);
        DerValue[] values = in.getSequence(2);
        BigInteger r = values[0].getPositiveBigInteger();
        BigInteger s = values[1].getPositiveBigInteger();
        // trim leading zeroes
        byte[] br = KeyUtil.trimZeroes(r.toByteArray());
        byte[] bs = KeyUtil.trimZeroes(s.toByteArray());
        int k = Math.max(br.length, bs.length);
        // r and s each occupy half the array
        byte[] res = new byte[k << 1];
        System.arraycopy(br, 0, res, k - br.length, br.length);
        System.arraycopy(bs, 0, res, res.length - bs.length, bs.length);
        return res;
    } catch (Exception e) {
        throw new SignatureException("invalid encoding for signature", e);
    }
}
 
Example #18
Source File: ShortRSAKeyWithinTLS.java    From jdk8u-jdk with GNU General Public License v2.0 6 votes vote down vote up
private void checkKeySize(KeyStore ks) throws Exception {
    PrivateKey privateKey = null;
    PublicKey publicKey = null;

    if (ks.containsAlias(keyAlias)) {
        System.out.println("Loaded entry: " + keyAlias);
        privateKey = (PrivateKey)ks.getKey(keyAlias, null);
        publicKey = (PublicKey)ks.getCertificate(keyAlias).getPublicKey();

        int privateKeySize = KeyUtil.getKeySize(privateKey);
        if (privateKeySize != keySize) {
            throw new Exception("Expected key size is " + keySize +
                    ", but the private key size is " + privateKeySize);
        }

        int publicKeySize = KeyUtil.getKeySize(publicKey);
        if (publicKeySize != keySize) {
            throw new Exception("Expected key size is " + keySize +
                    ", but the public key size is " + publicKeySize);
        }
    }
}
 
Example #19
Source File: DHCrypt.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
private DHPublicKeySpec generateDHPublicKeySpec(KeyPairGenerator kpg)
        throws GeneralSecurityException {

    boolean doExtraValiadtion =
                (!KeyUtil.isOracleJCEProvider(kpg.getProvider().getName()));
    for (int i = 0; i <= MAX_FAILOVER_TIMES; i++) {
        KeyPair kp = kpg.generateKeyPair();
        privateKey = kp.getPrivate();
        DHPublicKeySpec spec = getDHPublicKeySpec(kp.getPublic());

        // validate the Diffie-Hellman public key
        if (doExtraValiadtion) {
            try {
                KeyUtil.validate(spec);
            } catch (InvalidKeyException ivke) {
                if (i == MAX_FAILOVER_TIMES) {
                    throw ivke;
                }
                // otherwise, ignore the exception and try the next one
                continue;
            }
        }

        return spec;
    }

    return null;
}
 
Example #20
Source File: X509Factory.java    From Bytecoder with Apache License 2.0 5 votes vote down vote up
private void commitEvent(X509CertImpl info) {
    X509CertificateEvent xce = new X509CertificateEvent();
    if (xce.shouldCommit() || EventHelper.isLoggingSecurity()) {
        PublicKey pKey = info.getPublicKey();
        String algId = info.getSigAlgName();
        String serNum = info.getSerialNumber().toString(16);
        String subject = info.getSubjectDN().getName();
        String issuer = info.getIssuerDN().getName();
        String keyType = pKey.getAlgorithm();
        int length = KeyUtil.getKeySize(pKey);
        int hashCode = info.hashCode();
        long beginDate = info.getNotBefore().getTime();
        long endDate = info.getNotAfter().getTime();
        if (xce.shouldCommit()) {
            xce.algorithm = algId;
            xce.serialNumber = serNum;
            xce.subject = subject;
            xce.issuer = issuer;
            xce.keyType = keyType;
            xce.keyLength = length;
            xce.certificateId = hashCode;
            xce.validFrom = beginDate;
            xce.validUntil = endDate;
            xce.commit();
        }
        if (EventHelper.isLoggingSecurity()) {
            EventHelper.logX509CertificateEvent(algId,
                    serNum,
                    subject,
                    issuer,
                    keyType,
                    length,
                    hashCode,
                    beginDate,
                    endDate);
        }
    }
}
 
Example #21
Source File: Main.java    From Bytecoder with Apache License 2.0 5 votes vote down vote up
private String withWeak(Key key) {
    int kLen = KeyUtil.getKeySize(key);
    String displayAlg = fullDisplayAlgName(key);
    if (DISABLED_CHECK.permits(SIG_PRIMITIVE_SET, key)) {
        if (kLen >= 0) {
            return String.format(rb.getString("key.bit"), kLen, displayAlg);
        } else {
            return String.format(rb.getString("unknown.size.1"), displayAlg);
        }
    } else {
        return String.format(rb.getString("key.bit.weak"), kLen, displayAlg);
    }
}
 
Example #22
Source File: DHCrypt.java    From hottub with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Get the secret data that has been agreed on through Diffie-Hellman
 * key agreement protocol.  Note that in the two party protocol, if
 * the peer keys are already known, no other data needs to be sent in
 * order to agree on a secret.  That is, a secured message may be
 * sent without any mandatory round-trip overheads.
 *
 * <P>It is illegal to call this member function if the private key
 * has not been set (or generated).
 *
 * @param  peerPublicKey the peer's public key.
 * @param  keyIsValidated whether the {@code peerPublicKey} has beed
 *         validated
 * @return the secret, which is an unsigned big-endian integer
 *         the same size as the Diffie-Hellman modulus.
 */
SecretKey getAgreedSecret(BigInteger peerPublicValue,
        boolean keyIsValidated) throws SSLHandshakeException {
    try {
        KeyFactory kf = JsseJce.getKeyFactory("DiffieHellman");
        DHPublicKeySpec spec =
                    new DHPublicKeySpec(peerPublicValue, modulus, base);
        PublicKey publicKey = kf.generatePublic(spec);
        KeyAgreement ka = JsseJce.getKeyAgreement("DiffieHellman");

        // validate the Diffie-Hellman public key
        if (!keyIsValidated &&
                !KeyUtil.isOracleJCEProvider(ka.getProvider().getName())) {
            try {
                KeyUtil.validate(spec);
            } catch (InvalidKeyException ike) {
                // prefer handshake_failure alert to internal_error alert
                throw new SSLHandshakeException(ike.getMessage());
            }
        }

        ka.init(privateKey);
        ka.doPhase(publicKey, true);
        return ka.generateSecret("TlsPremasterSecret");
    } catch (GeneralSecurityException e) {
        throw (SSLHandshakeException) new SSLHandshakeException(
            "Could not generate secret").initCause(e);
    }
}
 
Example #23
Source File: DHCrypt.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Get the secret data that has been agreed on through Diffie-Hellman
 * key agreement protocol.  Note that in the two party protocol, if
 * the peer keys are already known, no other data needs to be sent in
 * order to agree on a secret.  That is, a secured message may be
 * sent without any mandatory round-trip overheads.
 *
 * <P>It is illegal to call this member function if the private key
 * has not been set (or generated).
 *
 * @param  peerPublicKey the peer's public key.
 * @param  keyIsValidated whether the {@code peerPublicKey} has beed
 *         validated
 * @return the secret, which is an unsigned big-endian integer
 *         the same size as the Diffie-Hellman modulus.
 */
SecretKey getAgreedSecret(BigInteger peerPublicValue,
        boolean keyIsValidated) throws SSLHandshakeException {
    try {
        KeyFactory kf = JsseJce.getKeyFactory("DiffieHellman");
        DHPublicKeySpec spec =
                    new DHPublicKeySpec(peerPublicValue, modulus, base);
        PublicKey publicKey = kf.generatePublic(spec);
        KeyAgreement ka = JsseJce.getKeyAgreement("DiffieHellman");

        // validate the Diffie-Hellman public key
        if (!keyIsValidated &&
                !KeyUtil.isOracleJCEProvider(ka.getProvider().getName())) {
            try {
                KeyUtil.validate(spec);
            } catch (InvalidKeyException ike) {
                // prefer handshake_failure alert to internal_error alert
                throw new SSLHandshakeException(ike.getMessage());
            }
        }

        ka.init(privateKey);
        ka.doPhase(publicKey, true);
        return ka.generateSecret("TlsPremasterSecret");
    } catch (GeneralSecurityException e) {
        throw (SSLHandshakeException) new SSLHandshakeException(
            "Could not generate secret").initCause(e);
    }
}
 
Example #24
Source File: DHCrypt.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Get the secret data that has been agreed on through Diffie-Hellman
 * key agreement protocol.  Note that in the two party protocol, if
 * the peer keys are already known, no other data needs to be sent in
 * order to agree on a secret.  That is, a secured message may be
 * sent without any mandatory round-trip overheads.
 *
 * <P>It is illegal to call this member function if the private key
 * has not been set (or generated).
 *
 * @param  peerPublicKey the peer's public key.
 * @param  keyIsValidated whether the {@code peerPublicKey} has beed
 *         validated
 * @return the secret, which is an unsigned big-endian integer
 *         the same size as the Diffie-Hellman modulus.
 */
SecretKey getAgreedSecret(BigInteger peerPublicValue,
        boolean keyIsValidated) throws SSLHandshakeException {
    try {
        KeyFactory kf = JsseJce.getKeyFactory("DiffieHellman");
        DHPublicKeySpec spec =
                    new DHPublicKeySpec(peerPublicValue, modulus, base);
        PublicKey publicKey = kf.generatePublic(spec);
        KeyAgreement ka = JsseJce.getKeyAgreement("DiffieHellman");

        // validate the Diffie-Hellman public key
        if (!keyIsValidated &&
                !KeyUtil.isOracleJCEProvider(ka.getProvider().getName())) {
            try {
                KeyUtil.validate(spec);
            } catch (InvalidKeyException ike) {
                // prefer handshake_failure alert to internal_error alert
                throw new SSLHandshakeException(ike.getMessage());
            }
        }

        ka.init(privateKey);
        ka.doPhase(publicKey, true);
        return ka.generateSecret("TlsPremasterSecret");
    } catch (GeneralSecurityException e) {
        throw (SSLHandshakeException) new SSLHandshakeException(
            "Could not generate secret").initCause(e);
    }
}
 
Example #25
Source File: DHCrypt.java    From jdk8u_jdk with GNU General Public License v2.0 5 votes vote down vote up
private DHPublicKeySpec generateDHPublicKeySpec(KeyPairGenerator kpg)
        throws GeneralSecurityException {

    boolean doExtraValiadtion =
                (!KeyUtil.isOracleJCEProvider(kpg.getProvider().getName()));
    for (int i = 0; i <= MAX_FAILOVER_TIMES; i++) {
        KeyPair kp = kpg.generateKeyPair();
        privateKey = kp.getPrivate();
        DHPublicKeySpec spec = getDHPublicKeySpec(kp.getPublic());

        // validate the Diffie-Hellman public key
        if (doExtraValiadtion) {
            try {
                KeyUtil.validate(spec);
            } catch (InvalidKeyException ivke) {
                if (i == MAX_FAILOVER_TIMES) {
                    throw ivke;
                }
                // otherwise, ignore the exception and try the next one
                continue;
            }
        }

        return spec;
    }

    return null;
}
 
Example #26
Source File: DHCrypt.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 5 votes vote down vote up
private DHPublicKeySpec generateDHPublicKeySpec(KeyPairGenerator kpg)
        throws GeneralSecurityException {

    boolean doExtraValiadtion =
                (!KeyUtil.isOracleJCEProvider(kpg.getProvider().getName()));
    for (int i = 0; i <= MAX_FAILOVER_TIMES; i++) {
        KeyPair kp = kpg.generateKeyPair();
        privateKey = kp.getPrivate();
        DHPublicKeySpec spec = getDHPublicKeySpec(kp.getPublic());

        // validate the Diffie-Hellman public key
        if (doExtraValiadtion) {
            try {
                KeyUtil.validate(spec);
            } catch (InvalidKeyException ivke) {
                if (i == MAX_FAILOVER_TIMES) {
                    throw ivke;
                }
                // otherwise, ignore the exception and try the next one
                continue;
            }
        }

        return spec;
    }

    return null;
}
 
Example #27
Source File: DHCrypt.java    From jdk8u-dev-jdk with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Get the secret data that has been agreed on through Diffie-Hellman
 * key agreement protocol.  Note that in the two party protocol, if
 * the peer keys are already known, no other data needs to be sent in
 * order to agree on a secret.  That is, a secured message may be
 * sent without any mandatory round-trip overheads.
 *
 * <P>It is illegal to call this member function if the private key
 * has not been set (or generated).
 *
 * @param  peerPublicKey the peer's public key.
 * @param  keyIsValidated whether the {@code peerPublicKey} has beed
 *         validated
 * @return the secret, which is an unsigned big-endian integer
 *         the same size as the Diffie-Hellman modulus.
 */
SecretKey getAgreedSecret(BigInteger peerPublicValue,
        boolean keyIsValidated) throws SSLHandshakeException {
    try {
        KeyFactory kf = JsseJce.getKeyFactory("DiffieHellman");
        DHPublicKeySpec spec =
                    new DHPublicKeySpec(peerPublicValue, modulus, base);
        PublicKey publicKey = kf.generatePublic(spec);
        KeyAgreement ka = JsseJce.getKeyAgreement("DiffieHellman");

        // validate the Diffie-Hellman public key
        if (!keyIsValidated &&
                !KeyUtil.isOracleJCEProvider(ka.getProvider().getName())) {
            try {
                KeyUtil.validate(spec);
            } catch (InvalidKeyException ike) {
                // prefer handshake_failure alert to internal_error alert
                throw new SSLHandshakeException(ike.getMessage());
            }
        }

        ka.init(privateKey);
        ka.doPhase(publicKey, true);
        return ka.generateSecret("TlsPremasterSecret");
    } catch (GeneralSecurityException e) {
        throw (SSLHandshakeException) new SSLHandshakeException(
            "Could not generate secret").initCause(e);
    }
}
 
Example #28
Source File: SignatureAndHashAlgorithm.java    From hottub with GNU General Public License v2.0 5 votes vote down vote up
private static int getMaxDigestLength(PrivateKey signingKey) {
    int maxDigestLength = Integer.MAX_VALUE;

    // only need to check RSA algorithm at present.
    if (signingKey != null &&
            "rsa".equalsIgnoreCase(signingKey.getAlgorithm())) {
        /*
         * RSA keys of 512 bits have been shown to be practically
         * breakable, it does not make much sense to use the strong
         * hash algorithm for keys whose key size less than 512 bits.
         * So it is not necessary to caculate the required max digest
         * length exactly.
         *
         * If key size is greater than or equals to 768, there is no max
         * digest length limitation in currect implementation.
         *
         * If key size is greater than or equals to 512, but less than
         * 768, the digest length should be less than or equal to 32 bytes.
         *
         * If key size is less than 512, the  digest length should be
         * less than or equal to 20 bytes.
         */
        int keySize = KeyUtil.getKeySize(signingKey);
        if (keySize >= 768) {
            maxDigestLength = HashAlgorithm.SHA512.length;
        } else if ((keySize >= 512) && (keySize < 768)) {
            maxDigestLength = HashAlgorithm.SHA256.length;
        } else if ((keySize > 0) && (keySize < 512)) {
            maxDigestLength = HashAlgorithm.SHA1.length;
        }   // Otherwise, cannot determine the key size, prefer the most
            // preferable hash algorithm.
    }

    return maxDigestLength;
}
 
Example #29
Source File: Main.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
private String withWeak(PublicKey key) {
    if (DISABLED_CHECK.permits(SIG_PRIMITIVE_SET, key)) {
        return String.format(rb.getString("key.bit"),
                KeyUtil.getKeySize(key), key.getAlgorithm());
    } else {
        return String.format(rb.getString("key.bit.weak"),
                KeyUtil.getKeySize(key), key.getAlgorithm());
    }
}
 
Example #30
Source File: DHCrypt.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Get the secret data that has been agreed on through Diffie-Hellman
 * key agreement protocol.  Note that in the two party protocol, if
 * the peer keys are already known, no other data needs to be sent in
 * order to agree on a secret.  That is, a secured message may be
 * sent without any mandatory round-trip overheads.
 *
 * <P>It is illegal to call this member function if the private key
 * has not been set (or generated).
 *
 * @param  peerPublicKey the peer's public key.
 * @param  keyIsValidated whether the {@code peerPublicKey} has beed
 *         validated
 * @return the secret, which is an unsigned big-endian integer
 *         the same size as the Diffie-Hellman modulus.
 */
SecretKey getAgreedSecret(BigInteger peerPublicValue,
        boolean keyIsValidated) throws SSLHandshakeException {
    try {
        KeyFactory kf = JsseJce.getKeyFactory("DiffieHellman");
        DHPublicKeySpec spec =
                    new DHPublicKeySpec(peerPublicValue, modulus, base);
        PublicKey publicKey = kf.generatePublic(spec);
        KeyAgreement ka = JsseJce.getKeyAgreement("DiffieHellman");

        // validate the Diffie-Hellman public key
        if (!keyIsValidated &&
                !KeyUtil.isOracleJCEProvider(ka.getProvider().getName())) {
            try {
                KeyUtil.validate(spec);
            } catch (InvalidKeyException ike) {
                // prefer handshake_failure alert to internal_error alert
                throw new SSLHandshakeException(ike.getMessage());
            }
        }

        ka.init(privateKey);
        ka.doPhase(publicKey, true);
        return ka.generateSecret("TlsPremasterSecret");
    } catch (GeneralSecurityException e) {
        throw (SSLHandshakeException) new SSLHandshakeException(
            "Could not generate secret").initCause(e);
    }
}