javax.crypto.KeyAgreement Java Examples

The following examples show how to use javax.crypto.KeyAgreement. 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: DhTest.java    From wycheproof with Apache License 2.0 7 votes vote down vote up
/** Check that key agreement using DH works. */
@SuppressWarnings("InsecureCryptoUsage")
@Test
public void testDh() throws Exception {
  KeyPairGenerator keyGen = KeyPairGenerator.getInstance("DH");
  DHParameterSpec dhparams = ike2048();
  keyGen.initialize(dhparams);
  KeyPair keyPairA = keyGen.generateKeyPair();
  KeyPair keyPairB = keyGen.generateKeyPair();

  KeyAgreement kaA = KeyAgreement.getInstance("DH");
  KeyAgreement kaB = KeyAgreement.getInstance("DH");
  kaA.init(keyPairA.getPrivate());
  kaB.init(keyPairB.getPrivate());
  kaA.doPhase(keyPairB.getPublic(), true);
  kaB.doPhase(keyPairA.getPublic(), true);
  byte[] kAB = kaA.generateSecret();
  byte[] kBA = kaB.generateSecret();
  assertEquals(TestUtil.bytesToHex(kAB), TestUtil.bytesToHex(kBA));
}
 
Example #2
Source File: KAKeyDerivation.java    From Bytecoder with Apache License 2.0 6 votes vote down vote up
/**
 * Handle the TLSv1-1.2 objects, which don't use the HKDF algorithms.
 */
private SecretKey t12DeriveKey(String algorithm,
        AlgorithmParameterSpec params) throws IOException {
    try {
        KeyAgreement ka = KeyAgreement.getInstance(algorithmName);
        ka.init(localPrivateKey);
        ka.doPhase(peerPublicKey, true);
        SecretKey preMasterSecret
                = ka.generateSecret("TlsPremasterSecret");
        SSLMasterKeyDerivation mskd
                = SSLMasterKeyDerivation.valueOf(
                        context.negotiatedProtocol);
        if (mskd == null) {
            // unlikely
            throw new SSLHandshakeException(
                    "No expected master key derivation for protocol: "
                    + context.negotiatedProtocol.name);
        }
        SSLKeyDerivation kd = mskd.createKeyDerivation(
                context, preMasterSecret);
        return kd.deriveKey("MasterSecret", params);
    } catch (GeneralSecurityException gse) {
        throw (SSLHandshakeException) new SSLHandshakeException(
                "Could not generate secret").initCause(gse);
    }
}
 
Example #3
Source File: HttpEce.java    From org.openhab.ui.habot with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Compute the shared secret using the server's key pair (indicated by
 * keyId) and the client's public key. Also compute context.
 *
 * @param keyId
 * @param publicKey
 * @return
 */
private byte[][] deriveDH(String keyId, PublicKey publicKey)
        throws NoSuchProviderException, NoSuchAlgorithmException, InvalidKeyException, IOException {
    PublicKey senderPubKey = keys.get(keyId).getPublic();

    KeyAgreement keyAgreement = KeyAgreement.getInstance("ECDH");
    keyAgreement.init(keys.get(keyId).getPrivate());
    keyAgreement.doPhase(publicKey, true);

    byte[] secret = keyAgreement.generateSecret();
    byte[] context = concat(labels.get(keyId).getBytes(UTF_8), new byte[1], lengthPrefix(publicKey),
            lengthPrefix(senderPubKey));

    return new byte[][] { secret, context };
}
 
Example #4
Source File: TestDH.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
private static void testAlgorithm(KeyAgreement ka1, KeyPair kp1,
        KeyAgreement ka2, KeyPair kp2, String algorithm) throws Exception {
    SecretKey key1;

    ka1.init(kp1.getPrivate());
    ka1.doPhase(kp2.getPublic(), true);
    System.out.println("Derive " + algorithm + " using SunJCE...");
    key1 = ka1.generateSecret(algorithm);

    ka2.init(kp1.getPrivate());
    ka2.doPhase(kp2.getPublic(), true);
    System.out.println("Derive " + algorithm + " using PKCS#11...");
    SecretKey key2 = ka2.generateSecret(algorithm);

    byte[] b1 = key1.getEncoded();
    byte[] b2 = key2.getEncoded();

    if (Arrays.equals(b1, b2) == false) {
        System.out.println(b1.length + " bytes: " + toString(b1));
        System.out.println(b2.length + " bytes: " + toString(b2));
        throw new Exception(algorithm + " secret mismatch");
    }
}
 
Example #5
Source File: EcdhKeyAgreementAlgorithm.java    From Jose4j with Apache License 2.0 6 votes vote down vote up
private byte[] generateEcdhSecret(PrivateKey privateKey, PublicKey publicKey, ProviderContext providerContext) throws JoseException
{
    String keyAgreementProvider = providerContext.getSuppliedKeyProviderContext().getKeyAgreementProvider();
    KeyAgreement keyAgreement = getKeyAgreement(keyAgreementProvider);

    try
    {
        keyAgreement.init(privateKey);
        keyAgreement.doPhase(publicKey, true);
    }
    catch (java.security.InvalidKeyException e)
    {
        throw new InvalidKeyException("Invalid Key for " + getJavaAlgorithm() + " key agreement." ,e);
    }

    return keyAgreement.generateSecret();
}
 
Example #6
Source File: DhTest.java    From wycheproof with Apache License 2.0 6 votes vote down vote up
/** This test tries a key agreement with keys using distinct parameters. */
@SuppressWarnings("InsecureCryptoUsage")
@Test
public void testDHDistinctParameters() throws Exception {
  KeyPairGenerator keyGen = KeyPairGenerator.getInstance("DH");
  keyGen.initialize(ike1536());
  KeyPair keyPairA = keyGen.generateKeyPair();

  keyGen.initialize(ike2048());
  KeyPair keyPairB = keyGen.generateKeyPair();

  KeyAgreement kaA = KeyAgreement.getInstance("DH");
  kaA.init(keyPairA.getPrivate());
  try {
    kaA.doPhase(keyPairB.getPublic(), true);
    byte[] kAB = kaA.generateSecret();
    fail("Generated secrets with mixed keys " + TestUtil.bytesToHex(kAB) + ", ");
  } catch (java.security.GeneralSecurityException ex) {
    // This is expected.
  }
}
 
Example #7
Source File: ECDH.java    From thunder with GNU Affero General Public License v3.0 6 votes vote down vote up
public static ECDHKeySet getSharedSecret (ECKey keyServer, ECKey keyClient) {
    try {

        ECPrivateKeySpec specPrivate = new ECPrivateKeySpec(keyServer.getPrivKey(), ecParameters);
        ECPublicKeySpec specPublic = new ECPublicKeySpec(new ECPoint(keyClient.getPubKeyPoint().getXCoord().toBigInteger(), keyClient.getPubKeyPoint()
                .getYCoord().toBigInteger()), ecParameters);

        ECPrivateKey privateKey = (ECPrivateKey) kf.generatePrivate(specPrivate);
        ECPublicKey publicKey = (ECPublicKey) kf.generatePublic(specPublic);

        JCEECPrivateKey ecPrivKey = new JCEECPrivateKey(privateKey);
        JCEECPublicKey ecPubKey = new JCEECPublicKey(publicKey);

        KeyAgreement aKeyAgree = KeyAgreement.getInstance("ECDH");
        aKeyAgree.init(ecPrivKey);
        aKeyAgree.doPhase(ecPubKey, true);

        return new ECDHKeySet(aKeyAgree.generateSecret(), keyServer.getPubKey(), keyClient.getPubKey());
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
 
Example #8
Source File: TestECDH2.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
private static void testKeyAgreement(KeyPair kpA, KeyPair kpB, Provider p)
    throws Exception {
    KeyAgreement ka1 = KeyAgreement.getInstance("ECDH", p);
    ka1.init(kpA.getPrivate());
    ka1.doPhase(kpB.getPublic(), true);
    byte[] s1 = ka1.generateSecret();

    KeyAgreement ka2 = KeyAgreement.getInstance("ECDH", p);
    ka2.init(kpB.getPrivate());
    ka2.doPhase(kpA.getPublic(), true);
    byte[] s2 = ka2.generateSecret();
    if (Arrays.equals(s1, s2) == false) {
        System.out.println("expected: " + toString(s1));
        System.out.println("actual:   " + toString(s2));
        throw new Exception("Generated secrets do not match");
    }
}
 
Example #9
Source File: DHCrypt.java    From openjdk-8 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 IOException {
    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 new RuntimeException("Could not generate secret", e);
    }
}
 
Example #10
Source File: ToolDH.java    From protools with Apache License 2.0 5 votes vote down vote up
/**
 * 构建密钥
 *
 * @param publicKey
 *         公钥
 * @param privateKey
 *         私钥
 *
 * @return byte[] 本地密钥
 *
 * @throws Exception
 */
public static byte[] getSecretKey(byte[] publicKey, byte[] privateKey) throws InvalidKeySpecException, NoSuchAlgorithmException, InvalidKeyException {

    // 实例化密钥工厂
    KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);

    // 初始化公钥
    // 密钥材料转换
    X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(publicKey);

    // 产生公钥
    PublicKey pubKey = keyFactory.generatePublic(x509KeySpec);

    // 初始化私钥
    // 密钥材料转换
    PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(privateKey);

    // 产生私钥
    PrivateKey priKey = keyFactory.generatePrivate(pkcs8KeySpec);

    // 实例化
    KeyAgreement keyAgree = KeyAgreement.getInstance(keyFactory.getAlgorithm());

    // 初始化
    keyAgree.init(priKey);

    keyAgree.doPhase(pubKey, true);

    // 生成本地密钥
    SecretKey secretKey = keyAgree.generateSecret(SECRET_KEY_ALGORITHM);

    return secretKey.getEncoded();
}
 
Example #11
Source File: HandShake.java    From gemfirexd-oss with Apache License 2.0 5 votes vote down vote up
static public byte[] decryptBytes(byte[] data, String dhSKAlgo, PublicKey publicKey)
throws Exception{
  try {
    KeyAgreement ka = KeyAgreement.getInstance("DH");
    ka.init(dhPrivateKey);
    ka.doPhase(publicKey, true);

    Cipher decrypt;
    
    int keysize = getKeySize(dhSKAlgo);
    int blocksize = getBlockSize(dhSKAlgo);

    if (keysize == -1 || blocksize == -1) {
      SecretKey sKey = ka.generateSecret(dhSKAlgo);
      decrypt = Cipher.getInstance(dhSKAlgo);
      decrypt.init(Cipher.DECRYPT_MODE, sKey);
    }
    else {
      String algoStr = getDhAlgoStr(dhSKAlgo);
      
      byte[] sKeyBytes = ka.generateSecret();
      SecretKeySpec sks = new SecretKeySpec(sKeyBytes, 0, keysize, algoStr);
      IvParameterSpec ivps = new IvParameterSpec(sKeyBytes, keysize, blocksize);
      
      decrypt = Cipher.getInstance(algoStr + "/CBC/PKCS5Padding");
      decrypt.init(Cipher.DECRYPT_MODE, sks, ivps);
    }
    
    byte[] decrptBytes = decrypt.doFinal(data);
    return decrptBytes;
  }catch(Exception ex) {
    throw ex;
  }    
}
 
Example #12
Source File: HandShake.java    From gemfirexd-oss with Apache License 2.0 5 votes vote down vote up
static public byte[] encryptBytes(byte[] data,String dhSKAlgo, PublicKey publicKey)
throws Exception{
  
  try {
    KeyAgreement ka = KeyAgreement.getInstance("DH");
    ka.init(dhPrivateKey);
    ka.doPhase(publicKey, true);
    
    Cipher encrypt;
    
    int keysize = getKeySize(dhSKAlgo);
    int blocksize = getBlockSize(dhSKAlgo);

    if (keysize == -1 || blocksize == -1) {
      SecretKey sKey = ka.generateSecret(dhSKAlgo);
      encrypt = Cipher.getInstance(dhSKAlgo);
      encrypt.init(Cipher.ENCRYPT_MODE, sKey);
    }
    else {
      String dhAlgoStr = getDhAlgoStr(dhSKAlgo);
      
      byte[] sKeyBytes = ka.generateSecret();
      SecretKeySpec sks = new SecretKeySpec(sKeyBytes, 0, keysize, dhAlgoStr);
      IvParameterSpec ivps = new IvParameterSpec(sKeyBytes, keysize, blocksize);
      
      encrypt = Cipher.getInstance(dhAlgoStr + "/CBC/PKCS5Padding");
      encrypt.init(Cipher.ENCRYPT_MODE, sks, ivps);
    }

      
      byte[] encBytes = encrypt.doFinal(data);
      return encBytes;
  } catch (Exception ex) {
    throw ex;
  }
}
 
Example #13
Source File: DHCrypt.java    From openjdk-8-source 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 IOException {
    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 new RuntimeException("Could not generate secret", e);
    }
}
 
Example #14
Source File: ECDHCrypt.java    From hottub with GNU General Public License v2.0 5 votes vote down vote up
SecretKey getAgreedSecret(
        PublicKey peerPublicKey) throws SSLHandshakeException {

    try {
        KeyAgreement ka = JsseJce.getKeyAgreement("ECDH");
        ka.init(privateKey);
        ka.doPhase(peerPublicKey, true);
        return ka.generateSecret("TlsPremasterSecret");
    } catch (GeneralSecurityException e) {
        throw (SSLHandshakeException) new SSLHandshakeException(
            "Could not generate secret").initCause(e);
    }
}
 
Example #15
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 #16
Source File: ECDHCrypt.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
SecretKey getAgreedSecret(
        PublicKey peerPublicKey) throws SSLHandshakeException {

    try {
        KeyAgreement ka = JsseJce.getKeyAgreement("ECDH");
        ka.init(privateKey);
        ka.doPhase(peerPublicKey, true);
        return ka.generateSecret("TlsPremasterSecret");
    } catch (GeneralSecurityException e) {
        throw (SSLHandshakeException) new SSLHandshakeException(
            "Could not generate secret").initCause(e);
    }
}
 
Example #17
Source File: ECKeyAgreement.java    From nuls with MIT License 5 votes vote down vote up
public static KeyAgreement getInstance(final Provider provider) {
    try {
        return KeyAgreement.getInstance(ALGORITHM, provider);
    } catch (NoSuchAlgorithmException ex) {
        throw new AssertionError(algorithmAssertionMsg, ex);
    }
}
 
Example #18
Source File: ECDHKeyExchange.java    From Bytecoder with Apache License 2.0 5 votes vote down vote up
SecretKey getAgreedSecret(
        PublicKey peerPublicKey) throws SSLHandshakeException {

    try {
        KeyAgreement ka = KeyAgreement.getInstance("ECDH");
        ka.init(privateKey);
        ka.doPhase(peerPublicKey, true);
        return ka.generateSecret("TlsPremasterSecret");
    } catch (GeneralSecurityException e) {
        throw (SSLHandshakeException) new SSLHandshakeException(
            "Could not generate secret").initCause(e);
    }
}
 
Example #19
Source File: KeyAgreementIdent.java    From ECTester with MIT License 5 votes vote down vote up
public KeyAgreement getInstance(Provider provider) throws NoSuchAlgorithmException {
    KeyAgreement instance = getInstance((algorithm, provider1) -> {
        try {
            return KeyAgreement.getInstance(algorithm, provider1);
        } catch (NoSuchAlgorithmException e) {
            return null;
        }
    }, provider);
    instance.getProvider();
    return instance;
}
 
Example #20
Source File: ValueLinkApi.java    From scipio-erp with Apache License 2.0 5 votes vote down vote up
/**
 * Generate a key exchange key for use in encrypting the mwk
 * @param privateKey The private key for the merchant
 * @return byte array containing the kek
 * @throws NoSuchAlgorithmException
 * @throws InvalidKeySpecException
 * @throws InvalidKeyException
 */
public byte[] generateKek(PrivateKey privateKey) throws NoSuchAlgorithmException, InvalidKeySpecException, InvalidKeyException {
    // get the ValueLink public key
    PublicKey vlPublic = this.getValueLinkPublicKey();

    // generate shared secret key
    KeyAgreement ka = KeyAgreement.getInstance("DH");
    ka.init(privateKey);
    ka.doPhase(vlPublic, true);
    byte[] secretKey = ka.generateSecret();

    if (debug) {
        Debug.logInfo("Secret Key : " + StringUtil.toHexString(secretKey) + " / " + secretKey.length,  module);
    }

    // generate 3DES from secret key using VL algorithm (KEK)
    MessageDigest md = MessageDigest.getInstance("SHA1");
    byte[] digest = md.digest(secretKey);
    byte[] des2 = getByteRange(digest, 0, 16);
    byte[] first8 = getByteRange(des2, 0, 8);
    byte[] kek = copyBytes(des2, first8, 0);

    if (debug) {
        Debug.logInfo("Generated KEK : " + StringUtil.toHexString(kek) + " / " + kek.length, module);
    }

    return kek;
}
 
Example #21
Source File: DHCrypt.java    From openjdk-jdk8u-backup 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 #22
Source File: Crypto.java    From webauthndemo with Apache License 2.0 5 votes vote down vote up
public static byte[] getS(PrivateKey privateKey, byte[] publicKey) {
  try {
    KeyAgreement agreement = KeyAgreement.getInstance("ECDH");
    agreement.init(privateKey);
    agreement.doPhase(decodePublicKey(publicKey), true);

    return agreement.generateSecret();
  } catch (NoSuchAlgorithmException | InvalidKeyException | IllegalStateException
      | WebAuthnException e) {
    throw new RuntimeException(e);
  }
}
 
Example #23
Source File: KAKeyDerivation.java    From Bytecoder with Apache License 2.0 5 votes vote down vote up
/**
 * Handle the TLSv1.3 objects, which use the HKDF algorithms.
 */
private SecretKey t13DeriveKey(String algorithm,
        AlgorithmParameterSpec params) throws IOException {
    try {
        KeyAgreement ka = KeyAgreement.getInstance(algorithmName);
        ka.init(localPrivateKey);
        ka.doPhase(peerPublicKey, true);
        SecretKey sharedSecret
                = ka.generateSecret("TlsPremasterSecret");

        CipherSuite.HashAlg hashAlg = context.negotiatedCipherSuite.hashAlg;
        SSLKeyDerivation kd = context.handshakeKeyDerivation;
        HKDF hkdf = new HKDF(hashAlg.name);
        if (kd == null) {   // No PSK is in use.
            // If PSK is not in use Early Secret will still be
            // HKDF-Extract(0, 0).
            byte[] zeros = new byte[hashAlg.hashLength];
            SecretKeySpec ikm
                    = new SecretKeySpec(zeros, "TlsPreSharedSecret");
            SecretKey earlySecret
                    = hkdf.extract(zeros, ikm, "TlsEarlySecret");
            kd = new SSLSecretDerivation(context, earlySecret);
        }

        // derive salt secret
        SecretKey saltSecret = kd.deriveKey("TlsSaltSecret", null);

        // derive handshake secret
        return hkdf.extract(saltSecret, sharedSecret, algorithm);
    } catch (GeneralSecurityException gse) {
        throw (SSLHandshakeException) new SSLHandshakeException(
                "Could not generate secret").initCause(gse);
    }
}
 
Example #24
Source File: ECDHCrypt.java    From jdk8u_jdk with GNU General Public License v2.0 5 votes vote down vote up
SecretKey getAgreedSecret(
        PublicKey peerPublicKey) throws SSLHandshakeException {

    try {
        KeyAgreement ka = JsseJce.getKeyAgreement("ECDH");
        ka.init(privateKey);
        ka.doPhase(peerPublicKey, true);
        return ka.generateSecret("TlsPremasterSecret");
    } catch (GeneralSecurityException e) {
        throw (SSLHandshakeException) new SSLHandshakeException(
            "Could not generate secret").initCause(e);
    }
}
 
Example #25
Source File: ECKeyAgreement.java    From javasdk with GNU Lesser General Public License v3.0 5 votes vote down vote up
public static KeyAgreement getInstance() {
    try {
        return KeyAgreement.getInstance(ALGORITHM);
    } catch (NoSuchAlgorithmException ex) {
        throw new AssertionError(algorithmAssertionMsg);
    }
}
 
Example #26
Source File: ECKeyAgreement.java    From nuls with MIT License 5 votes vote down vote up
public static KeyAgreement getInstance(final String provider) throws NoSuchProviderException {
    try {
        return KeyAgreement.getInstance(ALGORITHM, provider);
    } catch (NoSuchAlgorithmException ex) {
        throw new AssertionError(algorithmAssertionMsg, ex);
    }
}
 
Example #27
Source File: EncryptionUtils.java    From Protocol with Apache License 2.0 5 votes vote down vote up
private static byte[] getEcdhSecret(PrivateKey localPrivateKey, PublicKey remotePublicKey) throws InvalidKeyException {
    KeyAgreement agreement;
    try {
        agreement = KeyAgreement.getInstance("ECDH");
    } catch (NoSuchAlgorithmException e) {
        throw new AssertionError(e);
    }

    agreement.init(localPrivateKey);
    agreement.doPhase(remotePublicKey, true);
    return agreement.generateSecret();
}
 
Example #28
Source File: ECDHCrypt.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
SecretKey getAgreedSecret(
        PublicKey peerPublicKey) throws SSLHandshakeException {

    try {
        KeyAgreement ka = JsseJce.getKeyAgreement("ECDH");
        ka.init(privateKey);
        ka.doPhase(peerPublicKey, true);
        return ka.generateSecret("TlsPremasterSecret");
    } catch (GeneralSecurityException e) {
        throw (SSLHandshakeException) new SSLHandshakeException(
            "Could not generate secret").initCause(e);
    }
}
 
Example #29
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);
    }
}
 
Example #30
Source File: ECKeyAgreement.java    From tron-wallet-android with Apache License 2.0 5 votes vote down vote up
public static KeyAgreement getInstance(final Provider provider) {
    try {
        return KeyAgreement.getInstance(ALGORITHM, provider);
    } catch (NoSuchAlgorithmException ex) {
        throw new AssertionError(algorithmAssertionMsg, ex);
    }
}