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:org.candlepin.CRLBenchmark.java

@Setup(Level.Trial)
public void buildMassiveCRL() throws Exception {
    X500Name issuer = new X500Name("CN=Test Issuer");

    KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA");

    generator.initialize(2048);//  ww w. j a  v  a2s  .  com
    KeyPair keyPair = generator.generateKeyPair();

    Provider bc = new BouncyCastleProvider();
    ContentSigner signer = new JcaContentSignerBuilder("SHA256WithRSAEncryption").setProvider(bc)
            .build(keyPair.getPrivate());

    X509v2CRLBuilder crlBuilder = new X509v2CRLBuilder(issuer, new Date());

    crlBuilder.addExtension(X509Extension.authorityKeyIdentifier, false,
            new AuthorityKeyIdentifierStructure(keyPair.getPublic()));
    /* With a CRL number of 127, incrementing it should cause the number of bytes in the length
     * portion of the TLV to increase by one.*/
    crlBuilder.addExtension(X509Extension.cRLNumber, false, new CRLNumber(new BigInteger("127")));

    for (int i = 0; i < 2000000; i++) {
        crlBuilder.addCRLEntry(new BigInteger(String.valueOf(i)), new Date(), CRLReason.unspecified);
    }

    X509CRLHolder holder = crlBuilder.build(signer);
    X509CRL crl = new JcaX509CRLConverter().setProvider(bc).getCRL(holder);

    crlFile = File.createTempFile("crl", ".der");
    System.out.println("\nWrote test crl to " + crlFile.getAbsolutePath());
    FileUtils.writeByteArrayToFile(crlFile, crl.getEncoded());
}

From source file:com.microsoft.azure.keyvault.test.CertificateOperationsTest.java

/**
 * Verify a RSA key pair with a simple encrypt/decrypt test.
 * /* w  ww. j  a  va  2 s. c  o m*/
 * @throws NoSuchPaddingException
 * @throws NoSuchAlgorithmException
 * @throws InvalidKeyException
 * @throws BadPaddingException
 * @throws IllegalBlockSizeException
 */
private static void verifyRSAKeyPair(KeyPair keyPair) throws NoSuchAlgorithmException, NoSuchPaddingException,
        InvalidKeyException, IllegalBlockSizeException, BadPaddingException {
    // Validate algorithm is RSA
    Assert.assertTrue(keyPair.getPublic().getAlgorithm().equals(ALGO_RSA));
    Assert.assertTrue(keyPair.getPrivate().getAlgorithm().equals(ALGO_RSA));

    // Generate an array of 10 random bytes
    byte[] plainData = new byte[10];
    Random random = new Random();
    random.nextBytes(plainData);

    // Encrypt using the public key
    Cipher encryptCipher = Cipher.getInstance(ALGO_RSA);
    encryptCipher.init(Cipher.ENCRYPT_MODE, keyPair.getPublic());
    byte[] encryptedData = encryptCipher.doFinal(plainData);

    // Decrypt using the private key
    Cipher decryptCipher = Cipher.getInstance(ALGO_RSA);
    decryptCipher.init(Cipher.DECRYPT_MODE, keyPair.getPrivate());
    byte[] decryptedData = decryptCipher.doFinal(encryptedData);

    // Validate plainData is equal to decryptedData
    Assert.assertArrayEquals(plainData, decryptedData);
}

From source file:edu.vt.middleware.crypt.signature.SignatureAlgorithmTest.java

/**
 * @param  signature  A crypto signature algorithm to test.
 * @param  keys  Public/private key pair used for signing.
 * @param  converter  Converter used to convert sig bytes to String.
 *
 * @throws  Exception  On test failure.//from w  w  w  . j av a 2 s.c  o m
 */
@Test(groups = { "functest", "signature" }, dataProvider = "testdata")
public void testSignVerify(final SignatureAlgorithm signature, final KeyPair keys, final Converter converter)
        throws Exception {
    logger.info("Testing signature algorithm " + signature + " with converter " + converter);
    signature.setSignKey(keys.getPrivate());
    signature.initSign();
    if (converter == null) {
        final byte[] signedBytes = signature.sign(CLEARTEXT.getBytes());
        signature.setVerifyKey(keys.getPublic());
        signature.initVerify();
        AssertJUnit.assertTrue(signature.verify(CLEARTEXT.getBytes(), signedBytes));
    } else {
        final String sig = signature.sign(CLEARTEXT.getBytes(), converter);
        signature.setVerifyKey(keys.getPublic());
        signature.initVerify();
        AssertJUnit.assertTrue(signature.verify(CLEARTEXT.getBytes(), sig, converter));
    }
}

From source file:kr.ac.cau.mecs.cass.processor.SigninProcessor.java

@Override
public Signal process(Signal signal) {
    Signal resignal = new Signal();

    resignal.setReceiver(signal.getSender());
    resignal.setSender("CASS");
    resignal.setAction(new Action(Action.ACT_SIGNIN));

    if (signal.getPayload() != null && (signal.getPayload().getPayload() instanceof JSONObjectPayload)) {
        JSONObject jobj = (JSONObject) signal.getPayload().getPayload().getData();

        if (jobj.has("userid") && jobj.has("userpw")) {
            String userid = jobj.optString("userid");
            String userpw = jobj.optString("userpw");
            //valid payload

            DBUserEntity _user = UserEntityDAO.getByUserID(session, userid);

            if (_user != null && _user.getPassword().equals(userpw)) {
                //valid credential...
                JSONObject jres = new JSONObject();

                if (_user.getAccessToken() == null) {
                    System.out.println("new token");
                    _user.setAccessToken(new DBAccessTokenEntity());
                    _user.getAccessToken().setUser(_user);
                    session.save(_user.getAccessToken());
                }//from  ww  w . j  av a  2  s  . co m

                KeyPair keypair = AccessTokenUtil.generateKeyPair(System.currentTimeMillis());

                String usertoken = BCrypt.hashpw(userid, BCrypt.gensalt(12));
                String authtoken = AccessTokenUtil.signData(usertoken, keypair.getPrivate());

                _user.getAccessToken().setPrivateKey(AccessTokenUtil.encodePrivateKey(keypair.getPrivate()));
                _user.getAccessToken().setPublicKey(AccessTokenUtil.encodePublicKey(keypair.getPublic()));
                _user.getAccessToken().setAccessToken(authtoken);
                _user.getAccessToken().setUserToken(usertoken);

                jres.putOpt("authToken", authtoken);
                jres.putOpt("userToken", usertoken);

                session.update(_user);

                resignal.setPayload(new Payload(new JSONObjectPayload(jres)));

            } else {
                setGenericMessage(resignal, "invalid credential");
            }

        } else {
            setGenericMessage(resignal, "invalid payload type");
        }
    } else {
        //inform user invalid payload type
        setGenericMessage(resignal, "invalid payload type");
    }

    return resignal;
}

From source file:MainClass.java

public static X509Certificate generateV3Certificate(KeyPair pair)
        throws InvalidKeyException, NoSuchProviderException, SignatureException {
    Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());

    X509V3CertificateGenerator certGen = new X509V3CertificateGenerator();

    certGen.setSerialNumber(BigInteger.valueOf(System.currentTimeMillis()));
    certGen.setIssuerDN(new X500Principal("CN=Test Certificate"));
    certGen.setNotBefore(new Date(System.currentTimeMillis() - 10000));
    certGen.setNotAfter(new Date(System.currentTimeMillis() + 10000));
    certGen.setSubjectDN(new X500Principal("CN=Test Certificate"));
    certGen.setPublicKey(pair.getPublic());
    certGen.setSignatureAlgorithm("SHA256WithRSAEncryption");

    certGen.addExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(false));
    certGen.addExtension(X509Extensions.KeyUsage, true,
            new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyEncipherment));
    certGen.addExtension(X509Extensions.ExtendedKeyUsage, true,
            new ExtendedKeyUsage(KeyPurposeId.id_kp_serverAuth));

    certGen.addExtension(X509Extensions.SubjectAlternativeName, false,
            new GeneralNames(new GeneralName(GeneralName.rfc822Name, "test@test.test")));

    return certGen.generateX509Certificate(pair.getPrivate(), "BC");
}

From source file:com.cellngine.crypto.RSACipher.java

@Override
public void generateKeypair(final int keyLength) {
    if (keyLength <= 0) {
        throw new IllegalArgumentException("Key length must be positive and nonzero");
    }// w w w  .j  ava  2  s. c o m

    final KeyPairGenerator generator;
    try {
        generator = KeyPairGenerator.getInstance(ALGORITHM);
    } catch (final NoSuchAlgorithmException e) {
        LOG.error("Unable to get key generator instance (" + ALGORITHM + ")", e);
        return;
    }

    try {
        generator.initialize(keyLength, this.random);
    } catch (final InvalidParameterException e) {
        throw new IllegalArgumentException("Unsupported key length");
    }

    final KeyPair pair = generator.generateKeyPair();
    this.publicKey = pair.getPublic();
    this.privateKey = pair.getPrivate();
}

From source file:com.thoughtworks.go.server.util.HttpTestUtil.java

private KeyPair generateKeyPair() {
    try {//from  w  ww . j a  v a2s .c om
        KeyPair seed = KeyPairGenerator.getInstance("RSA", "BC").generateKeyPair();
        RSAPrivateKey privateSeed = (RSAPrivateKey) seed.getPrivate();
        RSAPublicKey publicSeed = (RSAPublicKey) seed.getPublic();
        KeyFactory fact = KeyFactory.getInstance("RSA", "BC");
        RSAPrivateKeySpec privateKeySpec = new RSAPrivateKeySpec(privateSeed.getModulus(),
                privateSeed.getPrivateExponent());
        RSAPublicKeySpec publicKeySpec = new RSAPublicKeySpec(publicSeed.getModulus(),
                publicSeed.getPublicExponent());
        return new KeyPair(fact.generatePublic(publicKeySpec), fact.generatePrivate(privateKeySpec));
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

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

@Override
public void setCurrentApplication(String applicationId, KeyPair pair) {
    notBlank("applicationId cannot be blank.", applicationId);
    Assertions.notNull("pair cannot be null.", pair);
    Assertions.notNull("pair.private cannot be null.", pair.getPrivate());
    Assertions.notNull("pair.public cannot be null.", pair.getPublic());

    accessLock.lock();//from  w  w  w.  ja  va2 s .com
    try {
        applicationProperties.setText(Keys.PRIVATE_KEY_DATA, KeyFactory.encode(pair.getPrivate()));
        applicationProperties.setText(Keys.PUBLIC_KEY_DATA, KeyFactory.encode(pair.getPublic()));
        applicationProperties.setString(Keys.UID, applicationId);
        cache.reset();
    } finally {
        accessLock.unlock();
    }
}

From source file:com.ibm.mobilefirstplatform.clientsdk.android.security.mca.internal.certificate.DefaultJSONSigner.java

@Override
public String sign(KeyPair keyPair, JSONObject json) throws Exception {

    if (keyPair == null || json == null) {
        throw new IllegalArgumentException("parameter cannot be null");
    }//  ww  w .ja  v  a2 s  .  c o m

    RSAPublicKey publicKey = ((RSAPublicKey) keyPair.getPublic());
    PrivateKey privateKey = keyPair.getPrivate();

    // create CSR Header (based on public key)
    JSONObject jwsHeaderJson = new JSONObject();
    jwsHeaderJson.put(ALG, "RS256");

    JSONObject publicKeyDataJson = new JSONObject();
    publicKeyDataJson.put(ALG, "RSA");

    String mod = encodeUrlSafe(publicKey.getModulus().toByteArray());
    publicKeyDataJson.put("mod", mod);

    String exp = encodeUrlSafe(publicKey.getPublicExponent().toByteArray());
    publicKeyDataJson.put("exp", exp);

    jwsHeaderJson.put("jpk", publicKeyDataJson);

    String jwsHeader = jwsHeaderJson.toString();
    String payload = json.toString();

    // concatenate JWS Header and payload.
    String csrHeaderAndPayload = encodeUrlSafe(jwsHeader.getBytes()) + "." + encodeUrlSafe(payload.getBytes());

    // create CSR Signature
    String jwsSignature = encodeUrlSafe(signCsrData(csrHeaderAndPayload, privateKey));

    // Concatenate them all, and return the result.
    return csrHeaderAndPayload + "." + jwsSignature;
}

From source file:com.frequencymarketing.citi.saml.PartnerSaml.java

private SAMLResponse getSAMLResponse(TySamlProfileData memberData, String a_clientIp) throws Exception {
    String memberId = memberData.getMemberId();
    SAMLIdentifier idgen = SAMLIdentifierFactory.getInstance();

    SAMLResponse samlResponse = new SAMLResponse();
    SAMLAssertion samlAssertion = new SAMLAssertion();
    SAMLAuthenticationStatement samlAuthenticationStatement = new SAMLAuthenticationStatement();
    SAMLSubject samlSubject = new SAMLSubject(new SAMLNameIdentifier(memberId, null, null),
            Collections.singleton(SAMLSubject.CONF_BEARER), null, null);

    samlResponse.setRecipient(getSamlProps().getRecipientURL());
    samlAuthenticationStatement.setSubjectIP(a_clientIp);
    samlAuthenticationStatement.setSubject(samlSubject);
    samlAuthenticationStatement.setAuthInstant(new Date());
    samlAuthenticationStatement.setAuthMethod(SAMLAuthenticationStatement.AuthenticationMethod_Password);
    samlAssertion.addStatement(samlAuthenticationStatement);
    samlAssertion.setId(idgen.getIdentifier());
    samlAssertion.setIssuer(getSamlProps().getIssuer());
    samlAssertion.setNotBefore(new Date(System.currentTimeMillis() - 30000));
    samlAssertion.setNotOnOrAfter(new Date(System.currentTimeMillis() + 90000));//2 minutes
    samlAssertion.addCondition(new SAMLAudienceRestrictionCondition(
            Collections.singleton(getSamlProps().getAudienceRestriction())));

    //NameIdentifier is the Member id.
    SAMLAttributeStatement samlsaStatement = new SAMLAttributeStatement();
    SAMLSubject l_subject2 = new SAMLSubject(new SAMLNameIdentifier(memberId, null, null),
            Collections.singleton(SAMLSubject.CONF_BEARER), null, null);

    samlsaStatement.setSubject(l_subject2);
    samlsaStatement = addToAttributeStatement(samlsaStatement, "member_id", memberId, null, XML.SAML_NS);

    samlsaStatement = addToAttributeStatement(samlsaStatement, "agent_id", memberData.getAgentId(), null,
            XML.SAML_NS);//www  .ja  va  2s.c  o  m

    samlsaStatement = addToAttributeStatement(samlsaStatement, "mbr_name_first", memberData.getFirstName(),
            null, XML.SAML_NS);
    samlsaStatement = addToAttributeStatement(samlsaStatement, "mbr_name_last", memberData.getLastName(), null,
            XML.SAML_NS);

    samlsaStatement = addToAttributeStatement(samlsaStatement, "point_balance", memberData.getPointBalance(),
            null, XML.SAML_NS);

    samlsaStatement = addToAttributeStatement(samlsaStatement, "email_address", memberData.getEmailAddress(),
            null, XML.SAML_NS);

    samlAssertion.addStatement(samlsaStatement);
    samlResponse.addAssertion(samlAssertion);
    samlResponse.setId(idgen.getIdentifier());

    //Load the KeyStore
    KeyStore keystore = CryptoKeystoreUtil.getKeyStore(getSamlProps().getKeystore(),
            getSamlProps().getKeystorePass().toCharArray());

    KeyPair keyPair = CryptoKeystoreUtil.getKeyPair(keystore, getSamlProps().getKeystoreAlias(),
            getSamlProps().getKeystorePass().toCharArray());

    samlResponse.sign(XMLSignature.ALGO_ID_SIGNATURE_RSA_SHA1, keyPair.getPrivate(), null);

    s_logger.debug(samlResponse.toString());
    return samlResponse;
}