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:test.integ.be.fedict.hsm.ws.WebServiceSecurityTest.java

@Test
public void testWSSecurityTS_BST_Signature() throws Exception {
    DigitalSignatureServicePortType dssPort = getPort();

    KeyPair keyPair = HSMProxyTestCredential.generateKeyPair();
    X509Certificate certificate = HSMProxyTestCredential.generateSelfSignedCertificate(keyPair);

    WSSecurityTestSOAPHandler securityTestSOAPHandler = new WSSecurityTestSOAPHandler();
    securityTestSOAPHandler.addTimestamp(true);
    securityTestSOAPHandler.addBinarySecurityToken(certificate);
    securityTestSOAPHandler.addSignature(keyPair.getPrivate());
    addSOAPHandler(securityTestSOAPHandler, dssPort);

    ObjectFactory objectFactory = new ObjectFactory();
    SignRequest signRequest = objectFactory.createSignRequest();

    try {//from w  w w .j  a v a 2s.  co  m
        dssPort.sign(signRequest);
        fail();
    } catch (SOAPFaultException e) {
        LOG.debug("expected exception: " + e.getMessage());
        // expected
    }
    assertEquals(1, getNumberOfSecurityAuditRecords());
}

From source file:test.integ.be.fedict.hsm.ws.WebServiceSecurityTest.java

@Test
public void testWSSecurity_SHA1DigestAlgoFails() throws Exception {
    DigitalSignatureServicePortType dssPort = getPort();

    KeyPair keyPair = HSMProxyTestCredential.generateKeyPair();
    X509Certificate certificate = HSMProxyTestCredential.generateSelfSignedCertificate(keyPair);

    WSSecurityTestSOAPHandler securityTestSOAPHandler = new WSSecurityTestSOAPHandler();
    securityTestSOAPHandler.addTimestamp(true);
    securityTestSOAPHandler.addBinarySecurityToken(certificate);
    securityTestSOAPHandler.addSignature(keyPair.getPrivate());
    securityTestSOAPHandler.setDigestAlgorithm(DigestMethod.SHA1);
    addSOAPHandler(securityTestSOAPHandler, dssPort);

    ObjectFactory objectFactory = new ObjectFactory();
    SignRequest signRequest = objectFactory.createSignRequest();

    try {/*from  ww w .  ja  v a  2  s  .  c  om*/
        dssPort.sign(signRequest);
        fail();
    } catch (SOAPFaultException e) {
        LOG.debug("expected exception: " + e.getMessage());
        // expected
    }
    assertEquals(1, getNumberOfSecurityAuditRecords());
}

From source file:test.integ.be.fedict.hsm.ws.WebServiceSecurityTest.java

@Test
public void testWSSecurity_RSASHA1SignatureAlgoFails() throws Exception {
    DigitalSignatureServicePortType dssPort = getPort();

    KeyPair keyPair = HSMProxyTestCredential.generateKeyPair();
    X509Certificate certificate = HSMProxyTestCredential.generateSelfSignedCertificate(keyPair);

    WSSecurityTestSOAPHandler securityTestSOAPHandler = new WSSecurityTestSOAPHandler();
    securityTestSOAPHandler.addTimestamp(true);
    securityTestSOAPHandler.addBinarySecurityToken(certificate);
    securityTestSOAPHandler.addSignature(keyPair.getPrivate());
    securityTestSOAPHandler.setSignatureAlgorithm(SignatureMethod.RSA_SHA1);
    addSOAPHandler(securityTestSOAPHandler, dssPort);

    ObjectFactory objectFactory = new ObjectFactory();
    SignRequest signRequest = objectFactory.createSignRequest();

    try {/*from  w  w  w  .  j  a  v  a2  s .com*/
        dssPort.sign(signRequest);
        fail();
    } catch (SOAPFaultException e) {
        LOG.debug("expected exception: " + e.getMessage());
        // expected
    }
    assertEquals(1, getNumberOfSecurityAuditRecords());
}

From source file:test.integ.be.fedict.hsm.ws.WebServiceSecurityTest.java

@Test
public void testWSSecurityUnsignedBodyFails() throws Exception {
    DigitalSignatureServicePortType dssPort = getPort();

    KeyPair keyPair = HSMProxyTestCredential.generateKeyPair();
    X509Certificate certificate = HSMProxyTestCredential.generateSelfSignedCertificate(keyPair);

    WSSecurityTestSOAPHandler securityTestSOAPHandler = new WSSecurityTestSOAPHandler();
    securityTestSOAPHandler.addTimestamp(true);
    securityTestSOAPHandler.addBinarySecurityToken(certificate);
    securityTestSOAPHandler.addSignature(keyPair.getPrivate());
    securityTestSOAPHandler.setSignBody(false);
    addSOAPHandler(securityTestSOAPHandler, dssPort);

    ObjectFactory objectFactory = new ObjectFactory();
    SignRequest signRequest = objectFactory.createSignRequest();

    try {/*from   w  ww. j  a va  2 s.  c  om*/
        dssPort.sign(signRequest);
        fail();
    } catch (SOAPFaultException e) {
        LOG.debug("expected exception: " + e.getMessage());
        // expected
    }
    assertEquals(1, getNumberOfSecurityAuditRecords());
}

From source file:com.cws.esolutions.security.processors.impl.FileSecurityProcessorImpl.java

/**
 * @see com.cws.esolutions.security.processors.interfaces.IFileSecurityProcessor#encryptFile(com.cws.esolutions.security.processors.dto.FileSecurityRequest)
 *//*from w  w  w  .  j  a  v a 2s . c  om*/
public synchronized FileSecurityResponse encryptFile(final FileSecurityRequest request)
        throws FileSecurityException {
    final String methodName = IFileSecurityProcessor.CNAME
            + "#encryptFile(final FileSecurityRequest request) throws FileSecurityException";

    if (DEBUG) {
        DEBUGGER.debug(methodName);
        DEBUGGER.debug("FileSecurityRequest: {}", request);
    }

    FileSecurityResponse response = new FileSecurityResponse();

    final RequestHostInfo reqInfo = request.getHostInfo();
    final UserAccount userAccount = request.getUserAccount();
    final KeyManager keyManager = KeyManagementFactory.getKeyManager(keyConfig.getKeyManager());

    if (DEBUG) {
        DEBUGGER.debug("RequestHostInfo: {}", reqInfo);
        DEBUGGER.debug("UserAccount", userAccount);
        DEBUGGER.debug("KeyManager: {}", keyManager);
    }

    try {
        KeyPair keyPair = keyManager.returnKeys(userAccount.getGuid());

        if (keyPair != null) {
            Cipher cipher = Cipher.getInstance(fileSecurityConfig.getEncryptionAlgorithm());
            cipher.init(Cipher.ENCRYPT_MODE, keyPair.getPrivate());

            if (DEBUG) {
                DEBUGGER.debug("Cipher: {}", cipher);
            }

            CipherOutputStream cipherOut = new CipherOutputStream(
                    new FileOutputStream(request.getEncryptedFile()), cipher);

            if (DEBUG) {
                DEBUGGER.debug("CipherOutputStream: {}", cipherOut);
            }

            byte[] data = IOUtils.toByteArray(new FileInputStream(request.getDecryptedFile()));
            IOUtils.write(data, cipherOut);

            cipherOut.flush();
            cipherOut.close();

            if ((request.getEncryptedFile().exists()) && (request.getEncryptedFile().length() != 0)) {
                response.setSignedFile(request.getEncryptedFile());
                response.setRequestStatus(SecurityRequestStatus.SUCCESS);
            } else {
                response.setRequestStatus(SecurityRequestStatus.FAILURE);
            }
        } else {
            response.setRequestStatus(SecurityRequestStatus.FAILURE);
        }
    } catch (IOException iox) {
        ERROR_RECORDER.error(iox.getMessage(), iox);

        throw new FileSecurityException(iox.getMessage(), iox);
    } catch (NoSuchAlgorithmException nsax) {
        ERROR_RECORDER.error(nsax.getMessage(), nsax);

        throw new FileSecurityException(nsax.getMessage(), nsax);
    } catch (NoSuchPaddingException nspx) {
        ERROR_RECORDER.error(nspx.getMessage(), nspx);

        throw new FileSecurityException(nspx.getMessage(), nspx);
    } catch (InvalidKeyException ikx) {
        ERROR_RECORDER.error(ikx.getMessage(), ikx);

        throw new FileSecurityException(ikx.getMessage(), ikx);
    } catch (KeyManagementException kmx) {
        ERROR_RECORDER.error(kmx.getMessage(), kmx);

        throw new FileSecurityException(kmx.getMessage(), kmx);
    } finally {
        // audit
        try {
            AuditEntry auditEntry = new AuditEntry();
            auditEntry.setHostInfo(reqInfo);
            auditEntry.setAuditType(AuditType.ENCRYPTFILE);
            auditEntry.setUserAccount(userAccount);
            auditEntry.setAuthorized(Boolean.TRUE);
            auditEntry.setApplicationId(request.getApplicationId());
            auditEntry.setApplicationName(request.getAppName());

            if (DEBUG) {
                DEBUGGER.debug("AuditEntry: {}", auditEntry);
            }

            AuditRequest auditRequest = new AuditRequest();
            auditRequest.setAuditEntry(auditEntry);

            if (DEBUG) {
                DEBUGGER.debug("AuditRequest: {}", auditRequest);
            }

            auditor.auditRequest(auditRequest);
        } catch (AuditServiceException asx) {
            ERROR_RECORDER.error(asx.getMessage(), asx);
        }
    }

    return response;
}

From source file:org.alfresco.extension.countersign.signature.RepositoryManagedSignatureProvider.java

/**
 * Create a keystore for this user to be used for document signing, store it associated with the user's
 * person node//from   w ww  .  j av a 2 s .c  o  m
 * 
 * @param person
 * @param password
 * 
 * @return a Java KeyStore object suitable for document signing
 * @throws NoSuchAlgorithmException 
 * @throws NoSuchProviderException 
 * @throws KeyStoreException 
 * @throws IOException 
 * @throws CertificateException 
 */
private KeyStore createUserKeyStore(NodeRef person, String password) throws NoSuchAlgorithmException,
        NoSuchProviderException, KeyStoreException, CertificateException, IOException {

    // get the alias from the configuration
    String alias = config.getProperty(RepositoryManagedSignatureProviderFactory.ALIAS);

    // initialize key generator
    KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
    SecureRandom random = SecureRandom.getInstance("SHA1PRNG", "SUN");
    keyGen.initialize(2048, random);

    // generate a keypair
    KeyPair pair = keyGen.generateKeyPair();
    PrivateKey priv = pair.getPrivate();
    PublicKey pub = pair.getPublic();

    // generate the user certificate
    Certificate cert = generateCertificate(pair, person);

    // get the ca cert used to sign and create cert chain
    KeyStore trustedKs = getTrustedKeyStore();
    Certificate[] caChain = getCaCertChain(trustedKs);
    Certificate[] certChain = new Certificate[caChain.length + 1];
    certChain[0] = cert;
    for (int i = 0; i < caChain.length; i++) {
        certChain[i + 1] = caChain[i];
    }

    // create keystore, adding private key and cert chain
    KeyStore ks = KeyStore.getInstance("pkcs12");
    ks.load(null, password.toCharArray());
    ks.setKeyEntry(alias, priv, password.toCharArray(), certChain);

    // save the keystore
    saveUserKeyStore(person, ks, password);

    // also save the public key separately, will need it 
    // for later validaiton activities
    saveUserPublicKey(person, pub);

    // return the generated keystore
    return ks;

}

From source file:dk.itst.oiosaml.sp.configuration.ConfigurationHandler.java

public void handlePost(RequestContext context) throws ServletException, IOException {
    HttpServletRequest request = context.getRequest();
    HttpServletResponse response = context.getResponse();

    if (!checkConfiguration(response))
        return;// w  w w  .  j  a  v a2 s . c o  m

    List<?> parameters = extractParameterList(request);

    String orgName = extractParameter("organisationName", parameters);
    String orgUrl = extractParameter("organisationUrl", parameters);
    String email = extractParameter("email", parameters);
    String entityId = extractParameter("entityId", parameters);
    final String password = extractParameter("keystorePassword", parameters);
    byte[] metadata = extractFile("metadata", parameters).get();
    FileItem ksData = extractFile("keystore", parameters);
    byte[] keystore = null;
    if (ksData != null) {
        keystore = ksData.get();
    }
    if (!checkNotNull(orgName, orgUrl, email, password, metadata, entityId) || metadata.length == 0
            || (keystore == null && !Boolean.valueOf(extractParameter("createkeystore", parameters)))) {
        Map<String, Object> params = getStandardParameters(request);
        params.put("error", "All fields must be filled.");
        params.put("organisationName", orgName);
        params.put("organisationUrl", orgUrl);
        params.put("email", email);
        params.put("keystorePassword", password);
        params.put("entityId", entityId);
        log.info("Parameters not correct: " + params);
        log.info("Metadata: " + new String(metadata));

        String res = renderTemplate("configure.vm", params, true);
        sendResponse(response, res);
        return;
    }

    Credential credential = context.getCredential();
    if (keystore != null && keystore.length > 0) {
        credential = CredentialRepository.createCredential(new ByteArrayInputStream(keystore), password);
    } else if (Boolean.valueOf(extractParameter("createkeystore", parameters))) {
        try {
            BasicX509Credential cred = new BasicX509Credential();
            KeyPair kp = dk.itst.oiosaml.security.SecurityHelper
                    .generateKeyPairFromURI("http://www.w3.org/2001/04/xmlenc#rsa-1_5", 1024);
            cred.setPrivateKey(kp.getPrivate());
            cred.setPublicKey(kp.getPublic());
            credential = cred;

            KeyStore ks = KeyStore.getInstance("JKS");
            ks.load(null, null);
            X509Certificate cert = dk.itst.oiosaml.security.SecurityHelper.generateCertificate(credential,
                    getEntityId(request));
            cred.setEntityCertificate(cert);

            ks.setKeyEntry("oiosaml", credential.getPrivateKey(), password.toCharArray(),
                    new Certificate[] { cert });
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            ks.store(bos, password.toCharArray());

            keystore = bos.toByteArray();
            bos.close();
        } catch (Exception e) {
            log.error("Unable to generate credential", e);
            throw new RuntimeException("Unable to generate credential", e);
        }
    }

    EntityDescriptor descriptor = generateSPDescriptor(getBaseUrl(request), entityId, credential, orgName,
            orgUrl, email, Boolean.valueOf(extractParameter("enableArtifact", parameters)),
            Boolean.valueOf(extractParameter("enablePost", parameters)),
            Boolean.valueOf(extractParameter("enableSoap", parameters)),
            Boolean.valueOf(extractParameter("enablePostSLO", parameters)),
            Boolean.valueOf(extractParameter("supportOCESAttributeProfile", parameters)));
    File zipFile = generateZipFile(request.getContextPath(), password, metadata, keystore, descriptor);

    byte[] configurationContents = saveConfigurationInSession(request, zipFile);
    boolean written = writeConfiguration(getHome(servletContext), configurationContents);

    Map<String, Object> params = new HashMap<String, Object>();
    params.put("home", getHome(servletContext));
    params.put("written", written);
    sendResponse(response, renderTemplate("done.vm", params, true));
}

From source file:com.schoentoon.connectbot.PubkeyListActivity.java

/**
 * @param name/*from  w  w  w. j a  v  a2  s.  c  o  m*/
 */
private void readKeyFromFile(File file) {
    PubkeyBean pubkey = new PubkeyBean();

    // find the exact file selected
    pubkey.setNickname(file.getName());

    if (file.length() > MAX_KEYFILE_SIZE) {
        Toast.makeText(PubkeyListActivity.this, R.string.pubkey_import_parse_problem, Toast.LENGTH_LONG).show();
        return;
    }

    // parse the actual key once to check if its encrypted
    // then save original file contents into our database
    try {
        byte[] raw = readRaw(file);

        String data = new String(raw);
        if (data.startsWith(PubkeyUtils.PKCS8_START)) {
            int start = data.indexOf(PubkeyUtils.PKCS8_START) + PubkeyUtils.PKCS8_START.length();
            int end = data.indexOf(PubkeyUtils.PKCS8_END);

            if (end > start) {
                char[] encoded = data.substring(start, end - 1).toCharArray();
                Log.d(TAG, "encoded: " + new String(encoded));
                byte[] decoded = Base64.decode(encoded);

                KeyPair kp = PubkeyUtils.recoverKeyPair(decoded);

                pubkey.setType(kp.getPrivate().getAlgorithm());
                pubkey.setPrivateKey(kp.getPrivate().getEncoded());
                pubkey.setPublicKey(kp.getPublic().getEncoded());
            } else {
                Log.e(TAG, "Problem parsing PKCS#8 file; corrupt?");
                Toast.makeText(PubkeyListActivity.this, R.string.pubkey_import_parse_problem, Toast.LENGTH_LONG)
                        .show();
            }
        } else {
            PEMStructure struct = PEMDecoder.parsePEM(new String(raw).toCharArray());
            pubkey.setEncrypted(PEMDecoder.isPEMEncrypted(struct));
            pubkey.setType(PubkeyDatabase.KEY_TYPE_IMPORTED);
            pubkey.setPrivateKey(raw);
        }

        // write new value into database
        if (pubkeydb == null)
            pubkeydb = new PubkeyDatabase(this);
        pubkeydb.savePubkey(pubkey);

        updateHandler.sendEmptyMessage(-1);
    } catch (Exception e) {
        Log.e(TAG, "Problem parsing imported private key", e);
        Toast.makeText(PubkeyListActivity.this, R.string.pubkey_import_parse_problem, Toast.LENGTH_LONG).show();
    }
}

From source file:org.ejbca.util.keystore.KeyStoreContainerBase.java

private byte[] generate(final KeyPairGenerator kpg, final String keyEntryName, final String sigAlgName)
        throws Exception {
    // We will make a loop to retry key generation here. Using the IAIK provider it seems to give
    // CKR_OBJECT_HANDLE_INVALID about every second time we try to store keys
    // But if we try again it succeeds
    int bar = 0;// ww w .jav  a  2 s . c  o  m
    while (bar < 3) {
        bar++;
        try {
            log.debug("generating...");
            final KeyPair keyPair = kpg.generateKeyPair();
            X509Certificate[] chain = new X509Certificate[1];
            chain[0] = getSelfCertificate("CN=some guy, L=around, C=US", (long) 30 * 24 * 60 * 60 * 365,
                    sigAlgName, keyPair);
            log.debug("Creating certificate with entry " + keyEntryName + '.');
            setKeyEntry(keyEntryName, keyPair.getPrivate(), chain);
            break; // success no need to try more
        } catch (KeyStoreException e) {
            log.info("Failed to generate or store new key, will try 3 times. This was try: " + bar, e);
        }
    }
    return storeKeyStore();
}

From source file:org.apache.hadoop.security.ssl.TestCRLValidator.java

@Test
public void testCRLValidatorFactory() throws Exception {
    Path truststore = Paths.get(BASE_DIR, "truststore.jks");
    Path crlPath = Paths.get(BASE_DIR, "crl.pem");

    // Generate CA keypair
    KeyPair keyPair = KeyStoreTestUtil.generateKeyPair(keyAlgorithm);
    X509Certificate cert = KeyStoreTestUtil.generateCertificate("CN=root", keyPair, 60, signatureAlgorithm);
    // Generate CA truststore
    KeyStoreTestUtil.createTrustStore(truststore.toString(), password, "root", cert);
    X509CRL crl = KeyStoreTestUtil.generateCRL(cert, keyPair.getPrivate(), signatureAlgorithm, null, null);
    writeCRLToFile(crl, crlPath);//from   ww w  . j  a va  2  s. co m

    conf.set(FileBasedKeyStoresFactory.resolvePropertyName(SSLFactory.Mode.SERVER,
            FileBasedKeyStoresFactory.SSL_TRUSTSTORE_LOCATION_TPL_KEY), truststore.toString());
    conf.set(FileBasedKeyStoresFactory.resolvePropertyName(SSLFactory.Mode.SERVER,
            FileBasedKeyStoresFactory.SSL_TRUSTSTORE_PASSWORD_TPL_KEY), password);
    conf.set(CommonConfigurationKeys.HOPS_CRL_OUTPUT_FILE_KEY, crlPath.toString());

    CRLValidator normalValidator1 = CRLValidatorFactory.getInstance()
            .getValidator(CRLValidatorFactory.TYPE.NORMAL, conf, conf);
    CRLValidator normalValidator2 = CRLValidatorFactory.getInstance()
            .getValidator(CRLValidatorFactory.TYPE.NORMAL, conf, conf);
    Assert.assertEquals(normalValidator1, normalValidator2);

    CRLValidator testingValidator1 = CRLValidatorFactory.getInstance()
            .getValidator(CRLValidatorFactory.TYPE.TESTING, conf, conf);
    CRLValidator testingValidator2 = CRLValidatorFactory.getInstance()
            .getValidator(CRLValidatorFactory.TYPE.TESTING, conf, conf);
    Assert.assertEquals(testingValidator1, testingValidator2);
    Assert.assertNotEquals(normalValidator1, testingValidator1);
}