Java Code Examples for javax.crypto.spec.DHParameterSpec#getG()

The following examples show how to use javax.crypto.spec.DHParameterSpec#getG() . 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: KeyPairGeneratorSpi.java    From RipplePower with Apache License 2.0 6 votes vote down vote up
public void initialize(
    AlgorithmParameterSpec params,
    SecureRandom random)
    throws InvalidAlgorithmParameterException
{
    if (!(params instanceof DHParameterSpec))
    {
        throw new InvalidAlgorithmParameterException("parameter object not a DHParameterSpec");
    }
    DHParameterSpec dhParams = (DHParameterSpec)params;

    param = new DHKeyGenerationParameters(random, new DHParameters(dhParams.getP(), dhParams.getG(), null, dhParams.getL()));

    engine.init(param);
    initialised = true;
}
 
Example 2
Source File: KeyPairGeneratorSpi.java    From ripple-lib-java with ISC License 6 votes vote down vote up
public void initialize(
    AlgorithmParameterSpec params,
    SecureRandom random)
    throws InvalidAlgorithmParameterException
{
    if (!(params instanceof ElGamalParameterSpec) && !(params instanceof DHParameterSpec))
    {
        throw new InvalidAlgorithmParameterException("parameter object not a DHParameterSpec or an ElGamalParameterSpec");
    }

    if (params instanceof ElGamalParameterSpec)
    {
        ElGamalParameterSpec elParams = (ElGamalParameterSpec)params;

        param = new ElGamalKeyGenerationParameters(random, new ElGamalParameters(elParams.getP(), elParams.getG()));
    }
    else
    {
        DHParameterSpec dhParams = (DHParameterSpec)params;

        param = new ElGamalKeyGenerationParameters(random, new ElGamalParameters(dhParams.getP(), dhParams.getG(), dhParams.getL()));
    }

    engine.init(param);
    initialised = true;
}
 
Example 3
Source File: AlgorithmParametersSpi.java    From RipplePower with Apache License 2.0 6 votes vote down vote up
protected void engineInit(
    AlgorithmParameterSpec paramSpec)
    throws InvalidParameterSpecException
{
    if (!(paramSpec instanceof ElGamalParameterSpec) && !(paramSpec instanceof DHParameterSpec))
    {
        throw new InvalidParameterSpecException("DHParameterSpec required to initialise a ElGamal algorithm parameters object");
    }

    if (paramSpec instanceof ElGamalParameterSpec)
    {
        this.currentSpec = (ElGamalParameterSpec)paramSpec;
    }
    else
    {
        DHParameterSpec s = (DHParameterSpec)paramSpec;

        this.currentSpec = new ElGamalParameterSpec(s.getP(), s.getG());
    }
}
 
Example 4
Source File: ValueLinkApi.java    From scipio-erp with Apache License 2.0 6 votes vote down vote up
/**
 * Get a public key object for the ValueLink supplied public key
 * @return PublicKey object of ValueLinks's public key
 * @throws NoSuchAlgorithmException
 * @throws InvalidKeySpecException
 */
public PublicKey getValueLinkPublicKey() throws NoSuchAlgorithmException, InvalidKeySpecException {
    // read the valuelink public key
    String publicValue = (String) props.get("payment.valuelink.publicValue");
    byte[] publicKeyBytes = StringUtil.fromHexString(publicValue);

    // initialize the parameter spec
    DHParameterSpec dhParamSpec = this.getDHParameterSpec();

    // load the valuelink public key
    KeyFactory keyFactory = KeyFactory.getInstance("DH");
    BigInteger publicKeyInt = new BigInteger(publicKeyBytes);
    DHPublicKeySpec dhPublicSpec = new DHPublicKeySpec(publicKeyInt, dhParamSpec.getP(), dhParamSpec.getG());
    PublicKey vlPublic = keyFactory.generatePublic(dhPublicSpec);

    return vlPublic;
}
 
Example 5
Source File: KeyAgreementSpi.java    From ripple-lib-java with ISC License 5 votes vote down vote up
protected void engineInit(
    Key                     key,
    AlgorithmParameterSpec  params,
    SecureRandom            random) 
    throws InvalidKeyException, InvalidAlgorithmParameterException
{
    if (!(key instanceof DHPrivateKey))
    {
        throw new InvalidKeyException("DHKeyAgreement requires DHPrivateKey for initialisation");
    }
    DHPrivateKey    privKey = (DHPrivateKey)key;

    if (params != null)
    {
        if (!(params instanceof DHParameterSpec))
        {
            throw new InvalidAlgorithmParameterException("DHKeyAgreement only accepts DHParameterSpec");
        }
        DHParameterSpec p = (DHParameterSpec)params;

        this.p = p.getP();
        this.g = p.getG();
    }
    else
    {
        this.p = privKey.getParams().getP();
        this.g = privKey.getParams().getG();
    }

    this.x = this.result = privKey.getX();
}
 
Example 6
Source File: KeyUtil.java    From j2objc with Apache License 2.0 5 votes vote down vote up
/**
 * Returns whether the Diffie-Hellman public key is valid or not.
 *
 * Per RFC 2631 and NIST SP800-56A, the following algorithm is used to
 * validate Diffie-Hellman public keys:
 * 1. Verify that y lies within the interval [2,p-1]. If it does not,
 *    the key is invalid.
 * 2. Compute y^q mod p. If the result == 1, the key is valid.
 *    Otherwise the key is invalid.
 */
private static void validateDHPublicKey(DHPublicKey publicKey)
        throws InvalidKeyException {
    DHParameterSpec paramSpec = publicKey.getParams();

    BigInteger p = paramSpec.getP();
    BigInteger g = paramSpec.getG();
    BigInteger y = publicKey.getY();

    validateDHPublicKey(p, g, y);
}
 
Example 7
Source File: DhTest.java    From wycheproof with Apache License 2.0 5 votes vote down vote up
/**
 * Tests whether a provider accepts invalid public keys that result in predictable shared secrets.
 * This test is based on RFC 2785, Section 4 and NIST SP 800-56A, If an attacker can modify both
 * public keys in an ephemeral-ephemeral key agreement scheme then it may be possible to coerce
 * both parties into computing the same predictable shared key.
 *
 * <p>Note: the test is quite whimsical. If the prime p is not a safe prime then the provider
 * itself cannot prevent all small-subgroup attacks because of the missing parameter q in the
 * Diffie-Hellman parameters. Implementations must add additional countermeasures such as the ones
 * proposed in RFC 2785.
 *
 * <p>CVE-2016-1000346: BouncyCastle before v.1.56 did not validate the other parties public key.
 */
@SuppressWarnings("InsecureCryptoUsage")
@Test
public void testSubgroupConfinement() throws Exception {
  KeyPairGenerator keyGen = KeyPairGenerator.getInstance("DH");
  DHParameterSpec params = ike2048();
  BigInteger p = params.getP();
  BigInteger g = params.getG();
  keyGen.initialize(params);
  PrivateKey priv = keyGen.generateKeyPair().getPrivate();
  KeyAgreement ka = KeyAgreement.getInstance("DH");
  BigInteger[] weakPublicKeys = {
    BigInteger.ZERO,
    BigInteger.ONE,
    p.subtract(BigInteger.ONE),
    p,
    p.add(BigInteger.ONE),
    BigInteger.ONE.negate()
  };
  for (BigInteger weakKey : weakPublicKeys) {
    ka.init(priv);
    try {
      KeyFactory kf = KeyFactory.getInstance("DH");
      DHPublicKeySpec weakSpec = new DHPublicKeySpec(weakKey, p, g);
      PublicKey pub = kf.generatePublic(weakSpec);
      ka.doPhase(pub, true);
      byte[] kAB = ka.generateSecret();
      fail(
          "Generated secrets with weak public key:"
              + weakKey.toString()
              + " secret:"
              + TestUtil.bytesToHex(kAB));
    } catch (GeneralSecurityException ex) {
      // this is expected
    }
  }
}
 
Example 8
Source File: KeyUtil.java    From openjdk-8 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Returns whether the Diffie-Hellman public key is valid or not.
 *
 * Per RFC 2631 and NIST SP800-56A, the following algorithm is used to
 * validate Diffie-Hellman public keys:
 * 1. Verify that y lies within the interval [2,p-1]. If it does not,
 *    the key is invalid.
 * 2. Compute y^q mod p. If the result == 1, the key is valid.
 *    Otherwise the key is invalid.
 */
private static void validateDHPublicKey(DHPublicKey publicKey)
        throws InvalidKeyException {
    DHParameterSpec paramSpec = publicKey.getParams();

    BigInteger p = paramSpec.getP();
    BigInteger g = paramSpec.getG();
    BigInteger y = publicKey.getY();

    validateDHPublicKey(p, g, y);
}
 
Example 9
Source File: KeyUtil.java    From openjdk-8-source with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Returns whether the Diffie-Hellman public key is valid or not.
 *
 * Per RFC 2631 and NIST SP800-56A, the following algorithm is used to
 * validate Diffie-Hellman public keys:
 * 1. Verify that y lies within the interval [2,p-1]. If it does not,
 *    the key is invalid.
 * 2. Compute y^q mod p. If the result == 1, the key is valid.
 *    Otherwise the key is invalid.
 */
private static void validateDHPublicKey(DHPublicKey publicKey)
        throws InvalidKeyException {
    DHParameterSpec paramSpec = publicKey.getParams();

    BigInteger p = paramSpec.getP();
    BigInteger g = paramSpec.getG();
    BigInteger y = publicKey.getY();

    validateDHPublicKey(p, g, y);
}
 
Example 10
Source File: KeyUtil.java    From hottub with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Returns whether the Diffie-Hellman public key is valid or not.
 *
 * Per RFC 2631 and NIST SP800-56A, the following algorithm is used to
 * validate Diffie-Hellman public keys:
 * 1. Verify that y lies within the interval [2,p-1]. If it does not,
 *    the key is invalid.
 * 2. Compute y^q mod p. If the result == 1, the key is valid.
 *    Otherwise the key is invalid.
 */
private static void validateDHPublicKey(DHPublicKey publicKey)
        throws InvalidKeyException {
    DHParameterSpec paramSpec = publicKey.getParams();

    BigInteger p = paramSpec.getP();
    BigInteger g = paramSpec.getG();
    BigInteger y = publicKey.getY();

    validateDHPublicKey(p, g, y);
}
 
Example 11
Source File: ValueLinkApi.java    From scipio-erp with Apache License 2.0 5 votes vote down vote up
/**
 * Get merchant Private Key
 * @return PrivateKey object for the merchant
 */
public PrivateKey getPrivateKey() throws InvalidKeySpecException, NoSuchAlgorithmException {
    byte[] privateKeyBytes = this.getPrivateKeyBytes();

    // initialize the parameter spec
    DHParameterSpec dhParamSpec = this.getDHParameterSpec();

    // load the private key
    KeyFactory keyFactory = KeyFactory.getInstance("DH");
    BigInteger privateKeyInt = new BigInteger(privateKeyBytes);
    DHPrivateKeySpec dhPrivateSpec = new DHPrivateKeySpec(privateKeyInt, dhParamSpec.getP(), dhParamSpec.getG());
    PrivateKey privateKey = keyFactory.generatePrivate(dhPrivateSpec);

    return privateKey;
}
 
Example 12
Source File: KeyUtil.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Returns whether the Diffie-Hellman public key is valid or not.
 *
 * Per RFC 2631 and NIST SP800-56A, the following algorithm is used to
 * validate Diffie-Hellman public keys:
 * 1. Verify that y lies within the interval [2,p-1]. If it does not,
 *    the key is invalid.
 * 2. Compute y^q mod p. If the result == 1, the key is valid.
 *    Otherwise the key is invalid.
 */
private static void validateDHPublicKey(DHPublicKey publicKey)
        throws InvalidKeyException {
    DHParameterSpec paramSpec = publicKey.getParams();

    BigInteger p = paramSpec.getP();
    BigInteger g = paramSpec.getG();
    BigInteger y = publicKey.getY();

    validateDHPublicKey(p, g, y);
}
 
Example 13
Source File: KeyUtil.java    From jdk8u-dev-jdk with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Returns whether the Diffie-Hellman public key is valid or not.
 *
 * Per RFC 2631 and NIST SP800-56A, the following algorithm is used to
 * validate Diffie-Hellman public keys:
 * 1. Verify that y lies within the interval [2,p-1]. If it does not,
 *    the key is invalid.
 * 2. Compute y^q mod p. If the result == 1, the key is valid.
 *    Otherwise the key is invalid.
 */
private static void validateDHPublicKey(DHPublicKey publicKey)
        throws InvalidKeyException {
    DHParameterSpec paramSpec = publicKey.getParams();

    BigInteger p = paramSpec.getP();
    BigInteger g = paramSpec.getG();
    BigInteger y = publicKey.getY();

    validateDHPublicKey(p, g, y);
}
 
Example 14
Source File: DHKeyExchange.java    From Bytecoder with Apache License 2.0 5 votes vote down vote up
private static DHPublicKeySpec getDHPublicKeySpec(PublicKey key) {
    if (key instanceof DHPublicKey) {
        DHPublicKey dhKey = (DHPublicKey)key;
        DHParameterSpec params = dhKey.getParams();
        return new DHPublicKeySpec(dhKey.getY(),
                                params.getP(), params.getG());
    }
    try {
        KeyFactory factory = KeyFactory.getInstance("DiffieHellman");
        return factory.getKeySpec(key, DHPublicKeySpec.class);
    } catch (NoSuchAlgorithmException | InvalidKeySpecException e) {
        // unlikely
        throw new RuntimeException("Unable to get DHPublicKeySpec", e);
    }
}
 
Example 15
Source File: KeyPairGeneratorSpi.java    From ripple-lib-java with ISC License 5 votes vote down vote up
public KeyPair generateKeyPair()
{
    if (!initialised)
    {
        DHParameterSpec dhParams = BouncyCastleProvider.CONFIGURATION.getDHDefaultParameters(strength);

        if (dhParams != null)
        {
            param = new ElGamalKeyGenerationParameters(random, new ElGamalParameters(dhParams.getP(), dhParams.getG(), dhParams.getL()));
        }
        else
        {
            ElGamalParametersGenerator pGen = new ElGamalParametersGenerator();

            pGen.init(strength, certainty, random);
            param = new ElGamalKeyGenerationParameters(random, pGen.generateParameters());
        }

        engine.init(param);
        initialised = true;
    }

    AsymmetricCipherKeyPair pair = engine.generateKeyPair();
    ElGamalPublicKeyParameters pub = (ElGamalPublicKeyParameters)pair.getPublic();
    ElGamalPrivateKeyParameters priv = (ElGamalPrivateKeyParameters)pair.getPrivate();

    return new KeyPair(new BCElGamalPublicKey(pub),
        new BCElGamalPrivateKey(priv));
}
 
Example 16
Source File: KeyUtil.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Returns whether the Diffie-Hellman public key is valid or not.
 *
 * Per RFC 2631 and NIST SP800-56A, the following algorithm is used to
 * validate Diffie-Hellman public keys:
 * 1. Verify that y lies within the interval [2,p-1]. If it does not,
 *    the key is invalid.
 * 2. Compute y^q mod p. If the result == 1, the key is valid.
 *    Otherwise the key is invalid.
 */
private static void validateDHPublicKey(DHPublicKey publicKey)
        throws InvalidKeyException {
    DHParameterSpec paramSpec = publicKey.getParams();

    BigInteger p = paramSpec.getP();
    BigInteger g = paramSpec.getG();
    BigInteger y = publicKey.getY();

    validateDHPublicKey(p, g, y);
}
 
Example 17
Source File: DHKeyExchange.java    From openjsse with GNU General Public License v2.0 5 votes vote down vote up
private static DHPublicKeySpec getDHPublicKeySpec(PublicKey key) {
    if (key instanceof DHPublicKey) {
        DHPublicKey dhKey = (DHPublicKey)key;
        DHParameterSpec params = dhKey.getParams();
        return new DHPublicKeySpec(dhKey.getY(),
                                params.getP(), params.getG());
    }
    try {
        KeyFactory factory = JsseJce.getKeyFactory("DiffieHellman");
        return factory.getKeySpec(key, DHPublicKeySpec.class);
    } catch (NoSuchAlgorithmException | InvalidKeySpecException e) {
        // unlikely
        throw new RuntimeException("Unable to get DHPublicKeySpec", e);
    }
}
 
Example 18
Source File: KeyPairGeneratorSpi.java    From RipplePower with Apache License 2.0 5 votes vote down vote up
public KeyPair generateKeyPair()
{
    if (!initialised)
    {
        DHParameterSpec dhParams = BouncyCastleProvider.CONFIGURATION.getDHDefaultParameters(strength);

        if (dhParams != null)
        {
            param = new ElGamalKeyGenerationParameters(random, new ElGamalParameters(dhParams.getP(), dhParams.getG(), dhParams.getL()));
        }
        else
        {
            ElGamalParametersGenerator pGen = new ElGamalParametersGenerator();

            pGen.init(strength, certainty, random);
            param = new ElGamalKeyGenerationParameters(random, pGen.generateParameters());
        }

        engine.init(param);
        initialised = true;
    }

    AsymmetricCipherKeyPair pair = engine.generateKeyPair();
    ElGamalPublicKeyParameters pub = (ElGamalPublicKeyParameters)pair.getPublic();
    ElGamalPrivateKeyParameters priv = (ElGamalPrivateKeyParameters)pair.getPrivate();

    return new KeyPair(new BCElGamalPublicKey(pub),
        new BCElGamalPrivateKey(priv));
}
 
Example 19
Source File: DHClientKeyExchange.java    From openjsse with GNU General Public License v2.0 4 votes vote down vote up
@Override
public void consume(ConnectionContext context,
        ByteBuffer message) throws IOException {
    // The consuming happens in server side only.
    ServerHandshakeContext shc = (ServerHandshakeContext)context;

    DHEPossession dhePossession = null;
    for (SSLPossession possession : shc.handshakePossessions) {
        if (possession instanceof DHEPossession) {
            dhePossession = (DHEPossession)possession;
            break;
        }
    }

    if (dhePossession == null) {
        // unlikely
        throw shc.conContext.fatal(Alert.HANDSHAKE_FAILURE,
            "No expected DHE possessions for client key exchange");
    }

    SSLKeyExchange ke = SSLKeyExchange.valueOf(
            shc.negotiatedCipherSuite.keyExchange,
            shc.negotiatedProtocol);
    if (ke == null) {
        // unlikely
        throw shc.conContext.fatal(Alert.INTERNAL_ERROR,
                "Not supported key exchange type");
    }

    DHClientKeyExchangeMessage ckem =
            new DHClientKeyExchangeMessage(shc, message);
    if (SSLLogger.isOn && SSLLogger.isOn("ssl,handshake")) {
        SSLLogger.fine(
            "Consuming DH ClientKeyExchange handshake message", ckem);
    }

    // create the credentials
    try {
        DHParameterSpec params = dhePossession.publicKey.getParams();
        DHPublicKeySpec spec = new DHPublicKeySpec(
                new BigInteger(1, ckem.y),
                params.getP(), params.getG());
        KeyFactory kf = JsseJce.getKeyFactory("DiffieHellman");
        DHPublicKey peerPublicKey =
                (DHPublicKey)kf.generatePublic(spec);

        // check constraints of peer DHPublicKey
        if (!shc.algorithmConstraints.permits(
                EnumSet.of(CryptoPrimitive.KEY_AGREEMENT),
                peerPublicKey)) {
            throw new SSLHandshakeException(
                "DHPublicKey does not comply to algorithm constraints");
        }

        NamedGroup namedGroup = NamedGroup.valueOf(params);
        shc.handshakeCredentials.add(
                new DHECredentials(peerPublicKey, namedGroup));
    } catch (GeneralSecurityException | java.io.IOException e) {
        throw (SSLHandshakeException)(new SSLHandshakeException(
                "Could not generate DHPublicKey").initCause(e));
    }

    // update the states
    SSLKeyDerivation masterKD = ke.createKeyDerivation(shc);
    SecretKey masterSecret =
            masterKD.deriveKey("MasterSecret", null);
    shc.handshakeSession.setMasterSecret(masterSecret);

    SSLTrafficKeyDerivation kd =
            SSLTrafficKeyDerivation.valueOf(shc.negotiatedProtocol);
    if (kd == null) {
        // unlikely
        throw shc.conContext.fatal(Alert.INTERNAL_ERROR,
            "Not supported key derivation: " + shc.negotiatedProtocol);
    } else {
        shc.handshakeKeyDerivation =
            kd.createKeyDerivation(shc, masterSecret);
    }
}
 
Example 20
Source File: KeyPairGeneratorSpi.java    From RipplePower with Apache License 2.0 4 votes vote down vote up
public KeyPair generateKeyPair()
{
    if (!initialised)
    {
        Integer paramStrength = Integers.valueOf(strength);

        if (params.containsKey(paramStrength))
        {
            param = (DHKeyGenerationParameters)params.get(paramStrength);
        }
        else
        {
            DHParameterSpec dhParams = BouncyCastleProvider.CONFIGURATION.getDHDefaultParameters(strength);

            if (dhParams != null)
            {
                param = new DHKeyGenerationParameters(random, new DHParameters(dhParams.getP(), dhParams.getG(), null, dhParams.getL()));
            }
            else
            {
                synchronized (lock)
                {
                    // we do the check again in case we were blocked by a generator for
                    // our key size.
                    if (params.containsKey(paramStrength))
                    {
                        param = (DHKeyGenerationParameters)params.get(paramStrength);
                    }
                    else
                    {

                        DHParametersGenerator pGen = new DHParametersGenerator();

                        pGen.init(strength, certainty, random);

                        param = new DHKeyGenerationParameters(random, pGen.generateParameters());

                        params.put(paramStrength, param);
                    }
                }
            }
        }

        engine.init(param);

        initialised = true;
    }

    AsymmetricCipherKeyPair pair = engine.generateKeyPair();
    DHPublicKeyParameters pub = (DHPublicKeyParameters)pair.getPublic();
    DHPrivateKeyParameters priv = (DHPrivateKeyParameters)pair.getPrivate();

    return new KeyPair(new BCDHPublicKey(pub),
        new BCDHPrivateKey(priv));
}