Example usage for java.security KeyPair getPrivate

List of usage examples for java.security KeyPair getPrivate

Introduction

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

Prototype

public PrivateKey getPrivate() 

Source Link

Document

Returns a reference to the private key component of this key pair.

Usage

From source file:com.hyeb.front.controller.CommonController.java

/**
 * //from  w w w .  j  av a 2 s. c o m
 */
@RequestMapping(value = "/public_key", method = RequestMethod.GET)
public @ResponseBody Map<String, String> publicKey(HttpServletRequest request) {
    Assert.notNull(request);
    KeyPair keyPair = RSAUtils.generateKeyPair();
    RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
    RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
    HttpSession session = request.getSession();
    session.setAttribute(PRIVATE_KEY_ATTRIBUTE_NAME, privateKey);

    Map<String, String> data = new HashMap<String, String>();
    data.put("modulus", Base64.encodeBase64String(publicKey.getModulus().toByteArray()));
    data.put("exponent", Base64.encodeBase64String(publicKey.getPublicExponent().toByteArray()));
    return data;
}

From source file:org.cesecore.certificates.certificate.CertificateDataSerializationTest.java

/** This test prints the serialized form of a CertificateData object, and was used to generated the data above. */
@Test//from w w  w.  j a v a2 s.  c  o  m
public void testSerializeCurrent() throws Exception {
    log.trace(">testSerializeCurrent");
    final KeyPair kp = KeyTools.genKeys("1024", "RSA");
    final Certificate cert = CertTools.genSelfCert("CN=certuser", 10 * 365, null, kp.getPrivate(),
            kp.getPublic(), "SHA256withRSA", false);
    final CertificateData certData = new CertificateData(cert, kp.getPublic(), "certuser", "1234567812345678",
            CertificateConstants.CERT_ACTIVE, CertificateConstants.CERTTYPE_ENDENTITY,
            CertificateProfileConstants.CERTPROFILE_FIXED_ENDUSER, EndEntityInformation.NO_ENDENTITYPROFILE,
            null, new Date().getTime(), false, true);
    final ByteArrayOutputStream baos = new ByteArrayOutputStream();
    final Base64OutputStream b64os = new Base64OutputStream(baos);
    final ObjectOutputStream oos = new ObjectOutputStream(b64os);
    oos.writeObject(certData);
    oos.close();
    b64os.close();
    log.info("Base 64 of serialized CertData is: " + baos.toString("US-ASCII"));
    log.trace("<testSerializeCurrent");
}

From source file:org.globus.gsi.gssapi.test.GlobusGSSCredentialTest.java

private X509Credential buildSelfSigned() throws GeneralSecurityException {
    KeyPair kp = kpg.generateKeyPair();
    PrivateKey privateKey = kp.getPrivate();
    certificateGenerator.setPublicKey(kp.getPublic());
    X509Certificate certificate = certificateGenerator.generate(privateKey);
    X509Certificate[] certChain = new X509Certificate[] { certificate };
    return new X509Credential(privateKey, certChain);
}

From source file:net.solarnetwork.pki.bc.test.BCCertificateServiceTest.java

@Test
public void signCertificate() throws Exception {
    X509Certificate cert = service.generateCertificate(TEST_DN, publicKey, privateKey);
    String csr = service.generatePKCS10CertificateRequestString(cert, privateKey);

    KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
    keyGen.initialize(2048, new SecureRandom());
    KeyPair caKeypair = keyGen.generateKeyPair();
    X509Certificate caCert = service.generateCertificationAuthorityCertificate(TEST_CA_DN,
            caKeypair.getPublic(), caKeypair.getPrivate());

    X509Certificate signed = service.signCertificate(csr, caCert, caKeypair.getPrivate());
    assertEquals("Issuer", caCert.getSubjectX500Principal(), signed.getIssuerX500Principal());
    assertEquals("Subject", cert.getSubjectX500Principal(), signed.getSubjectX500Principal());
}

From source file:hudson.plugins.ec2.EC2AxisPrivateKey.java

/**
 * Obtains the fingerprint of the key in the "ab:cd:ef:...:12" format.
 */// w  ww  .  ja v a  2s .  com
public String getFingerprint() throws IOException {
    Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
    @SuppressWarnings("deprecation")
    Reader r = new BufferedReader(new StringReader(privateKey.toString()));
    @SuppressWarnings("resource")
    PEMReader pem = new PEMReader(r, new PasswordFinder() {
        public char[] getPassword() {
            throw PRIVATE_KEY_WITH_PASSWORD;
        }
    });

    try {
        KeyPair pair = (KeyPair) pem.readObject();
        if (pair == null)
            return null;
        PrivateKey key = pair.getPrivate();
        return digest(key);
    } catch (RuntimeException e) {
        if (e == PRIVATE_KEY_WITH_PASSWORD)
            throw new IOException("This private key is password protected, which isn't supported yet");
        throw e;
    }
}

From source file:org.gluu.com.ox_push2.u2f.v2.cert.KeyPairGeneratorImpl.java

public String keyPairToJson(KeyPair keyPair) throws U2FException {
    ECPrivateKey privateKey = (ECPrivateKey) keyPair.getPrivate();
    ECPublicKey publicKey = (ECPublicKey) keyPair.getPublic();

    BigInteger x = publicKey.getQ().getAffineXCoord().toBigInteger();
    BigInteger y = publicKey.getQ().getAffineYCoord().toBigInteger();
    BigInteger d = privateKey.getD();

    try {// www  . j a  va  2  s. c o  m
        JSONObject jsonPrivateKey = new JSONObject();
        jsonPrivateKey.put("d", Utils.encodeHexString(d.toByteArray()));

        JSONObject jsonPublicKey = new JSONObject();
        jsonPublicKey.put("x", Utils.encodeHexString(x.toByteArray()));
        jsonPublicKey.put("y", Utils.encodeHexString(y.toByteArray()));

        JSONObject jsonKeyPair = new JSONObject();
        jsonKeyPair.put("privateKey", jsonPrivateKey);
        jsonKeyPair.put("publicKey", jsonPublicKey);

        String keyPairJson = jsonKeyPair.toString();

        if (BuildConfig.DEBUG)
            Log.d(TAG, "JSON key pair: " + keyPairJson);

        return keyPairJson;
    } catch (JSONException ex) {
        throw new U2FException("Failed to serialize key pair to JSON", ex);
    }
}

From source file:com.xinferin.licensing.LicenceGenerator.java

/**
 * Creates a new private and public key and at the same time encodes the public key as XML to be used by the .NET client
 * @param size//from w  w w .  ja v a  2s.  c o m
 * @param productId
 *
 */
private void firstTimeInitialisation(int size) {
    try {

        // Get Key Pair Generator for RSA.
        KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
        keyGen.initialize(size);

        KeyPair keypair = keyGen.genKeyPair();
        privateKey = keypair.getPrivate();
        publicKey = keypair.getPublic();

        // Get the bytes of the public and private keys
        byte[] privateKeyBytes = privateKey.getEncoded();
        byte[] publicKeyBytes = publicKey.getEncoded();

        // store temporarily witht he public key for the lifetime of this class.
        encodedPrivateKey = new Base64().encode(privateKeyBytes);

        // Generate the Private Key, Public Key and Public Key in XML format.
        KeyFactory.getInstance("RSA").generatePrivate(new PKCS8EncodedKeySpec(privateKeyBytes));
        KeyFactory.getInstance("RSA").generatePublic(new X509EncodedKeySpec(publicKeyBytes));
        RSAPublicKey rsaPublicKey = (RSAPublicKey) KeyFactory.getInstance("RSA")
                .generatePublic(new X509EncodedKeySpec(publicKeyBytes));

        // Store the public key in XML string to make compatible .Net public key file
        encodedToXMLPublicKey = getRSAPublicKeyAsXMLString(rsaPublicKey);

    } catch (Exception ex) {
        System.out.println(ex.getMessage());
    }
}

From source file:SecureConnection.java

private byte[] getPublicKeyStep2(DHParameterSpec dhParamSpec) throws Exception {
    KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("DH");
    keyPairGen.initialize(dhParamSpec);//w ww .j  av a 2s  .c om
    KeyPair keyPair = keyPairGen.generateKeyPair();
    this.keyAgree = KeyAgreement.getInstance("DH");
    this.keyAgree.init(keyPair.getPrivate());
    return keyPair.getPublic().getEncoded();
}

From source file:com.joyent.manta.client.AuthAwareConfigContextTest.java

private void differentKeyPairsSameContent(final KeyPair keyPairFromContent, final KeyPair keyPairFromFile) {
    // different instances
    Assert.assertNotSame(keyPairFromContent, keyPairFromFile);

    // same key//from ww w. j  av a  2 s .co  m
    AssertJUnit.assertArrayEquals(keyPairFromContent.getPrivate().getEncoded(),
            keyPairFromFile.getPrivate().getEncoded());
    AssertJUnit.assertArrayEquals(keyPairFromContent.getPublic().getEncoded(),
            keyPairFromFile.getPublic().getEncoded());
}

From source file:com.streamreduce.util.CAGenerator.java

public static X509Certificate generateCACert(KeyPair keyPair) throws Exception {
    Date startDate = new Date(System.currentTimeMillis()); // time from which certificate is valid
    Calendar expiry = Calendar.getInstance();
    expiry.add(Calendar.DAY_OF_YEAR, 1000 * 365);
    Date expiryDate = expiry.getTime(); // time after which certificate is not valid
    BigInteger serialNumber = new BigInteger(Long.toString(System.currentTimeMillis())); // serial number for certificate

    X509V3CertificateGenerator certGen = new X509V3CertificateGenerator();
    X500Principal dnName = new X500Principal("CN=Nodeable Client");

    certGen.setSerialNumber(serialNumber);
    certGen.setIssuerDN(dnName);//from   w  w w  .j  a  v  a2 s . c om
    certGen.setNotBefore(startDate);
    certGen.setNotAfter(expiryDate);
    certGen.setSubjectDN(dnName);
    certGen.setPublicKey(keyPair.getPublic());
    certGen.setSignatureAlgorithm("MD5withRSA");

    certGen.addExtension(X509Extensions.AuthorityKeyIdentifier, false,
            new AuthorityKeyIdentifierStructure(keyPair.getPublic()));
    certGen.addExtension(X509Extensions.SubjectKeyIdentifier, false,
            new SubjectKeyIdentifierStructure(keyPair.getPublic()));

    return certGen.generate(keyPair.getPrivate()); // note: private key of CA
}