Example usage for java.security PublicKey equals

List of usage examples for java.security PublicKey equals

Introduction

In this page you can find the example usage for java.security PublicKey equals.

Prototype

public boolean equals(Object obj) 

Source Link

Document

Indicates whether some other object is "equal to" this one.

Usage

From source file:MainClass.java

public static void main(String[] args) throws Exception {
    Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
    KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA", "BC");

    generator.initialize(128, new SecureRandom());
    KeyPair pair = generator.generateKeyPair();
    ASN1InputStream aIn = new ASN1InputStream(pair.getPublic().getEncoded());
    SubjectPublicKeyInfo info = SubjectPublicKeyInfo.getInstance(aIn.readObject());

    System.out.println(ASN1Dump.dumpAsString(info));
    System.out.println(ASN1Dump.dumpAsString(info.getPublicKey()));

    X509EncodedKeySpec x509Spec = new X509EncodedKeySpec(pair.getPublic().getEncoded());
    KeyFactory keyFact = KeyFactory.getInstance("RSA", "BC");
    PublicKey pubKey = keyFact.generatePublic(x509Spec);

    System.out.println(pubKey.equals(pair.getPublic()));
}

From source file:Main.java

public static void main(String[] argv) throws Exception {
    String algorithm = "DSA"; // or RSA, DH, etc.

    // Generate a 1024-bit Digital Signature Algorithm (DSA) key pair
    KeyPairGenerator keyGen = KeyPairGenerator.getInstance(algorithm);
    keyGen.initialize(1024);/*www  .j a v a 2 s  .  com*/
    KeyPair keypair = keyGen.genKeyPair();
    PrivateKey privateKey = keypair.getPrivate();
    PublicKey publicKey = keypair.getPublic();

    byte[] privateKeyBytes = privateKey.getEncoded();
    byte[] publicKeyBytes = publicKey.getEncoded();

    KeyFactory keyFactory = KeyFactory.getInstance(algorithm);
    EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(privateKeyBytes);
    PrivateKey privateKey2 = keyFactory.generatePrivate(privateKeySpec);

    EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(publicKeyBytes);
    PublicKey publicKey2 = keyFactory.generatePublic(publicKeySpec);

    // The orginal and new keys are the same
    boolean same = privateKey.equals(privateKey2);
    same = publicKey.equals(publicKey2);
}

From source file:gov.niem.ws.util.SecurityUtil.java

/**
 * Check that the certificate in the holder of key assertion matches
 * the passed certificate, sent via another channel (e.g. SSL client auth).
 * The certificate must be validated separately, before making this call.
 * @param assertion SAML holder of key assertion.
 * @param presentedCert certificate claimed to be presented in the HoK.
 * @return//  w  w w .  j a v a2 s .c  om
 * @throws IOException 
 * @throws SAXException 
 * @throws ParserConfigurationException 
 */
public static boolean confirmHolderOfKey(Document assertion, X509Certificate presentedCert)
        throws ParserConfigurationException, SAXException, IOException {
    Node keyInfoNode = null;
    try {
        keyInfoNode = (Node) subjectConfirmationKeyInfoPath.evaluate(assertion, XPathConstants.NODE);
    } catch (XPathExpressionException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        return false;
    }
    if (keyInfoNode == null) {
        System.out.println("key info not found in subject confirmation");
        return false;
    }
    X509Certificate assertionCert = getCertificateFromKeyInfo(keyInfoNode);
    if (assertionCert != null) {
        return assertionCert.equals(presentedCert);
    }

    PublicKey publicKey = getPublicKeyFromKeyInfo(keyInfoNode);
    if (publicKey != null) {
        return publicKey.equals(presentedCert.getPublicKey());
    }

    return false;
}

From source file:org.jasig.portal.security.provider.saml.PublicKeyVerifyingSSLSocketFactory.java

/**
 * This method makes a connection to the server by utilizing the base class
 * method, but it adds a validation of the server's public key if one was
 * supplied previously.//from w ww  .j  av a  2  s. co m
 * 
 * @see org.apache.http.conn.ssl.SSLSocketFactory#connectSocket(java.net.Socket, java.lang.String, int, java.net.InetAddress, int, org.apache.http.params.HttpParams)
 */
@Override
public Socket connectSocket(final Socket sock, final String host, final int port,
        final InetAddress localAddress, int localPort, final HttpParams params) throws IOException {
    SSLSocket newSocket = (SSLSocket) super.connectSocket(sock, host, port, localAddress, localPort, params);

    if (publicKey != null) {
        logger.debug("Verifying SSL Socket to {}:{} against configured public key {}",
                new Object[] { host, port, publicKey });

        SSLSession session = newSocket.getSession();
        Certificate[] certs = session.getPeerCertificates();
        boolean matchFound = false;

        for (int i = 0; i < certs.length; i++) {
            X509Certificate x509 = (X509Certificate) certs[i];
            PublicKey certKey = x509.getPublicKey();

            if (certKey.equals(publicKey)) {
                logger.debug("Validated public key against server key: {}", certKey);
                matchFound = true;
                break;
            }
            logger.debug("server key doesn't match public key: {} ", certKey);
        }
        if (!matchFound) {
            newSocket.close();
            throw new IOException("Unable to verify the server's public key");
        }
    }
    return newSocket;
}

From source file:io.sample.sshd.utilities.EmbeddedSftpServer.java

@Override
public void afterPropertiesSet() throws Exception {
    final PublicKey allowedKey = decodePublicKey();

    this.server.setPublickeyAuthenticator(new PublickeyAuthenticator() {
        @Override//w ww  .j  a v  a  2 s  . c om
        public boolean authenticate(String username, PublicKey key, ServerSession session) {
            return key.equals(allowedKey);
        }
    });
    this.server.setPasswordAuthenticator(new PasswordAuthenticator() {
        public boolean authenticate(String username, String password, ServerSession session) {
            return username != null && username.equals(password);
        }
    });
    this.server.setPublickeyAuthenticator(new PublickeyAuthenticator() {
        public boolean authenticate(String username, PublicKey key, ServerSession session) {
            //File f = new File("/Users/" + username + "/.ssh/authorized_keys");
            return true;
        }
    });

    this.server.setPort(this.port);
    this.server.setKeyPairProvider(new SimpleGeneratorHostKeyProvider("src/test/resources/keys/hostkey.ser"));
    this.server.setSubsystemFactories(
            Collections.<NamedFactory<Command>>singletonList(new SftpSubsystem.Factory()));
    final String virtualDir = new FileSystemResource("src/test/resources/remote/").getFile().getAbsolutePath();
    server.setFileSystemFactory(new VirtualFileSystemFactory(virtualDir));
}

From source file:com.dreamworks.dsp.server.EmbeddedSftpServer.java

@Override
public void afterPropertiesSet() throws Exception {
    final PublicKey allowedKey = decodePublicKey();
    this.server.setPublickeyAuthenticator(new PublickeyAuthenticator() {

        @Override//from   w  w w  .j a va 2 s. co  m
        public boolean authenticate(String username, PublicKey key, ServerSession session) {
            return key.equals(allowedKey);
        }

    });
    this.server.setPort(this.port);
    this.server.setKeyPairProvider(new SimpleGeneratorHostKeyProvider("hostkey.ser"));
    this.server.setSubsystemFactories(
            Collections.<NamedFactory<Command>>singletonList(new SftpSubsystem.Factory()));
    final String virtualDir = new FileSystemResource("").getFile().getAbsolutePath();
    this.server.setFileSystemFactory(new NativeFileSystemFactory() {

        @Override
        public FileSystemView createFileSystemView(org.apache.sshd.common.Session session) {
            return new NativeFileSystemView(session.getUsername(), false) {

                @Override
                public String getVirtualUserDir() {
                    return virtualDir;
                }
            };
        }

    });
}

From source file:net.nicholaswilliams.java.licensing.encryption.TestKeyFileUtilities.java

@Test
public void testPublicKeyEncryption04() throws Throwable {
    PublicKey publicKey = KeyPairGenerator.getInstance(KeyFileUtilities.keyAlgorithm).generateKeyPair()
            .getPublic();//from  w w  w .  j  a  v  a  2 s  . c om

    PublicKey otherKey = KeyPairGenerator.getInstance(KeyFileUtilities.keyAlgorithm).generateKeyPair()
            .getPublic();

    assertFalse("The keys should not be equal (1).", otherKey.equals(publicKey));

    byte[] publicKeyData = KeyFileUtilities.writeEncryptedPublicKey(publicKey,
            "yourTestPassword02".toCharArray());

    assertNotNull("The key data should not be null.", publicKeyData);
    assertTrue("The key data should have length.", publicKeyData.length > 0);

    PublicKey publicKey2 = KeyFileUtilities.readEncryptedPublicKey(publicKeyData,
            "yourTestPassword02".toCharArray());

    assertNotNull("The key should not be null.", publicKey2);
    assertFalse("The objects should not be the same.", publicKey == publicKey2);
    assertEquals("The keys should be the same.", publicKey, publicKey2);

    assertFalse("The keys should not be equal (2).", otherKey.equals(publicKey2));
}

From source file:net.nicholaswilliams.java.licensing.encryption.TestKeyFileUtilities.java

@Test
public void testPublicKeyEncryption02() throws Throwable {
    File file = new File("testPublicKeyEncryption02.key");

    if (file.exists())
        FileUtils.forceDelete(file);/*from w w  w . j a  v a  2  s . co m*/

    PublicKey publicKey = KeyPairGenerator.getInstance(KeyFileUtilities.keyAlgorithm).generateKeyPair()
            .getPublic();

    PublicKey otherKey = KeyPairGenerator.getInstance(KeyFileUtilities.keyAlgorithm).generateKeyPair()
            .getPublic();

    assertFalse("The keys should not be equal (1).", otherKey.equals(publicKey));

    KeyFileUtilities.writeEncryptedPublicKey(publicKey, file, "yourTestPassword02".toCharArray());

    PublicKey publicKey2 = KeyFileUtilities.readEncryptedPublicKey(file, "yourTestPassword02".toCharArray());

    assertNotNull("The key should not be null.", publicKey2);
    assertFalse("The objects should not be the same.", publicKey == publicKey2);
    assertEquals("The keys should be the same.", publicKey, publicKey2);

    assertFalse("The keys should not be equal (2).", otherKey.equals(publicKey2));

    FileUtils.forceDelete(file);
}

From source file:org.apache.ws.security.components.crypto.Merlin.java

/**
 * Find the Public Key in a keystore. /*w  ww . ja va 2s  . c  o m*/
 */
private boolean findPublicKeyInKeyStore(PublicKey publicKey, KeyStore keyStoreToSearch) {
    if (keyStoreToSearch == null) {
        return false;
    }
    try {
        for (Enumeration<String> e = keyStoreToSearch.aliases(); e.hasMoreElements();) {
            String alias = e.nextElement();
            Certificate[] certs = keyStoreToSearch.getCertificateChain(alias);
            Certificate cert;
            if (certs == null || certs.length == 0) {
                // no cert chain, so lets check if getCertificate gives us a result.
                cert = keyStoreToSearch.getCertificate(alias);
                if (cert == null) {
                    continue;
                }
            } else {
                cert = certs[0];
            }
            if (!(cert instanceof X509Certificate)) {
                continue;
            }
            X509Certificate x509cert = (X509Certificate) cert;
            if (publicKey.equals(x509cert.getPublicKey())) {
                return true;
            }
        }
    } catch (KeyStoreException e) {
        return false;
    }
    return false;
}

From source file:org.cesecore.keys.util.KeyStoreTools.java

/**
 * Install certificate chain to key in keystore.
 * @param file name of the file with chain. Starting with the certificate of the key. Ending with the root certificate.
 * @throws Exception/*from   ww  w  . j av a 2  s . c  o m*/
 */
public void installCertificate(final String fileName) throws Exception {
    final X509Certificate chain[] = ((Collection<?>) CertTools.getCertsFromPEM(new FileInputStream(fileName)))
            .toArray(new X509Certificate[0]);
    final PublicKey importPublicKey = chain[0].getPublicKey();
    final String importKeyHash = CertTools.getFingerprintAsString(importPublicKey.getEncoded());
    final Enumeration<String> eAlias = getKeyStore().aliases();
    boolean notFound = true;
    while (eAlias.hasMoreElements() && notFound) {
        final String alias = eAlias.nextElement();
        final PublicKey hsmPublicKey = getCertificate(alias).getPublicKey();
        if (log.isDebugEnabled()) {
            log.debug("alias: " + alias + " SHA1 of public hsm key: "
                    + CertTools.getFingerprintAsString(hsmPublicKey.getEncoded())
                    + " SHA1 of first public key in chain: " + importKeyHash
                    + (chain.length == 1 ? ""
                            : ("SHA1 of last public key in chain: " + CertTools.getFingerprintAsString(
                                    chain[chain.length - 1].getPublicKey().getEncoded()))));
        }
        if (hsmPublicKey.equals(importPublicKey)) {
            log.info("Found a matching public key for alias \"" + alias + "\".");
            getKeyStore().setKeyEntry(alias, getPrivateKey(alias), null, chain);
            notFound = false;
        }
    }
    if (notFound) {
        final String msg = intres.getLocalizedMessage("token.errorkeynottoken", importKeyHash);
        throw new Exception(msg);
    }
}