Java Code Examples for javax.crypto.KeyAgreement#getInstance()

The following examples show how to use javax.crypto.KeyAgreement#getInstance() . 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 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 2
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 3
Source File: ECKeyAgreement.java    From gsc-core 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, ex);
    }
}
 
Example 4
Source File: ECKeyAgreement.java    From tron-wallet-android with Apache License 2.0 5 votes vote down vote up
public static KeyAgreement getInstance() {
    try {
        return KeyAgreement.getInstance(ALGORITHM);
    } catch (NoSuchAlgorithmException ex) {
        throw new AssertionError(algorithmAssertionMsg, ex);
    }
}
 
Example 5
Source File: ECKeyAgreement.java    From wkcwallet-java 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);
  }
}
 
Example 6
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 7
Source File: ECKeyAgreement.java    From wkcwallet-java with Apache License 2.0 5 votes vote down vote up
public static KeyAgreement getInstance() {
  try {
    return KeyAgreement.getInstance(ALGORITHM);
  } catch (NoSuchAlgorithmException ex) {
    throw new AssertionError(algorithmAssertionMsg, ex);
  }
}
 
Example 8
Source File: ECKeyAgreement.java    From nuls-v2 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 9
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 10
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 11
Source File: ECKeyAgreement.java    From aion 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 12
Source File: ECKeyAgreement.java    From tron-wallet-android with Apache License 2.0 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 13
Source File: TestDH.java    From openjdk-jdk9 with GNU General Public License v2.0 4 votes vote down vote up
@Override
    public void main(Provider p) throws Exception {
        if (p.getService("KeyAgreement", "DH") == null) {
            System.out.println("DH not supported, skipping");
            return;
        }
        KeyPairGenerator kpg = KeyPairGenerator.getInstance("DH", p);
        kpg.initialize(512);
        KeyPair kp1 = kpg.generateKeyPair();
        KeyPair kp2 = kpg.generateKeyPair();

        KeyAgreement ka1, ka2;
        ka1 = KeyAgreement.getInstance("DH", p);
        ka1.init(kp1.getPrivate());
        ka1.doPhase(kp2.getPublic(), true);
        System.out.println("Derive 1...");
        byte[] secret1 = ka1.generateSecret();

        ka1.init(kp2.getPrivate());
        ka1.doPhase(kp1.getPublic(), true);
        System.out.println("Derive 2...");
        byte[] secret2 = ka1.generateSecret();

        if (Arrays.equals(secret1, secret2) == false) {
            throw new Exception("Secrets (1,2) do not match");
        }

        ka2 = KeyAgreement.getInstance("DH", "SunJCE");
        ka2.init(kp1.getPrivate());
        ka2.doPhase(kp2.getPublic(), true);
        System.out.println("Derive 3...");
        byte[] secret3 = ka2.generateSecret();

        if (Arrays.equals(secret1, secret3) == false) {
            throw new Exception("Secrets (1,3) do not match");
        }

        ka2.init(kp2.getPrivate());
        ka2.doPhase(kp1.getPublic(), true);
        System.out.println("Derive 4...");
        byte[] secret4 = ka2.generateSecret();

        if (Arrays.equals(secret1, secret4) == false) {
            throw new Exception("Secrets (1,4) do not match");
        }

        testAlgorithm(ka2, kp2, ka1, kp1, "DES");
        testAlgorithm(ka2, kp2, ka1, kp1, "DESede");
//      testAlgorithm(ka2, kp2, ka1, kp1, "AES");
//      testAlgorithm(ka2, kp2, ka1, kp1, "RC4");
        testAlgorithm(ka2, kp2, ka1, kp1, "Blowfish");
        testAlgorithm(ka2, kp2, ka1, kp1, "TlsPremasterSecret");
    }
 
Example 14
Source File: ProtocolDecoderPHE.java    From BiglyBT with GNU General Public License v2.0 4 votes vote down vote up
protected void
initCrypto()

	throws IOException
{
	try{
        KeyPair key_pair = generateDHKeyPair( transport, outbound );

        key_agreement = KeyAgreement.getInstance("DH");

        key_agreement.init(key_pair.getPrivate());

        DHPublicKey	dh_public_key = (DHPublicKey)key_pair.getPublic();

        BigInteger	dh_y = dh_public_key.getY();

        dh_public_key_bytes = bigIntegerToBytes( dh_y, DH_SIZE_BYTES );

	}catch( Throwable e ){

		throw( new IOException( Debug.getNestedExceptionMessage(e)));
	}
}
 
Example 15
Source File: SameDHKeyStressTest.java    From TencentKona-8 with GNU General Public License v2.0 4 votes vote down vote up
public KAParticipant(String pName, String algo) throws NoSuchAlgorithmException, NoSuchProviderException {
    name = pName;
    algorithm = algo;
    keyGen = KeyPairGenerator.getInstance(algo,"SunJCE");
    ka = KeyAgreement.getInstance(algo,"SunJCE");
}
 
Example 16
Source File: SameDHKeyStressTest.java    From hottub with GNU General Public License v2.0 4 votes vote down vote up
public KAParticipant(String pName, String algo) throws NoSuchAlgorithmException, NoSuchProviderException {
    name = pName;
    algorithm = algo;
    keyGen = KeyPairGenerator.getInstance(algo,"SunJCE");
    ka = KeyAgreement.getInstance(algo,"SunJCE");
}
 
Example 17
Source File: SameDHKeyStressTest.java    From dragonwell8_jdk with GNU General Public License v2.0 4 votes vote down vote up
public KAParticipant(String pName, String algo) throws NoSuchAlgorithmException, NoSuchProviderException {
    name = pName;
    algorithm = algo;
    keyGen = KeyPairGenerator.getInstance(algo,"SunJCE");
    ka = KeyAgreement.getInstance(algo,"SunJCE");
}
 
Example 18
Source File: SameDHKeyStressTest.java    From openjdk-jdk9 with GNU General Public License v2.0 4 votes vote down vote up
public KAParticipant(String pName, String algo) throws NoSuchAlgorithmException, NoSuchProviderException {
    name = pName;
    algorithm = algo;
    keyGen = KeyPairGenerator.getInstance(algo,"SunJCE");
    ka = KeyAgreement.getInstance(algo,"SunJCE");
}
 
Example 19
Source File: SupportedGroupsExtension.java    From openjsse with GNU General Public License v2.0 4 votes vote down vote up
private NamedGroup(int id, NamedGroupType type, String name,
        String oid, String algorithm, boolean isFips,
        ProtocolVersion[] supportedProtocols,
        AlgorithmParameterSpec keAlgParamSpec) {
    this.id = id;
    this.type = type;
    this.name = name;
    this.oid = oid;
    this.algorithm = algorithm;
    this.isFips = isFips;
    this.supportedProtocols = supportedProtocols;
    this.keAlgParamSpec = keAlgParamSpec;

    boolean mediator = (keAlgParamSpec != null);

    // An EC provider, for example the SunEC provider, may support
    // AlgorithmParameters but not KeyPairGenerator or KeyAgreement.
    if (mediator && (type == NamedGroupType.NAMED_GROUP_ECDHE)) {
        mediator = JsseJce.isEcAvailable();
    }
    // Check the specific algorithm parameters.
    if (mediator) {
        try {
            AlgorithmParameters algParams =
                AlgorithmParameters.getInstance(type.algorithm);
            algParams.init(keAlgParamSpec);
        } catch (InvalidParameterSpecException
                | NoSuchAlgorithmException exp) {
            if (type != NamedGroupType.NAMED_GROUP_XDH) {
                mediator = false;
                if (SSLLogger.isOn && SSLLogger.isOn("ssl,handshake")) {
                    SSLLogger.warning(
                        "No AlgorithmParameters for " + name, exp);
                }
            } else {
                // Please remove the following code if the XDH/X25519/X448
                // AlgorithmParameters algorithms are supported in JDK.
                try {
                    KeyAgreement.getInstance(name);

                    // The following service is also needed.  But for
                    // performance, check the KeyAgreement impl only.
                    //
                    // KeyFactory.getInstance(name);
                    // KeyPairGenerator.getInstance(name);
                    // AlgorithmParameters.getInstance(name);
                } catch (NoSuchAlgorithmException nsae) {
                    mediator = false;
                    if (SSLLogger.isOn && SSLLogger.isOn("ssl,handshake")) {
                        SSLLogger.warning(
                            "No AlgorithmParameters for " + name, nsae);
                    }
                }
            }
        }
    }
    this.isAvailable = mediator;
}
 
Example 20
Source File: ProtocolDecoderPHE.java    From TorrentEngine with GNU General Public License v3.0 4 votes vote down vote up
protected void
initCrypto()

	throws IOException
{
	try{
        KeyPair key_pair = generateDHKeyPair( transport, outbound );
    	    
        key_agreement = KeyAgreement.getInstance("DH");
        
        key_agreement.init(key_pair.getPrivate());
       
        DHPublicKey	dh_public_key = (DHPublicKey)key_pair.getPublic();
        
        BigInteger	dh_y = dh_public_key.getY();
        
        dh_public_key_bytes = bigIntegerToBytes( dh_y, DH_SIZE_BYTES );
        
	}catch( Throwable e ){
		
		throw( new IOException( Debug.getNestedExceptionMessage(e)));
	}
}