List of usage examples for java.security KeyStore store
public final void store(OutputStream stream, char[] password) throws KeyStoreException, IOException, NoSuchAlgorithmException, CertificateException
From source file:org.texai.x509.X509Utils.java
/** Copies the given keystore from the .uber format to the .jceks format. * * @param uberKeyStorePath the .uber keystore path * @param uberKeyStorePassword the .uber keystore password * @param jceksKeyStorePath the .jceks keystore path * @param jceksKeyStorePassword the .jceks keystore password * @throws KeyStoreException if no Provider supports a KeyStoreSpi implementation for the specified type * @throws IOException if there is an I/O or format problem with the keystore data, * if a password is required but not given, or if the given password was incorrect * @throws NoSuchAlgorithmException if the algorithm used to check the integrity of the keystore cannot be found * @throws CertificateException if any of the certificates in the keystore could not be loaded * @throws NoSuchProviderException if the cryptography provider cannot be found * @throws UnrecoverableEntryException if the keystore entry cannot be recovered with the provided password and alias *///w ww .j a v a 2 s . c o m public static synchronized void copyKeyStoreUberToJceks(final String uberKeyStorePath, final char[] uberKeyStorePassword, final String jceksKeyStorePath, final char[] jceksKeyStorePassword) throws KeyStoreException, IOException, NoSuchAlgorithmException, CertificateException, NoSuchProviderException, UnrecoverableEntryException { //Preconditions assert uberKeyStorePath != null : "uberKeyStorePath must not be null"; assert !uberKeyStorePath.isEmpty() : "uberKeyStorePath must not be empty"; assert uberKeyStorePath.endsWith(".uber") : "uber keystore file extension must be .uber"; assert uberKeyStorePassword != null : "uberKeyStorePassword must not be null"; assert jceksKeyStorePath != null : "jceksKeyStorePath must not be null"; assert !jceksKeyStorePath.isEmpty() : "jceksKeyStorePath must not be empty"; assert jceksKeyStorePath.endsWith(".jceks") : "jceks keystore file extension must be .jceks"; assert uberKeyStorePassword != null : "uberKeyStorePassword must not be null"; LOGGER.info("copying keystore contents of " + uberKeyStorePath + " to " + jceksKeyStorePath); final KeyStore uberKeyStore = findOrCreateUberKeyStore(uberKeyStorePath, uberKeyStorePassword); final KeyStore jceksKeyStore = findOrCreateJceksKeyStore(jceksKeyStorePath, jceksKeyStorePassword); final Enumeration<String> aliases_enumeration = uberKeyStore.aliases(); final PasswordProtection uberPasswordProtection = new PasswordProtection(uberKeyStorePassword); final PasswordProtection jceksPasswordProtection = new PasswordProtection(jceksKeyStorePassword); while (aliases_enumeration.hasMoreElements()) { final String alias = aliases_enumeration.nextElement(); final KeyStore.Entry entry = uberKeyStore.getEntry(alias, uberPasswordProtection); assert entry != null; jceksKeyStore.setEntry(alias, entry, jceksPasswordProtection); LOGGER.info(" copied entry: " + alias); } jceksKeyStore.store(new FileOutputStream(jceksKeyStorePath), jceksKeyStorePassword); }
From source file:org.signserver.server.cryptotokens.KeystoreCryptoToken.java
@Override public void importCertificateChain(final List<Certificate> certChain, final String alias, final char[] authCode, final Map<String, Object> params, final IServices services) throws CryptoTokenOfflineException, IllegalArgumentException { if (certChain.size() < 1) { throw new IllegalArgumentException("Certificate chain can not be empty"); }/*from w w w . j a v a2 s . com*/ try { final KeyStore keyStore = getKeyStore(); final Key key = keyStore.getKey(alias, authCode != null ? authCode : authenticationCode); CryptoTokenHelper.ensureNewPublicKeyMatchesOld(keyStore, alias, certChain.get(0)); keyStore.setKeyEntry(alias, key, authCode != null ? authCode : authenticationCode, certChain.toArray(new Certificate[0])); // persist keystore OutputStream out = null; if (!TYPE_INTERNAL.equalsIgnoreCase(keystoretype)) { out = new FileOutputStream(new File(keystorepath)); } else { // use internal worker data out = new ByteArrayOutputStream(); } keyStore.store(out, authenticationCode); if (TYPE_INTERNAL.equalsIgnoreCase(keystoretype)) { final byte[] data = ((ByteArrayOutputStream) out).toByteArray(); getWorkerSession().setKeystoreData(new AdminInfo("Internal", null, null), this.workerId, data); } // update in-memory representation KeyEntry entry = getKeyEntry(alias); final Certificate signingCert = certChain.get(0); if (entry == null) { entry = new KeyEntry(); } entry.setCertificate(signingCert); entry.setCertificateChain(certChain); } catch (Exception e) { throw new CryptoTokenOfflineException(e); } }
From source file:edu.vt.middleware.crypt.KeyStoreCli.java
/** * Imports a certificate or key pair into the keystore. * * @param line Parsed command line arguments container. * * @throws Exception On errors./*w w w . j a va 2 s .c om*/ */ protected void doImport(final CommandLine line) throws Exception { validateOptions(line); final KeyStore store = readKeyStore(line); final String alias = line.getOptionValue(OPT_ALIAS); final File certFile = new File(line.getOptionValue(OPT_CERT)); if (line.hasOption(OPT_KEY)) { final File keyFile = new File(line.getOptionValue(OPT_KEY)); final char[] passChars = line.getOptionValue(OPT_PASS).toCharArray(); final PrivateKey key = CryptReader.readPrivateKey(keyFile); final Certificate[] chain = CryptReader.readCertificateChain(certFile); System.err.println("Read certificate chain of length " + chain.length + ":"); for (int i = 0; i < chain.length; i++) { System.out.println("===== Certificate [" + i + "] ====="); printCertificate(chain[i]); } store.setKeyEntry(alias, key, passChars, chain); System.err.println("Imported key entry " + alias); } else { final Certificate cert = CryptReader.readCertificate(certFile); System.err.println("Read certificate:"); printCertificate(cert); store.setCertificateEntry(alias, cert); System.err.println("Imported trusted cert entry " + alias); } final OutputStream os = new FileOutputStream(new File(line.getOptionValue(OPT_STORE))); try { store.store(os, line.getOptionValue(OPT_PASS).toCharArray()); } finally { os.close(); } }
From source file:org.signserver.server.log.SystemLoggingTest.java
@Test public void test01LogKeyGenAndTestAndCSR_separateToken() throws Exception { LOG.info(">test01LogKeyGenAndTestAndCSR_separateToken"); final int workerId = 5881; final String tokenName = "TestKeyGenAndCSR2"; final int p12SignerId = 5880; try {// w w w . java 2s .c o m // Copy sample P12 to a temporary P12 File sampleP12 = new File(getSignServerHome(), "res/test/dss10/dss10_signer3.p12"); File p12 = File.createTempFile("testkeystore", "tmp"); p12.deleteOnExit(); KeyStore keystore = KeyStore.getInstance("PKCS12", "BC"); FileInputStream fin = null; FileOutputStream fout = null; try { fin = new FileInputStream(sampleP12); fout = new FileOutputStream(p12); keystore.load(fin, "foo123".toCharArray()); keystore.store(fout, "foo123".toCharArray()); } finally { if (fin != null) { try { fin.close(); } catch (IOException ignored) { } // NOPMD } if (fout != null) { try { fout.close(); } catch (IOException ignored) { } // NOPMD } } // Add crypto worker using the P12 addP12DummySigner(p12SignerId, tokenName, p12, "foo123", null); // Add a separate worker getGlobalSession().setProperty(GlobalConfiguration.SCOPE_GLOBAL, "WORKER" + workerId + ".CLASSPATH", PlainSigner.class.getName()); getWorkerSession().setWorkerProperty(workerId, "NAME", "TheWorker" + workerId); getWorkerSession().setWorkerProperty(workerId, "AUTHTYPE", IProcessable.AUTHTYPE_NOAUTH); getWorkerSession().setWorkerProperty(workerId, "CRYPTOTOKEN", tokenName); getWorkerSession().reloadConfiguration(workerId); // Test keygen int linesBefore = readEntriesCount(auditLogFile); workerSession.generateSignerKey(workerId, "RSA", "512", "ts_key00004", "foo123".toCharArray()); workerSession.generateSignerKey(workerId, "RSA", "512", "additionalKey", "foo123".toCharArray()); List<String> lines = readEntries(auditLogFile, linesBefore, 1); LOG.info(lines); String line = lines.get(0); assertTrue("Contains event", line.contains("EVENT: KEYGEN")); assertTrue("Contains module", line.contains("MODULE: KEY_MANAGEMENT")); assertTrue("Contains worker id", line.contains("WORKER_ID: " + workerId)); assertTrue("Contains key alias", line.contains("KEYALIAS: ts_key00004")); assertTrue("Contains spec", line.contains("KEYSPEC: 512")); assertTrue("Contains alg", line.contains("KEYALG: RSA")); assertTrue("Contains crypto token", line.contains("CRYPTOTOKEN: " + tokenName)); // Test keytest workerSession.activateSigner(workerId, "foo123"); workerSession.testKey(workerId, "ts_key00004", "foo123".toCharArray()); lines = readEntries(auditLogFile, linesBefore + 2, 1); LOG.info(lines); line = lines.get(0); assertTrue("Contains event", line.contains("EVENT: KEYTEST")); assertTrue("Contains module", line.contains("MODULE: KEY_MANAGEMENT")); assertTrue("Contains worker id", line.contains("WORKER_ID: " + workerId)); assertTrue("Contains key alias", line.contains("KEYALIAS: ts_key00004")); assertTrue("Contains crypto token", line.contains("CRYPTOTOKEN: " + tokenName)); assertTrue("Contains test results", line.contains("KeyTestResult{alias=ts_key00004, success=true")); // Test key with all, to assure not extra base 64 encoding is done workerSession.testKey(workerId, "all", "foo123".toCharArray()); lines = readEntries(auditLogFile, linesBefore + 3, 1); LOG.info(lines); line = lines.get(0); assertTrue("Contains test results", line.contains("KeyTestResult{alias=ts_key00004, success=true")); // Test gencsr PKCS10CertReqInfo certReqInfo = new PKCS10CertReqInfo("SHA1WithRSA", "CN=TS Signer 1,C=SE", null); ICertReqData req = workerSession.getCertificateRequest(workerId, certReqInfo, false, "ts_key00004"); Base64SignerCertReqData reqData = (Base64SignerCertReqData) req; lines = readEntries(auditLogFile, linesBefore + 4, 1); LOG.info(lines); line = lines.get(0); assertTrue("Contains event", line.contains("EVENT: GENCSR")); assertTrue("Contains module", line.contains("MODULE: KEY_MANAGEMENT")); assertTrue("Contains worker id", line.contains("WORKER_ID: " + workerId)); assertTrue("Contains crypto token", line.contains("CRYPTOTOKEN: " + tokenName)); assertTrue("Contains key alias", line.contains("KEYALIAS: ts_key00004")); assertTrue("Contains for default key: " + line, line.contains("FOR_DEFAULTKEY: false")); assertTrue("Contains csr", line.contains("CSR: " + new String(reqData.getBase64CertReq()))); // Test remove key workerSession.removeKey(workerId, "ts_key00004"); lines = readEntries(auditLogFile, linesBefore + 5, 1); LOG.info(lines); line = lines.get(0); assertTrue("Contains event", line.contains("EVENT: KEYREMOVE")); assertTrue("Contains module", line.contains("MODULE: KEY_MANAGEMENT")); assertTrue("Contains worker id", line.contains("WORKER_ID: " + workerId)); assertTrue("Contains crypto token", line.contains("CRYPTOTOKEN: " + tokenName)); assertTrue("Contains key alias: " + line, line.contains("KEYALIAS: ts_key00004")); } finally { removeWorker(workerId); removeWorker(p12SignerId); } }
From source file:org.signserver.server.log.SystemLoggingTest.java
@Test public void test01LogKeyGenAndTestAndCSR() throws Exception { LOG.info(">test01LogKeyGenAndTestAndCSR"); final String signerName = "TestKeyGenAndCSR1"; final int p12SignerId = 5980; try {/*from w w w. j a v a 2 s .com*/ // Copy sample P12 to a temporary P12 File sampleP12 = new File(getSignServerHome(), "res/test/dss10/dss10_signer3.p12"); final String keyInKeystore = "Signer 3"; File p12 = File.createTempFile("testkeystore", "tmp"); p12.deleteOnExit(); KeyStore keystore = KeyStore.getInstance("PKCS12", "BC"); FileInputStream fin = null; FileOutputStream fout = null; try { fin = new FileInputStream(sampleP12); fout = new FileOutputStream(p12); keystore.load(fin, "foo123".toCharArray()); keystore.store(fout, "foo123".toCharArray()); } finally { if (fin != null) { try { fin.close(); } catch (IOException ignored) { } // NOPMD } if (fout != null) { try { fout.close(); } catch (IOException ignored) { } // NOPMD } } // Add signer using the P12 addP12DummySigner(p12SignerId, signerName, p12, "foo123", keyInKeystore); // Test keygen int linesBefore = readEntriesCount(auditLogFile); workerSession.generateSignerKey(p12SignerId, "RSA", "512", "ts_key00004", "foo123".toCharArray()); workerSession.generateSignerKey(p12SignerId, "RSA", "512", "additionalKey", "foo123".toCharArray()); List<String> lines = readEntries(auditLogFile, linesBefore, 1); LOG.info(lines); String line = lines.get(0); assertTrue("Contains event", line.contains("EVENT: KEYGEN")); assertTrue("Contains module", line.contains("MODULE: KEY_MANAGEMENT")); assertTrue("Contains worker id", line.contains("WORKER_ID: " + p12SignerId)); assertTrue("Contains alias", line.contains("KEYALIAS: ts_key00004")); assertTrue("Contains spec", line.contains("KEYSPEC: 512")); assertTrue("Contains alg", line.contains("KEYALG: RSA")); assertTrue("Contains crypto token", line.contains("CRYPTOTOKEN: " + signerName)); // Test keytest workerSession.activateSigner(p12SignerId, "foo123"); workerSession.testKey(p12SignerId, "ts_key00004", "foo123".toCharArray()); lines = readEntries(auditLogFile, linesBefore + 2, 1); LOG.info(lines); line = lines.get(0); assertTrue("Contains event", line.contains("EVENT: KEYTEST")); assertTrue("Contains module", line.contains("MODULE: KEY_MANAGEMENT")); assertTrue("Contains worker id", line.contains("WORKER_ID: " + p12SignerId)); assertTrue("Contains key alias", line.contains("KEYALIAS: ts_key00004")); assertTrue("Contains crypto token", line.contains("CRYPTOTOKEN: " + signerName)); assertTrue("Contains test results", line.contains("KeyTestResult{alias=ts_key00004, success=true")); // Test key with all, to assure not extra base 64 encoding is done workerSession.testKey(p12SignerId, "all", "foo123".toCharArray()); lines = readEntries(auditLogFile, linesBefore + 3, 1); LOG.info(lines); line = lines.get(0); assertTrue("Contains test results", line.contains("KeyTestResult{alias=ts_key00004, success=true")); // Test gencsr PKCS10CertReqInfo certReqInfo = new PKCS10CertReqInfo("SHA1WithRSA", "CN=TS Signer 1,C=SE", null); ICertReqData req = workerSession.getCertificateRequest(p12SignerId, certReqInfo, false); Base64SignerCertReqData reqData = (Base64SignerCertReqData) req; lines = readEntries(auditLogFile, linesBefore + 4, 1); LOG.info(lines); line = lines.get(0); assertTrue("Contains event", line.contains("EVENT: GENCSR")); assertTrue("Contains module", line.contains("MODULE: KEY_MANAGEMENT")); assertTrue("Contains worker id", line.contains("WORKER_ID: " + p12SignerId)); assertTrue("Contains crypto token", line.contains("CRYPTOTOKEN: " + signerName)); assertTrue("Contains key alias: " + line, line.contains("KEYALIAS: " + keyInKeystore)); assertTrue("Contains for default key: " + line, line.contains("FOR_DEFAULTKEY: true")); assertTrue("Contains csr", line.contains("CSR: " + new String(reqData.getBase64CertReq()))); // Test gencsr req = workerSession.getCertificateRequest(p12SignerId, certReqInfo, false, "ts_key00004"); reqData = (Base64SignerCertReqData) req; lines = readEntries(auditLogFile, linesBefore + 5, 1); LOG.info(lines); line = lines.get(0); assertTrue("Contains event", line.contains("EVENT: GENCSR")); assertTrue("Contains module", line.contains("MODULE: KEY_MANAGEMENT")); assertTrue("Contains worker id", line.contains("WORKER_ID: " + p12SignerId)); assertTrue("Contains crypto token", line.contains("CRYPTOTOKEN: " + signerName)); assertTrue("Contains key alias: " + line, line.contains("KEYALIAS: ts_key00004")); assertTrue("Contains for default key: " + line, line.contains("FOR_DEFAULTKEY: false")); assertTrue("Contains csr", line.contains("CSR: " + new String(reqData.getBase64CertReq()))); // Test remove key workerSession.removeKey(p12SignerId, "ts_key00004"); lines = readEntries(auditLogFile, linesBefore + 6, 1); LOG.info(lines); line = lines.get(0); assertTrue("Contains event", line.contains("EVENT: KEYREMOVE")); assertTrue("Contains module", line.contains("MODULE: KEY_MANAGEMENT")); assertTrue("Contains worker id", line.contains("WORKER_ID: " + p12SignerId)); assertTrue("Contains crypto token", line.contains("CRYPTOTOKEN: " + signerName)); assertTrue("Contains key alias: " + line, line.contains("KEYALIAS: ts_key00004")); } finally { removeWorker(p12SignerId); } }
From source file:gov.nih.nci.cacisweb.action.SecureFTPAddAction.java
@Override public String execute() throws Exception { log.debug("execute() - START"); String secureFTPPropertyFileLocation = CaCISUtil .getProperty(CaCISWebConstants.COM_PROPERTY_NAME_SECFTP_PROPERTIES_FILE_LOCATION); String secureFTPKeystoreLocation = CaCISUtil.getPropertyFromPropertiesFile(secureFTPPropertyFileLocation, CaCISUtil.getProperty(CaCISWebConstants.COM_PROPERTY_NAME_SECFTP_TRUSTSTORE_LOCATION_PROP_NAME)); String secureFTPKeystorePassword = CaCISUtil.getPropertyFromPropertiesFile(secureFTPPropertyFileLocation, CaCISUtil.getProperty(CaCISWebConstants.COM_PROPERTY_NAME_SECFTP_TRUSTSTORE_PASSWORD_PROP_NAME)); try {/* w w w.j a v a 2s. c om*/ CaCISUtil caCISUtil = new CaCISUtil(); KeyStore keystore = caCISUtil.getKeystore(secureFTPKeystoreLocation, CaCISWebConstants.COM_KEYSTORE_TYPE_JKS, secureFTPKeystorePassword); if (keystore.containsAlias(secureFTPBean.getCertificateAlias())) { log.error(getText("secureFTPBean.duplicateKey")); addFieldError("secureFTPBean.certificateAlias", getText("secureFTPBean.duplicateKey")); } if (StringUtils.contains(secureFTPBean.getCertificateAlias(), "ftps")) { if (StringUtils.isBlank(secureFTPBean.getCertificateFileName())) { log.error(getText("secureFTPBean.certificateRequired")); addFieldError("secureFTPBean.certificateFileName", getText("secureFTPBean.certificateRequired")); caCISUtil.releaseKeystore(); return INPUT; } else { caCISUtil.releaseKeystore(); FileInputStream certificateStream = new FileInputStream(secureFTPBean.getCertificate()); CertificateFactory cf = CertificateFactory.getInstance("X.509"); java.security.cert.Certificate cert = cf.generateCertificate(certificateStream); // Add the certificate keystore.setCertificateEntry(secureFTPBean.getCertificateAlias(), cert); // Save the new keystore contents FileOutputStream out = new FileOutputStream(new File(secureFTPKeystoreLocation)); keystore.store(out, secureFTPKeystorePassword.toCharArray()); out.close(); } } // add the new entry to FTP configuration properties file PropertiesConfiguration config = new PropertiesConfiguration( CaCISUtil.getProperty(CaCISWebConstants.COM_PROPERTY_NAME_SECFTP_CONFIG_FILE_LOCATION)); config.setProperty(secureFTPBean.getCertificateAlias(), ""); config.save(); } catch (KeystoreInstantiationException kie) { log.error(kie.getMessage()); addActionError(getText("exception.keystoreInstantiation")); return ERROR; } catch (CertificateException ce) { log.error(CaCISUtil.getStackTrace(ce)); addActionError(getText("exception.certification")); return INPUT; } addActionMessage(getText("secureFTPBean.addCertificateSuccessful")); log.debug("execute() - END"); return SUCCESS; }
From source file:org.oscarehr.sharingcenter.actions.SecurityInfrastructureServlet.java
private String importCertificates(Integer infrastructureId, InputStream inputStream) { String status = "fail"; OscarProperties oscarProperties = OscarProperties.getInstance(); String keyStoreFile = oscarProperties.getProperty("TOMCAT_KEYSTORE_FILE"); String trustStoreFile = oscarProperties.getProperty("TOMCAT_TRUSTSTORE_FILE"); String keyStorePass = oscarProperties.getProperty("TOMCAT_KEYSTORE_PASSWORD"); String trustStorePass = oscarProperties.getProperty("TOMCAT_TRUSTSTORE_PASSWORD"); InfrastructureDao dao = SpringUtils.getBean(InfrastructureDao.class); InfrastructureDataObject infrastructure = dao.getInfrastructure(infrastructureId); String alias = infrastructure.getAlias(); PrivateKey privateKey = null; KeyStore ks = null; KeyStore ts = null;/*w ww . j a v a 2 s .co m*/ try { //acquiring the private key Base64 base64 = new Base64(); byte[] privKey = base64.decode(infrastructure.getBase64EncodedPrivateKey()); privateKey = KeyFactory.getInstance("RSA").generatePrivate(new PKCS8EncodedKeySpec(privKey)); ks = SslUtility.loadKeyStore(keyStoreFile, keyStorePass.toCharArray()); ts = SslUtility.loadKeyStore(trustStoreFile, trustStorePass.toCharArray()); } catch (SslException ex) { LOGGER.info(ex); } catch (InvalidKeySpecException ex) { LOGGER.info(ex); } catch (NoSuchAlgorithmException ex) { LOGGER.info(ex); } if (ks != null && ts != null && privateKey != null) { // import certificates to keystore and truststore try { // extract certificates ArrayList<X509Certificate> certificates = SslUtility.extractX509Certificates(inputStream); // get the private key and add certificate chain X509Certificate[] chain = new X509Certificate[2]; ks.setKeyEntry(alias, privateKey, keyStorePass.toCharArray(), certificates.toArray(chain)); // save the keystore ks.store(new FileOutputStream(keyStoreFile), keyStorePass.toCharArray()); // add root CA certificate truststore ArrayList<X509Certificate> caCerts = SslUtility.retrieveCACertificates(certificates); for (X509Certificate x509Certificate : caCerts) { ts.setCertificateEntry(alias, x509Certificate); } // save the truststore ts.store(new FileOutputStream(trustStoreFile), trustStorePass.toCharArray()); status = "import"; } catch (NoSuchAlgorithmException ex) { LOGGER.info(ex); } catch (CertificateException ex) { LOGGER.info(ex); } catch (KeyStoreException ex) { LOGGER.info(ex); } catch (IOException ex) { LOGGER.info(ex); } catch (SslException ex) { LOGGER.info(ex); } } else { LOGGER.debug("Bad data. Keystore/Truststore/PrivateKey might be null"); } return status; }
From source file:it.geosolutions.sfs.web.Start.java
private static void assureSelfSignedServerCertificate(String hostname, File keyStoreFile, String password) throws Exception { KeyStore privateKS = KeyStore.getInstance("JKS"); if (keyStoreFile.exists()) { FileInputStream fis = new FileInputStream(keyStoreFile); privateKS.load(fis, password.toCharArray()); if (keyStoreContainsCertificate(privateKS, hostname)) return; } else {/*from w w w.j av a 2 s.com*/ privateKS.load(null); } // create a RSA key pair generator using 1024 bits KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA"); keyPairGenerator.initialize(1024); KeyPair KPair = keyPairGenerator.generateKeyPair(); // cerate a X509 certifacte generator // X509V3CertificateGenerator v3CertGen = new X509V3CertificateGenerator(); // set validity to 10 years, issuer and subject are equal --> self singed certificate int random = new SecureRandom().nextInt(); if (random < 0) random *= -1; // v3CertGen.setSerialNumber(BigInteger.valueOf(random)); // v3CertGen.setIssuerDN(new X509Principal("CN=" + hostname + ", OU=None, O=None L=None, C=None")); // v3CertGen.setNotBefore(new Date(System.currentTimeMillis() - 1000L * 60 * 60 * 24 * 30)); // v3CertGen.setNotAfter(new Date(System.currentTimeMillis() + (1000L * 60 * 60 * 24 * 365*10))); // v3CertGen.setSubjectDN(new X509Principal("CN=" + hostname + ", OU=None, O=None L=None, C=None")); // // v3CertGen.setPublicKey(KPair.getPublic()); // v3CertGen.setSignatureAlgorithm("MD5WithRSAEncryption"); // // X509Certificate PKCertificate = v3CertGen.generateX509Certificate(KPair.getPrivate()); // // store the certificate containing the public key,this file is needed // to import the public key in other key store. File certFile = new File(keyStoreFile.getParentFile(), hostname + ".cert"); FileOutputStream fos = new FileOutputStream(certFile.getAbsoluteFile()); // fos.write(PKCertificate.getEncoded()); fos.close(); // privateKS.setKeyEntry(hostname+".key", KPair.getPrivate(), // password.toCharArray(), // new java.security.cert.Certificate[]{PKCertificate}); // // privateKS.setCertificateEntry(hostname+".cert",PKCertificate); privateKS.store(new FileOutputStream(keyStoreFile), password.toCharArray()); }
From source file:org.alfresco.extension.countersign.signature.RepositoryManagedSignatureProvider.java
/** * Save the Java KeyStore, associated as a child with the person that owns this keystore * // w w w. ja va 2s.c o m * @param person * @param keystore * @throws IOException * @throws CertificateException * @throws NoSuchAlgorithmException * @throws KeyStoreException */ private void saveUserKeyStore(NodeRef person, KeyStore keystore, String password) throws KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException { NodeRef keystoreNode = counterSignService.getSignatureArtifact(person, CounterSignSignatureModel.ASSOC_SIGNERKEYSTORE); if (keystoreNode == null) { QName assocQName = QName.createQName(CounterSignSignatureModel.COUNTERSIGN_SIGNATURE_MODEL_1_0_URI, QName.createValidLocalName(user + "-signaturekeystore")); ChildAssociationRef keyChildRef = serviceRegistry.getNodeService().createNode(person, CounterSignSignatureModel.ASSOC_SIGNERKEYSTORE, assocQName, CounterSignSignatureModel.TYPE_PKCS12); keystoreNode = keyChildRef.getChildRef(); } // get a writer, store the user keystore ContentWriter writer = serviceRegistry.getContentService().getWriter(keystoreNode, ContentModel.PROP_CONTENT, true); ByteArrayOutputStream baos = new ByteArrayOutputStream(); keystore.store(baos, password.toCharArray()); writer.putContent(new ByteArrayInputStream(baos.toByteArray())); // now set the permissions on this node so that only the person that owns it // can access it. PermissionService.ALL_AUTHORITIES = GROUP_EVERYONE // this should leave the owner permissions intact PermissionService ps = serviceRegistry.getPermissionService(); ps.clearPermission(keystoreNode, PermissionService.ALL_AUTHORITIES); ps.setInheritParentPermissions(keystoreNode, false); }