Search in sources :

Example 86 with KeyPairGenerator

use of java.security.KeyPairGenerator in project geode by apache.

the class GMSEncryptJUnitTest method testDHAlgo3.

@Test
public void testDHAlgo3() throws Exception {
    DHParameterSpec dhSkipParamSpec;
    System.out.println("Using SKIP Diffie-Hellman parameters");
    dhSkipParamSpec = new DHParameterSpec(skip1024Modulus, skip1024Base);
    // Alice creates her own DH key pair
    System.out.println("ALICE: Generate DH keypair ...");
    KeyPairGenerator aliceKpairGen = KeyPairGenerator.getInstance("DH");
    aliceKpairGen.initialize(dhSkipParamSpec);
    KeyPair aliceKpair = aliceKpairGen.generateKeyPair();
    // Bob creates his own DH key pair
    System.out.println("BOB: Generate DH keypair ...");
    KeyPairGenerator bobKpairGen = KeyPairGenerator.getInstance("DH");
    bobKpairGen.initialize(dhSkipParamSpec);
    KeyPair bobKpair = bobKpairGen.generateKeyPair();
    // Alice initialize
    System.out.println("ALICE: Initialize ...");
    KeyAgreement aliceKeyAgree = KeyAgreement.getInstance("DH");
    aliceKeyAgree.init(aliceKpair.getPrivate());
    // Bob initialize
    System.out.println("BOB  : Initialize ...");
    KeyAgreement bobKeyAgree = KeyAgreement.getInstance("DH");
    bobKeyAgree.init(bobKpair.getPrivate());
    // Alice uses Carol's public key
    aliceKeyAgree.doPhase(bobKpair.getPublic(), true);
    // Bob uses Alice's public key
    bobKeyAgree.doPhase(aliceKpair.getPublic(), true);
    String dhKalgo = "AES";
    // Alice, Bob and Carol compute their secrets
    SecretKey aliceSharedSecret = aliceKeyAgree.generateSecret(dhKalgo);
    System.out.println("Alice secret: " + toHexString(aliceSharedSecret.getEncoded()));
    SecretKey bobSharedSecret = bobKeyAgree.generateSecret(dhKalgo);
    System.out.println("Bob   secret: " + toHexString(bobSharedSecret.getEncoded()));
    // Compare Alice and Bob
    if (!java.util.Arrays.equals(aliceSharedSecret.getEncoded(), bobSharedSecret.getEncoded()))
        throw new Exception("Alice and Bob differ");
    System.out.println("Alice and Bob are the same");
}
Also used : KeyPair(java.security.KeyPair) SecretKey(javax.crypto.SecretKey) DHParameterSpec(javax.crypto.spec.DHParameterSpec) KeyPairGenerator(java.security.KeyPairGenerator) KeyAgreement(javax.crypto.KeyAgreement) Test(org.junit.Test) MembershipTest(org.apache.geode.test.junit.categories.MembershipTest) IntegrationTest(org.apache.geode.test.junit.categories.IntegrationTest)

Example 87 with KeyPairGenerator

use of java.security.KeyPairGenerator in project geode by apache.

the class GMSEncryptJUnitTest method testDHAlgo.

@Test
public void testDHAlgo() throws Exception {
    DHParameterSpec dhSkipParamSpec;
    System.out.println("Using SKIP Diffie-Hellman parameters");
    dhSkipParamSpec = new DHParameterSpec(skip1024Modulus, skip1024Base);
    // Alice creates her own DH key pair
    System.out.println("ALICE: Generate DH keypair ...");
    KeyPairGenerator aliceKpairGen = KeyPairGenerator.getInstance("DH");
    aliceKpairGen.initialize(dhSkipParamSpec);
    KeyPair aliceKpair = aliceKpairGen.generateKeyPair();
    // Bob creates his own DH key pair
    System.out.println("BOB: Generate DH keypair ...");
    KeyPairGenerator bobKpairGen = KeyPairGenerator.getInstance("DH");
    bobKpairGen.initialize(dhSkipParamSpec);
    KeyPair bobKpair = bobKpairGen.generateKeyPair();
    // Carol creates her own DH key pair
    System.out.println("CAROL: Generate DH keypair ...");
    KeyPairGenerator carolKpairGen = KeyPairGenerator.getInstance("DH");
    carolKpairGen.initialize(dhSkipParamSpec);
    KeyPair carolKpair = carolKpairGen.generateKeyPair();
    // Alice initialize
    System.out.println("ALICE: Initialize ...");
    KeyAgreement aliceKeyAgree = KeyAgreement.getInstance("DH");
    aliceKeyAgree.init(aliceKpair.getPrivate());
    // Bob initialize
    System.out.println("BOB: Initialize ...");
    KeyAgreement bobKeyAgree = KeyAgreement.getInstance("DH");
    bobKeyAgree.init(bobKpair.getPrivate());
    // Carol initialize
    System.out.println("CAROL: Initialize ...");
    KeyAgreement carolKeyAgree = KeyAgreement.getInstance("DH");
    carolKeyAgree.init(carolKpair.getPrivate());
    // Alice uses Carol's public key
    Key ac = aliceKeyAgree.doPhase(carolKpair.getPublic(), false);
    // Bob uses Alice's public key
    Key ba = bobKeyAgree.doPhase(aliceKpair.getPublic(), false);
    // Carol uses Bob's public key
    Key cb = carolKeyAgree.doPhase(bobKpair.getPublic(), false);
    // Alice uses Carol's result from above
    aliceKeyAgree.doPhase(cb, true);
    // Bob uses Alice's result from above
    bobKeyAgree.doPhase(ac, true);
    // Carol uses Bob's result from above
    carolKeyAgree.doPhase(ba, true);
    // Alice, Bob and Carol compute their secrets
    byte[] aliceSharedSecret = aliceKeyAgree.generateSecret();
    System.out.println("Alice secret: " + toHexString(aliceSharedSecret));
    byte[] bobSharedSecret = bobKeyAgree.generateSecret();
    System.out.println("Bob secret: " + toHexString(bobSharedSecret));
    byte[] carolSharedSecret = carolKeyAgree.generateSecret();
    System.out.println("Carol secret: " + toHexString(carolSharedSecret));
    // Compare Alice and Bob
    if (!java.util.Arrays.equals(aliceSharedSecret, bobSharedSecret))
        throw new Exception("Alice and Bob differ");
    System.out.println("Alice and Bob are the same");
    // Compare Bob and Carol
    if (!java.util.Arrays.equals(bobSharedSecret, carolSharedSecret))
        throw new Exception("Bob and Carol differ");
    System.out.println("Bob and Carol are the same");
}
Also used : KeyPair(java.security.KeyPair) DHParameterSpec(javax.crypto.spec.DHParameterSpec) KeyPairGenerator(java.security.KeyPairGenerator) KeyAgreement(javax.crypto.KeyAgreement) Key(java.security.Key) SecretKey(javax.crypto.SecretKey) Test(org.junit.Test) MembershipTest(org.apache.geode.test.junit.categories.MembershipTest) IntegrationTest(org.apache.geode.test.junit.categories.IntegrationTest)

Example 88 with KeyPairGenerator

use of java.security.KeyPairGenerator in project geode by apache.

the class GMSEncryptJUnitTest method testDHAlgo2.

@Test
public void testDHAlgo2() throws Exception {
    DHParameterSpec dhSkipParamSpec;
    System.out.println("Using SKIP Diffie-Hellman parameters");
    dhSkipParamSpec = new DHParameterSpec(skip1024Modulus, skip1024Base);
    // Alice creates her own DH key pair
    System.out.println("ALICE: Generate DH keypair ...");
    KeyPairGenerator aliceKpairGen = KeyPairGenerator.getInstance("DH");
    aliceKpairGen.initialize(dhSkipParamSpec);
    KeyPair aliceKpair = aliceKpairGen.generateKeyPair();
    // Bob creates his own DH key pair
    System.out.println("BOB: Generate DH keypair ...");
    KeyPairGenerator bobKpairGen = KeyPairGenerator.getInstance("DH");
    bobKpairGen.initialize(dhSkipParamSpec);
    KeyPair bobKpair = bobKpairGen.generateKeyPair();
    // Alice initialize
    System.out.println("ALICE: Initialize ...");
    KeyAgreement aliceKeyAgree = KeyAgreement.getInstance("DH");
    aliceKeyAgree.init(aliceKpair.getPrivate());
    // Bob initialize
    System.out.println("BOB  : Initialize ...");
    KeyAgreement bobKeyAgree = KeyAgreement.getInstance("DH");
    bobKeyAgree.init(bobKpair.getPrivate());
    // Alice uses Carol's public key
    aliceKeyAgree.doPhase(bobKpair.getPublic(), true);
    // Bob uses Alice's public key
    bobKeyAgree.doPhase(aliceKpair.getPublic(), true);
    // Alice, Bob and Carol compute their secrets
    byte[] aliceSharedSecret = aliceKeyAgree.generateSecret();
    System.out.println("Alice secret: " + toHexString(aliceSharedSecret));
    byte[] bobSharedSecret = bobKeyAgree.generateSecret();
    System.out.println("Bob   secret: " + toHexString(bobSharedSecret));
    // Compare Alice and Bob
    if (!java.util.Arrays.equals(aliceSharedSecret, bobSharedSecret))
        throw new Exception("Alice and Bob differ");
    System.out.println("Alice and Bob are the same");
}
Also used : KeyPair(java.security.KeyPair) DHParameterSpec(javax.crypto.spec.DHParameterSpec) KeyPairGenerator(java.security.KeyPairGenerator) KeyAgreement(javax.crypto.KeyAgreement) Test(org.junit.Test) MembershipTest(org.apache.geode.test.junit.categories.MembershipTest) IntegrationTest(org.apache.geode.test.junit.categories.IntegrationTest)

Example 89 with KeyPairGenerator

use of java.security.KeyPairGenerator in project karaf by apache.

the class KnownHostsManagerTest method createPubKey.

private PublicKey createPubKey() throws NoSuchAlgorithmException {
    KeyPairGenerator gen = KeyPairGenerator.getInstance(ALGORITHM);
    gen.initialize(KEY_SIZE);
    KeyPair keyPair = gen.generateKeyPair();
    return keyPair.getPublic();
}
Also used : KeyPair(java.security.KeyPair) KeyPairGenerator(java.security.KeyPairGenerator)

Example 90 with KeyPairGenerator

use of java.security.KeyPairGenerator in project oxTrust by GluuFederation.

the class UpdateTrustRelationshipAction method getCertForGeneratedSP.

/**
	 * If there is no certificate selected, or certificate is invalid -
	 * generates one.
	 * 
	 * @author �Oleksiy Tataryn�
	 * @return certificate for generated SP
	 * @throws CertificateEncodingException
	 */
public String getCertForGeneratedSP() {
    X509Certificate cert = null;
    try {
        cert = sslService.getPEMCertificate(certWrapper.getStream());
    } catch (Exception e) {
        log.error(e.getMessage(), e);
    }
    if (cert == null) {
        facesMessages.add(FacesMessage.SEVERITY_INFO, "Certificate were not provided, or was incorrect. Appliance will create a self-signed certificate.");
        if (Security.getProvider(BouncyCastleProvider.PROVIDER_NAME) == null) {
            Security.addProvider(new BouncyCastleProvider());
        }
        try {
            KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("RSA", "BC");
            keyPairGen.initialize(2048);
            KeyPair pair = keyPairGen.generateKeyPair();
            StringWriter keyWriter = new StringWriter();
            PEMWriter pemFormatWriter = new PEMWriter(keyWriter);
            pemFormatWriter.writeObject(pair.getPrivate());
            pemFormatWriter.close();
            String url = trustRelationship.getUrl().replaceFirst(".*//", "");
            X509v3CertificateBuilder v3CertGen = new JcaX509v3CertificateBuilder(new X500Name("CN=" + url + ", OU=None, O=None L=None, C=None"), BigInteger.valueOf(new SecureRandom().nextInt()), new Date(System.currentTimeMillis() - 1000L * 60 * 60 * 24 * 30), new Date(System.currentTimeMillis() + (1000L * 60 * 60 * 24 * 365 * 10)), new X500Name("CN=" + url + ", OU=None, O=None L=None, C=None"), pair.getPublic());
            cert = new JcaX509CertificateConverter().setProvider("BC").getCertificate(v3CertGen.build(new JcaContentSignerBuilder("MD5withRSA").setProvider("BC").build(pair.getPrivate())));
            org.apache.commons.codec.binary.Base64 encoder = new org.apache.commons.codec.binary.Base64(64);
            byte[] derCert = cert.getEncoded();
            String pemCertPre = new String(encoder.encode(derCert));
            log.debug(Shibboleth3ConfService.PUBLIC_CERTIFICATE_START_LINE);
            log.debug(pemCertPre);
            log.debug(Shibboleth3ConfService.PUBLIC_CERTIFICATE_END_LINE);
            saveCert(trustRelationship, pemCertPre);
            saveKey(trustRelationship, keyWriter.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
    //			String certName = appConfiguration.getCertDir() + File.separator + StringHelper.removePunctuation(appConfiguration.getOrgInum())
    //					+ "-shib.crt";
    //			File certFile = new File(certName);
    //			if (certFile.exists()) {
    //				cert = SSLService.instance().getPEMCertificate(certName);
    //			}
    }
    String certificate = null;
    if (cert != null) {
        try {
            certificate = new String(Base64.encode(cert.getEncoded()));
            log.info("##### certificate = " + certificate);
        } catch (CertificateEncodingException e) {
            certificate = null;
            facesMessages.add(FacesMessage.SEVERITY_ERROR, "Failed to encode provided certificate. Please notify Gluu support about this.");
            log.error("Failed to encode certificate to DER", e);
        }
    } else {
        facesMessages.add(FacesMessage.SEVERITY_INFO, "Certificate were not provided, or was incorrect. Appliance will create a self-signed certificate.");
    }
    return certificate;
}
Also used : KeyPair(java.security.KeyPair) Base64(org.bouncycastle.util.encoders.Base64) JcaContentSignerBuilder(org.bouncycastle.operator.jcajce.JcaContentSignerBuilder) SecureRandom(java.security.SecureRandom) PEMWriter(org.bouncycastle.openssl.PEMWriter) CertificateEncodingException(java.security.cert.CertificateEncodingException) KeyPairGenerator(java.security.KeyPairGenerator) X500Name(org.bouncycastle.asn1.x500.X500Name) X509Certificate(java.security.cert.X509Certificate) LdapMappingException(org.gluu.site.ldap.persistence.exception.LdapMappingException) CertificateEncodingException(java.security.cert.CertificateEncodingException) IOException(java.io.IOException) Date(java.util.Date) StringWriter(java.io.StringWriter) JcaX509v3CertificateBuilder(org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder) X509v3CertificateBuilder(org.bouncycastle.cert.X509v3CertificateBuilder) JcaX509CertificateConverter(org.bouncycastle.cert.jcajce.JcaX509CertificateConverter) JcaX509v3CertificateBuilder(org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder) BouncyCastleProvider(org.bouncycastle.jce.provider.BouncyCastleProvider)

Aggregations

KeyPairGenerator (java.security.KeyPairGenerator)197 KeyPair (java.security.KeyPair)145 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)43 SecureRandom (java.security.SecureRandom)39 PublicKey (java.security.PublicKey)27 PrivateKey (java.security.PrivateKey)26 X509Certificate (java.security.cert.X509Certificate)23 KeyFactory (java.security.KeyFactory)21 IOException (java.io.IOException)19 BigInteger (java.math.BigInteger)17 GeneralSecurityException (java.security.GeneralSecurityException)15 Signature (java.security.Signature)15 Date (java.util.Date)15 Cipher (javax.crypto.Cipher)15 KeyAgreement (javax.crypto.KeyAgreement)15 RSAPublicKey (java.security.interfaces.RSAPublicKey)14 X500Principal (javax.security.auth.x500.X500Principal)13 ECPrivateKey (java.security.interfaces.ECPrivateKey)12 ECPublicKey (java.security.interfaces.ECPublicKey)12 HashMap (java.util.HashMap)11