Example usage for java.security KeyPair KeyPair

List of usage examples for java.security KeyPair KeyPair

Introduction

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

Prototype

public KeyPair(PublicKey publicKey, PrivateKey privateKey) 

Source Link

Document

Constructs a key pair from the given public key and private key.

Usage

From source file:com.atlassian.jira.security.auth.trustedapps.TestDefaultCurrentApplicationStore.java

@Test
public void testSetCurrentApplicationBadKeys() throws Exception {
    TrustedApplicationProperties properties = new TrustedApplicationProperties(TEST_UID, PAIR);
    DefaultCurrentApplicationStore store = new DefaultCurrentApplicationStore(properties, stubServerId("ABC"),
            new MemoryCacheManager(), new SimpleClusterLockService());

    store.start();//from ww  w .  jav a  2 s .  c om
    //Need to init the cache.
    store.getCurrentApplication();
    assertState(PAIR, TEST_UID, store);

    try {
        store.setCurrentApplication("somethings", null);
        fail("Not Allowed.");
    } catch (IllegalArgumentException good) {
    }

    try {
        store.setCurrentApplication("somethings", new KeyPair(null, PAIR2.getPrivate()));
        fail("Not Allowed.");
    } catch (IllegalArgumentException good) {
    }

    try {
        store.setCurrentApplication("somethings", new KeyPair(PAIR2.getPublic(), null));
        fail("Not Allowed.");
    } catch (IllegalArgumentException good) {
    }

    assertState(PAIR, TEST_UID, store);
}

From source file:org.kaaproject.kaa.client.persistence.KaaClientPropertiesState.java

private KeyPair getOrInitKeyPair(boolean isAutogeneratedKeys) {
    LOG.debug("Check if key pair exists {}, {}", clientPublicKeyFileLocation, clientPrivateKeyFileLocation);
    if (keyPair != null) {
        return keyPair;
    }/*w ww . j  av a 2 s  .  c  o  m*/
    if (storage.exists(clientPublicKeyFileLocation) && storage.exists(clientPrivateKeyFileLocation)) {
        InputStream publicKeyInput = null;
        InputStream privateKeyInput = null;
        try {
            publicKeyInput = storage.openForRead(clientPublicKeyFileLocation);
            privateKeyInput = storage.openForRead(clientPrivateKeyFileLocation);

            PublicKey publicKey = KeyUtil.getPublic(publicKeyInput);
            PrivateKey privateKey = KeyUtil.getPrivate(privateKeyInput);

            if (publicKey != null && privateKey != null) {
                keyPair = new KeyPair(publicKey, privateKey);
                if (!KeyUtil.validateKeyPair(keyPair)) {
                    throw new InvalidKeyException();
                }

                return keyPair;
            }
        } catch (InvalidKeyException ex) {
            keyPair = null;
            LOG.error("Unable to parse client RSA keypair. Generating new keys.. Reason {}", ex);
        } catch (Exception ex) {
            LOG.error("Error loading client RSA keypair. Reason {}", ex);
            throw new RuntimeException(ex); // NOSONAR
        } finally {
            IOUtils.closeQuietly(publicKeyInput);
            IOUtils.closeQuietly(privateKeyInput);
        }
    }
    if (isAutogeneratedKeys) {
        LOG.debug("Generating Client Key pair");
        OutputStream privateKeyOutput = null;
        OutputStream publicKeyOutput = null;
        try {
            privateKeyOutput = storage.openForWrite(clientPrivateKeyFileLocation);
            publicKeyOutput = storage.openForWrite(clientPublicKeyFileLocation);
            keyPair = KeyUtil.generateKeyPair(privateKeyOutput, publicKeyOutput);
        } catch (IOException ex) {
            LOG.error("Error generating Client Key pair", ex);
            throw new RuntimeException(ex);
        } finally {
            IOUtils.closeQuietly(privateKeyOutput);
            IOUtils.closeQuietly(publicKeyOutput);
        }
    } else {
        LOG.debug("Error loading key pair!", "Key pair is not found and key strategy is default");
        throw new KaaRuntimeException("Key pair is not found and your key strategy is default");
    }
    return keyPair;
}

From source file:org.keycloak.testsuite.client.OIDCJwksClientRegistrationTest.java

private KeyPair getKeyPairFromGeneratedPems(Map<String, String> generatedKeys) {
    String privateKeyPem = generatedKeys.get(TestingOIDCEndpointsApplicationResource.PRIVATE_KEY);
    String publicKeyPem = generatedKeys.get(TestingOIDCEndpointsApplicationResource.PUBLIC_KEY);
    PrivateKey privateKey = KeycloakModelUtils.getPrivateKey(privateKeyPem);
    PublicKey publicKey = KeycloakModelUtils.getPublicKey(publicKeyPem);
    return new KeyPair(publicKey, privateKey);
}

From source file:com.intuit.s3encrypt.S3Encrypt.java

public static KeyPair loadKeyPair(String filename, String algorithm)
        throws IOException, NoSuchAlgorithmException, InvalidKeySpecException {
    // Read public key from file.
    FileInputStream keyfis = new FileInputStream(filename + ".pub");
    byte[] encodedPublicKey = new byte[keyfis.available()];
    keyfis.read(encodedPublicKey);/*from   w  ww  .  j av  a  2  s  . c om*/
    keyfis.close();

    // Read private key from file.
    keyfis = new FileInputStream(filename);
    byte[] encodedPrivateKey = new byte[keyfis.available()];
    keyfis.read(encodedPrivateKey);
    keyfis.close();

    // Generate KeyPair from public and private keys.
    KeyFactory keyFactory = KeyFactory.getInstance(algorithm);
    X509EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(encodedPublicKey);
    PublicKey publicKey = keyFactory.generatePublic(publicKeySpec);

    PKCS8EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(encodedPrivateKey);
    PrivateKey privateKey = keyFactory.generatePrivate(privateKeySpec);

    return new KeyPair(publicKey, privateKey);

}

From source file:com.atlassian.jira.security.auth.trustedapps.TestDefaultCurrentApplicationStore.java

private static KeyPair getKeys(String publicKeyString, String privateKeyString) {
    PrivateKey privateKey = KeyFactory.getPrivateKey(privateKeyString);
    PublicKey publicKey = KeyFactory.getPublicKey(publicKeyString);

    return new KeyPair(publicKey, privateKey);
}

From source file:org.ejbca.core.model.ca.catoken.BaseCAToken.java

public int getCATokenStatus() {
    if (log.isTraceEnabled()) {
        log.trace(">getCATokenStatus");
    }/*  ww w . ja  v a2 s . co m*/
    autoActivate();
    int ret = ICAToken.STATUS_OFFLINE;
    // If we have no keystrings, no point in continuing...
    if (this.keyStrings != null) {
        String strings[] = this.keyStrings.getAllStrings();
        int i = 0;
        while (strings != null && i < strings.length && this.mKeys != null
                && this.mKeys.get(strings[i]) != null) {
            i++;
        }
        // If we don't have any keys for the strings, or we don't have enough keys for the strings, no point in continuing...
        if (strings != null && i >= strings.length) {
            PrivateKey privateKey;
            PublicKey publicKey;
            try {
                privateKey = getPrivateKey(SecConst.CAKEYPURPOSE_KEYTEST);
                publicKey = getPublicKey(SecConst.CAKEYPURPOSE_KEYTEST);
            } catch (CATokenOfflineException e) {
                privateKey = null;
                publicKey = null;
                if (log.isDebugEnabled()) {
                    log.debug("no test key defined");
                }
            }
            if (privateKey != null && publicKey != null) {
                //Check that that the testkey is usable by doing a test signature.
                try {
                    testKey(new KeyPair(publicKey, privateKey));
                    // If we can test the testkey, we are finally active!
                    ret = ICAToken.STATUS_ACTIVE;
                } catch (Throwable th) {
                    log.error(intres.getLocalizedMessage("catoken.activationtestfail"), th);
                }
            }
        }
    }
    if (log.isTraceEnabled()) {
        log.trace("<getCATokenStatus: " + ret);
    }
    return ret;
}

From source file:org.hyperledger.fabric_ca.sdk.HFCAClient.java

/**
 * Re-Enroll the user with member service
 *
 * @param user User to be re-enrolled//from  w w w  . j  av a 2 s  .  co m
 * @param req  Enrollment request with the following fields: hosts, profile, csr, label
 * @return enrollment
 * @throws EnrollmentException
 * @throws InvalidArgumentException
 */

public Enrollment reenroll(User user, EnrollmentRequest req)
        throws EnrollmentException, InvalidArgumentException {

    if (cryptoSuite == null) {
        throw new InvalidArgumentException("Crypto primitives not set.");
    }

    if (user == null) {
        throw new InvalidArgumentException("reenrollment user is missing");
    }
    if (user.getEnrollment() == null) {
        throw new InvalidArgumentException("reenrollment user is not a valid user object");
    }

    logger.debug(format("re-enroll user: %s, url: %s", user.getName(), url));

    try {
        setUpSSL();

        PublicKey publicKey = cryptoSuite
                .bytesToCertificate(user.getEnrollment().getCert().getBytes(StandardCharsets.UTF_8))
                .getPublicKey();

        KeyPair keypair = new KeyPair(publicKey, user.getEnrollment().getKey());

        // generate CSR

        String pem = cryptoSuite.generateCertificationRequest(user.getName(), keypair);

        // build request body
        req.setCSR(pem);
        if (caName != null && !caName.isEmpty()) {
            req.setCAName(caName);
        }
        String body = req.toJson();

        // build authentication header
        JsonObject result = httpPost(url + HFCA_REENROLL, body, user);

        // get new cert from response
        Base64.Decoder b64dec = Base64.getDecoder();
        String signedPem = new String(b64dec.decode(result.getString("Cert").getBytes(UTF_8)));
        logger.debug(format("[HFCAClient] re-enroll returned pem:[%s]", signedPem));

        logger.debug(format("reenroll user %s done.", user.getName()));
        return new X509Enrollment(keypair, signedPem);

    } catch (EnrollmentException ee) {
        logger.error(ee.getMessage(), ee);
        throw ee;
    } catch (Exception e) {
        EnrollmentException ee = new EnrollmentException(format("Failed to re-enroll user %s", user), e);
        logger.error(e.getMessage(), e);
        throw ee;
    }
}

From source file:net.nicholaswilliams.java.licensing.licensor.interfaces.cli.TestConsoleRSAKeyPairGenerator.java

@Test
public void testDoInteractive01() throws Exception {
    ByteArrayOutputStream stream = new ByteArrayOutputStream();

    String privateFileName = "testDoInteractive01Private.key";
    String publicFileName = "testDoInteractive01Public.key";

    this.console.cli = EasyMock.createMockBuilder(CommandLine.class).withConstructor()
            .addMockedMethod("hasOption", String.class).addMockedMethod("getOptionValue", String.class)
            .createMock();/*from  www .  j ava 2s.c  om*/

    PrivateKey privateKey = EasyMock.createMock(PrivateKey.class);
    PublicKey publicKey = EasyMock.createMock(PublicKey.class);
    KeyPair keyPair = new KeyPair(publicKey, privateKey);

    this.device.printOutLn("Would you like to...");
    EasyMock.expectLastCall();
    this.device.printOutLn("    (1) Save the public and private keys to .key files?");
    EasyMock.expectLastCall();
    this.device.printOutLn("    (2) Generate compilable Java code with embedded keys?");
    EasyMock.expectLastCall();
    EasyMock.expect(this.device.readLine("Your selection (default 1)? ")).andReturn(" ");
    this.device.printOutLn();
    EasyMock.expectLastCall();

    this.device.printOutLn("Would you like to...");
    EasyMock.expectLastCall();
    this.device.printOutLn("    (1) Use the same password to encrypt both keys?");
    EasyMock.expectLastCall();
    this.device.printOutLn("    (2) Use a different password for each key?");
    EasyMock.expectLastCall();
    EasyMock.expect(this.device.readLine("Your selection (default 1)? ")).andReturn(" ");
    this.device.printOutLn();
    EasyMock.expectLastCall();

    EasyMock.expect(this.device.promptForValidPassword(6, 32, "both keys"))
            .andReturn("keyPassword01".toCharArray());
    this.device.printOutLn("Passwords match.");
    EasyMock.expectLastCall();
    this.device.printOutLn();
    EasyMock.expectLastCall();

    EasyMock.expect(this.device.readLine("Please enter the name of a file to store the public key in: "))
            .andReturn(publicFileName);
    this.device.printOutLn();
    EasyMock.expectLastCall();
    EasyMock.expect(this.device.readLine("Please enter the name of a file to store the private key in: "))
            .andReturn(privateFileName);
    this.device.printOutLn();
    EasyMock.expectLastCall();

    this.device.printOut("Generating RSA key pair, 2048-bit long modulus");
    EasyMock.expectLastCall();
    EasyMock.expect(this.device.out()).andReturn(new PrintStream(stream));

    EasyMock.expect(this.generator.generateKeyPair()).andReturn(keyPair);

    this.device.printOutLn("+++");
    EasyMock.expectLastCall();
    this.device.printOutLn();
    EasyMock.expectLastCall();
    this.device.printOut("Key pair generated. Encrypting keys with 128-bit AES security");
    EasyMock.expectLastCall();
    EasyMock.expect(this.device.out()).andReturn(new PrintStream(stream));

    final Capture<char[]> capture1 = new Capture<char[]>();

    this.generator.saveKeyPairToFiles(EasyMock.eq(keyPair), EasyMock.eq(privateFileName),
            EasyMock.eq(publicFileName), EasyMock.capture(capture1));
    EasyMock.expectLastCall().andAnswer(new IAnswer<Void>() {
        @Override
        public Void answer() throws Throwable {
            assertNotNull("The captured key password should not be null.", capture1.getValue());
            assertArrayEquals("The captured key password is not correct.", "keyPassword01".toCharArray(),
                    capture1.getValue());
            return null;
        }
    });

    this.device.printOutLn("+++");
    EasyMock.expectLastCall();
    this.device.printOutLn();
    EasyMock.expectLastCall();
    this.device.printOutLn("Private key written to " + privateFileName);
    EasyMock.expectLastCall();
    this.device.printOutLn("Public key written to " + publicFileName);

    EasyMock.replay(this.generator, this.device, this.console.cli, privateKey, publicKey);

    try {
        this.console.doInteractive();

        assertNotNull("The captured key password should still not be null.", capture1.getValue());
        assertArrayEquals("The captured key password should have been erased.",
                new char[capture1.getValue().length], capture1.getValue());
    } finally {
        EasyMock.verify(this.console.cli, privateKey, publicKey);
    }
}

From source file:org.cesecore.certificates.ca.X509CA.java

/**
 * @see CA#createRequest(Collection, String, Certificate, int)
 *///w  ww. ja va 2 s  .co m
@Override
public byte[] createRequest(CryptoToken cryptoToken, Collection<ASN1Encodable> attributes, String signAlg,
        Certificate cacert, int signatureKeyPurpose) throws CryptoTokenOfflineException {
    log.trace(
            ">createRequest: " + signAlg + ", " + CertTools.getSubjectDN(cacert) + ", " + signatureKeyPurpose);
    ASN1Set attrset = new DERSet();
    if (attributes != null) {
        log.debug("Adding attributes in the request");
        Iterator<ASN1Encodable> iter = attributes.iterator();
        ASN1EncodableVector vec = new ASN1EncodableVector();
        while (iter.hasNext()) {
            ASN1Encodable o = (ASN1Encodable) iter.next();
            vec.add(o);
        }
        attrset = new DERSet(vec);
    }
    final X500NameStyle nameStyle;
    if (getUsePrintableStringSubjectDN()) {
        nameStyle = PrintableStringNameStyle.INSTANCE;
    } else {
        nameStyle = CeSecoreNameStyle.INSTANCE;
    }
    X500Name x509dn = CertTools.stringToBcX500Name(getSubjectDN(), nameStyle, getUseLdapDNOrder());
    PKCS10CertificationRequest req;
    try {
        final CAToken catoken = getCAToken();
        final String alias = catoken.getAliasFromPurpose(signatureKeyPurpose);
        final KeyPair keyPair = new KeyPair(cryptoToken.getPublicKey(alias), cryptoToken.getPrivateKey(alias));
        req = CertTools.genPKCS10CertificationRequest(signAlg, x509dn, keyPair.getPublic(), attrset,
                keyPair.getPrivate(), cryptoToken.getSignProviderName());
        log.trace("<createRequest");
        return req.getEncoded();
    } catch (CryptoTokenOfflineException e) { // NOPMD, since we catch wide below
        throw e;
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}