Search in sources :

Example 41 with KeyPair

use of java.security.KeyPair in project GNS by MobilityFirst.

the class KeyPairUtils method generateAndSaveKeyPair.

/**
   * Saves the public/private key pair to preferences for the given user.
   *
   * @param gnsName the name of the GNS instance (e.g. "server.gns.name:8080")
   * @param username the user name or human readable name
   */
public static GuidEntry generateAndSaveKeyPair(String gnsName, String username) throws NoSuchAlgorithmException, EncryptionException {
    KeyPair keyPair = KeyPairGenerator.getInstance(GNSProtocol.RSA_ALGORITHM.toString()).generateKeyPair();
    String guid = SharedGuidUtils.createGuidStringFromPublicKey(keyPair.getPublic().getEncoded());
    GuidEntry guidEntry = new GuidEntry(gnsName, guid, keyPair.getPublic(), keyPair.getPrivate());
    saveKeyPair(gnsName, username, guid, keyPair);
    return guidEntry;
}
Also used : KeyPair(java.security.KeyPair)

Example 42 with KeyPair

use of java.security.KeyPair in project wildfly by wildfly.

the class SingleSignOnSessionFactoryBuilder method getValue.

@Override
public SingleSignOnSessionFactory getValue() {
    KeyStore store = this.keyStore.getValue();
    String alias = this.keyAlias;
    CredentialSource source = this.credentialSource.getValue();
    try {
        if (!store.containsAlias(alias)) {
            UndertowLogger.ROOT_LOGGER.missingKeyStoreEntry(alias);
        }
        if (!store.entryInstanceOf(alias, KeyStore.PrivateKeyEntry.class)) {
            UndertowLogger.ROOT_LOGGER.keyStoreEntryNotPrivate(alias);
        }
        PasswordCredential credential = source.getCredential(PasswordCredential.class);
        if (credential == null) {
            UndertowLogger.ROOT_LOGGER.missingCredential(source.toString());
        }
        ClearPassword password = credential.getPassword(ClearPassword.class);
        if (password == null) {
            UndertowLogger.ROOT_LOGGER.credentialNotClearPassword(credential.toString());
        }
        KeyStore.PrivateKeyEntry entry = (KeyStore.PrivateKeyEntry) store.getEntry(alias, new KeyStore.PasswordProtection(password.getPassword()));
        KeyPair keyPair = new KeyPair(entry.getCertificate().getPublicKey(), entry.getPrivateKey());
        Optional<SSLContext> context = Optional.ofNullable(this.sslContext).map(dependency -> dependency.getValue());
        return new DefaultSingleSignOnSessionFactory(this.manager.getValue(), keyPair, connection -> context.ifPresent(ctx -> connection.setSSLSocketFactory(ctx.getSocketFactory())));
    } catch (GeneralSecurityException | IOException e) {
        throw new IllegalArgumentException(e);
    }
}
Also used : ClearPassword(org.wildfly.security.password.interfaces.ClearPassword) KeyPair(java.security.KeyPair) ValueDependency(org.wildfly.clustering.service.ValueDependency) SSLContext(javax.net.ssl.SSLContext) Value(org.jboss.msc.value.Value) CredentialSource(org.wildfly.security.credential.source.CredentialSource) OperationContext(org.jboss.as.controller.OperationContext) DefaultSingleSignOnSessionFactory(org.wildfly.security.http.util.sso.DefaultSingleSignOnSessionFactory) GeneralSecurityException(java.security.GeneralSecurityException) CredentialSourceDependency(org.jboss.as.clustering.controller.CredentialSourceDependency) PasswordCredential(org.wildfly.security.credential.PasswordCredential) InjectedValueDependency(org.wildfly.clustering.service.InjectedValueDependency) ServiceTarget(org.jboss.msc.service.ServiceTarget) UndertowLogger(org.wildfly.extension.undertow.logging.UndertowLogger) SingleSignOnSessionFactory(org.wildfly.security.http.util.sso.SingleSignOnSessionFactory) CommonUnaryRequirement(org.jboss.as.clustering.controller.CommonUnaryRequirement) ServiceBuilder(org.jboss.msc.service.ServiceBuilder) IOException(java.io.IOException) KeyStore(java.security.KeyStore) ResourceServiceBuilder(org.jboss.as.clustering.controller.ResourceServiceBuilder) Objects(java.util.Objects) ModelNodes(org.jboss.as.clustering.dmr.ModelNodes) ValueService(org.jboss.msc.service.ValueService) Stream(java.util.stream.Stream) OperationFailedException(org.jboss.as.controller.OperationFailedException) SingleSignOnManager(org.wildfly.security.http.util.sso.SingleSignOnManager) Optional(java.util.Optional) ClearPassword(org.wildfly.security.password.interfaces.ClearPassword) ModelNode(org.jboss.dmr.ModelNode) Attribute(org.wildfly.extension.undertow.ApplicationSecurityDomainSingleSignOnDefinition.Attribute) Builder(org.wildfly.clustering.service.Builder) KeyPair(java.security.KeyPair) GeneralSecurityException(java.security.GeneralSecurityException) PasswordCredential(org.wildfly.security.credential.PasswordCredential) SSLContext(javax.net.ssl.SSLContext) IOException(java.io.IOException) KeyStore(java.security.KeyStore) DefaultSingleSignOnSessionFactory(org.wildfly.security.http.util.sso.DefaultSingleSignOnSessionFactory) CredentialSource(org.wildfly.security.credential.source.CredentialSource)

Example 43 with KeyPair

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

the class Main method startAgent.

private static SshAgent startAgent(String user, URL privateKeyUrl, String keyFile, FilePasswordProvider passwordProvider) {
    InputStream is = null;
    try {
        SshAgent agent = new AgentImpl();
        is = privateKeyUrl.openStream();
        ObjectInputStream r = new ObjectInputStream(is);
        KeyPair keyPair = (KeyPair) r.readObject();
        is.close();
        agent.addIdentity(keyPair, user);
        if (keyFile != null) {
            FileKeyPairProvider fileKeyPairProvider = new FileKeyPairProvider(Paths.get(keyFile));
            fileKeyPairProvider.setPasswordFinder(passwordProvider);
            for (KeyPair key : fileKeyPairProvider.loadKeys()) {
                agent.addIdentity(key, user);
            }
        }
        return agent;
    } catch (Throwable e) {
        close(is);
        System.err.println("Error starting ssh agent for: " + e.getMessage());
        return null;
    }
}
Also used : KeyPair(java.security.KeyPair) FileKeyPairProvider(org.apache.sshd.common.keyprovider.FileKeyPairProvider) ObjectInputStream(java.io.ObjectInputStream) ByteArrayInputStream(java.io.ByteArrayInputStream) FileInputStream(java.io.FileInputStream) NoCloseInputStream(org.apache.sshd.common.util.io.NoCloseInputStream) InputStream(java.io.InputStream) SshAgent(org.apache.sshd.agent.SshAgent) AgentImpl(org.apache.sshd.agent.local.AgentImpl) ObjectInputStream(java.io.ObjectInputStream)

Example 44 with KeyPair

use of java.security.KeyPair 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 45 with KeyPair

use of java.security.KeyPair 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)

Aggregations

KeyPair (java.security.KeyPair)903 KeyPairGenerator (java.security.KeyPairGenerator)345 Test (org.junit.Test)235 PrivateKey (java.security.PrivateKey)189 X509Certificate (java.security.cert.X509Certificate)185 PublicKey (java.security.PublicKey)167 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)127 IOException (java.io.IOException)121 BigInteger (java.math.BigInteger)87 Date (java.util.Date)78 SecureRandom (java.security.SecureRandom)75 KeyStore (java.security.KeyStore)74 GeneralSecurityException (java.security.GeneralSecurityException)63 RSAPublicKey (java.security.interfaces.RSAPublicKey)55 X500Principal (javax.security.auth.x500.X500Principal)53 File (java.io.File)52 KeyFactory (java.security.KeyFactory)52 ECPrivateKey (java.security.interfaces.ECPrivateKey)52 ECPublicKey (java.security.interfaces.ECPublicKey)52 InvalidKeyException (java.security.InvalidKeyException)40