public void loadPfx(InputStream is, String password) throws NoSuchAlgorithmException, CertificateException, IOException, KeyStoreException, UnrecoverableEntryException { char[] pwd = password.toCharArray(); KeyStore keyStore = KeyStore.getInstance("pkcs12"); keyStore.load(is, pwd); PasswordProtection passwordProtection = new KeyStore.PasswordProtection(pwd); for (Enumeration<String> aliases = keyStore.aliases(); aliases.hasMoreElements();) { String alias = aliases.nextElement(); KeyStore.PrivateKeyEntry entry = (KeyStore.PrivateKeyEntry) keyStore.getEntry(alias, passwordProtection); Certificate cert = entry.getCertificate(); if (cert.getType().equals("X.509")) { this.certificate = (X509Certificate) cert; this.privateKey = entry.getPrivateKey(); return; } } throw new RuntimeException("Certificate of type X.509 was not found."); }
public String decrypt(final String alias, final byte[] encryptedData, Context appContext) throws UnrecoverableEntryException, NoSuchAlgorithmException, KeyStoreException, NoSuchProviderException, NoSuchPaddingException, InvalidKeyException, IOException, BadPaddingException, IllegalBlockSizeException, InvalidAlgorithmParameterException { final Cipher cipher = Cipher.getInstance(TRANSFORMATION); String IV = PreferenceHelper.getPrefernceHelperInstace().getString(appContext, "IV", ""); if (null != IV && !IV.isEmpty()) { byte[] encryptionIv = Base64.decode(IV, Base64.DEFAULT); Log.e("Decrypter", "IV : " + IV + " IV size " + encryptionIv.length); final GCMParameterSpec spec = new GCMParameterSpec(128, encryptionIv); cipher.init(Cipher.DECRYPT_MODE, getSecretKey(alias), spec); return new String(cipher.doFinal(encryptedData), "UTF-8"); } else { return "{}"; } }
public byte[] encrypt(final String alias, final String textToEncrypt, Context appContext) throws UnrecoverableEntryException, NoSuchAlgorithmException, KeyStoreException, NoSuchProviderException, NoSuchPaddingException, InvalidKeyException, IOException, InvalidAlgorithmParameterException, SignatureException, BadPaddingException, IllegalBlockSizeException { final Cipher cipher = Cipher.getInstance(TRANSFORMATION); cipher.init(Cipher.ENCRYPT_MODE, getSecretKey(alias)); String IV = Base64.encodeToString(cipher.getIV(), Base64.DEFAULT); Log.e("MILK", "IV : " + IV + " IV size " + IV.length()); PreferenceHelper.getPrefernceHelperInstace().setString(appContext, "IV", IV); // // iv = cipher.getIV(); return (/*encryption = */cipher.doFinal(textToEncrypt.getBytes("UTF-8"))); }
public void printAliasesList(String keyPasswd) { try { System.out.println("trustStoreType=" + trustStore.getType()); System.out.println("size=" + trustStore.size()); // --- Get All TrustStore's Certificates Alias ----------- Enumeration<String> enumeration = trustStore.aliases(); while (enumeration.hasMoreElements()) { String alias = enumeration.nextElement(); System.out.println("alias=" + alias); // Entry entry = trustStore.getEntry(alias, null); Entry entry = trustStore.getEntry(alias, new PasswordProtection(keyPasswd.toCharArray())); System.out.println("entryClass=" + entry.getClass()); } } catch (KeyStoreException | NoSuchAlgorithmException | UnrecoverableEntryException e) { e.printStackTrace(); } }
@TargetApi(Build.VERSION_CODES.M) public SecretKey getSymmetricKey(String alias) throws NoSuchProviderException, NoSuchAlgorithmException, InvalidAlgorithmParameterException, IOException, CertificateException, KeyStoreException, UnrecoverableEntryException { ESLog.v("%s=>getSymmetricKey(%s)", getClass().getSimpleName(), alias); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { KeyStore ks = KeyStore.getInstance(KEYSTORE_PROVIDER); ks.load(null); Key key = ks.getKey(alias, null); if (key != null) { ESLog.i("SecretKey found in KeyStore."); return (SecretKey) key; } ESLog.w("SecretKey not found in KeyStore."); return null; } UnsupportedOperationException unsupportedOperationException = new UnsupportedOperationException(); ESLog.wtf("Unsupported operation. This code should be called only from M onwards.", unsupportedOperationException.getCause()); throw unsupportedOperationException; }
/** * Gets the secret key stored in keystore under given alias. * @param alias * @param entryPassword entry password to access the secret key stored in keystore * @return the secret key or null if secret key does not exists in keystore * @throws KeyStoreProviderException */ public SecretKey getSecretKey(String alias, String entryPassword) throws KeyStoreProviderException { try { LOG.info(String.format("Getting secret key with alias %s from keystore ...", alias)); Optional<KeyStore.SecretKeyEntry> entry = Optional.fromNullable((KeyStore.SecretKeyEntry)this.keystore.getEntry(alias, new KeyStore.PasswordProtection(entryPassword.toCharArray()))); if (!entry.isPresent()) { return null; } return entry.get().getSecretKey(); } catch (NoSuchAlgorithmException nsae) { throw new KeyStoreProviderException("Algorithm for recovering the secret key cannot be found.", nsae); } catch (UnrecoverableEntryException uee) { throw new KeyStoreProviderException("Invalid entry password to recover secret.", uee); } catch (KeyStoreException kse) { throw new KeyStoreProviderException("Failed to get secret key entry.", kse); } catch (Exception e) { throw new KeyStoreProviderException("Failed to get secret key.", e); } }
private void checkAttrs() throws UnrecoverableEntryException, GeneralSecurityException, NoSuchAlgorithmException, KeyStoreException, IOException { KeyStore ks = Utils.loadKeyStore(WORKING_DIRECTORY + File.separator + KESTORE_NEW, Utils.KeyStoreType.pkcs12, PASSWORD); KeyStore.Entry keyStoreEntry = ks.getEntry(ALIAS, new KeyStore.PasswordProtection(KEY_PASSWORD)); out.println("Attributes after store:"); //print attribute values keyStoreEntry.getAttributes().stream().forEach((attr) -> { out.println(attr.getName() + ", '" + attr.getValue() + "'"); }); Arrays.stream(ATTR_SET).forEach((attr) -> { if (!keyStoreEntry.getAttributes().contains(attr)) { throw new RuntimeException("Entry doesn't contain attribute: (" + attr.getName() + ", '" + attr.getValue() + "')"); } }); }
private void storeAttrs() throws UnrecoverableEntryException, GeneralSecurityException, NoSuchAlgorithmException, KeyStoreException, IOException { KeyStore ksIn = Utils.loadKeyStore(KEYSTORE_PATH, Utils.KeyStoreType.pkcs12, PASSWORD); KeyStore ksAttr = KeyStore .getInstance(Utils.KeyStoreType.pkcs12.name()); ksAttr.load(null); Key key = ksIn.getKey(ALIAS, PASSWORD); Certificate cert = ksIn.getCertificate(ALIAS); Set<KeyStore.Entry.Attribute> attrs = new HashSet<>(Arrays.asList(ATTR_SET)); KeyStore.Entry e = new KeyStore.PrivateKeyEntry((PrivateKey) key, new Certificate[]{cert}, attrs); ksAttr.setEntry(ALIAS, e, new KeyStore.PasswordProtection( KEY_PASSWORD)); out.println("Attributes before store:"); e.getAttributes().stream().forEach((attr) -> { out.println(attr.getName() + ", '" + attr.getValue() + "'"); }); Utils.saveKeyStore(ksAttr, WORKING_DIRECTORY + File.separator + KESTORE_NEW, PASSWORD); }
private byte[] buildAssertion() throws IOException, NoSuchAlgorithmException, NoSuchProviderException, InvalidAlgorithmParameterException, UnrecoverableEntryException, KeyStoreException, InvalidKeyException, SignatureException { ByteArrayOutputStream byteout = new ByteArrayOutputStream(); byte[] value; int length; byteout.write(UnsignedUtil.encodeInt(TagsEnum.TAG_UAFV1_REG_ASSERTION.id)); value = regAssertion(); length = value.length; byteout.write(UnsignedUtil.encodeInt(length)); byteout.write(value); return byteout.toByteArray(); }
private byte[] regAssertion() throws IOException, NoSuchAlgorithmException, NoSuchProviderException, InvalidAlgorithmParameterException, UnrecoverableEntryException, KeyStoreException, InvalidKeyException, SignatureException { ByteArrayOutputStream byteout = new ByteArrayOutputStream(); byte[] value; int length; byteout.write(UnsignedUtil.encodeInt(TagsEnum.TAG_UAFV1_KRD.id)); value = buildKRD(); length = value.length; byteout.write(UnsignedUtil.encodeInt(length)); byteout.write(value); byte[] dataToSign = byteout.toByteArray(); byteout.write(UnsignedUtil.encodeInt(TagsEnum.TAG_ATTESTATION_BASIC_FULL.id)); value = buildBasicFullAttestation(dataToSign); length = value.length; byteout.write(UnsignedUtil.encodeInt(length)); byteout.write(value); return byteout.toByteArray(); }
private byte[] buildBasicFullAttestation(byte[] data) throws IOException, NoSuchAlgorithmException, UnrecoverableEntryException, KeyStoreException, InvalidKeyException, SignatureException { ByteArrayOutputStream byteout = new ByteArrayOutputStream(); byte[] value; int length; byteout.write(UnsignedUtil.encodeInt(TagsEnum.TAG_SIGNATURE.id)); value = getSignature(data); length = value.length; byteout.write(UnsignedUtil.encodeInt(length)); byteout.write(value); byteout.write(UnsignedUtil.encodeInt(TagsEnum.TAG_ATTESTATION_CERT.id)); value = Base64.decode(Authenticator.base64DERCert, Base64.URL_SAFE); length = value.length; byteout.write(UnsignedUtil.encodeInt(length)); byteout.write(value); return byteout.toByteArray(); }
private byte[] getSignResponse() throws IOException, KeyStoreException, NoSuchAlgorithmException, UnrecoverableEntryException, InvalidKeyException, SignatureException { ByteArrayOutputStream byteout = new ByteArrayOutputStream(); byte[] value; int length; byteout.write(UnsignedUtil.encodeInt(TagsEnum.TAG_UAFV1_SIGN_CMD_RESPONSE.id)); value = buildSignResponse(); length = value.length; byteout.write(UnsignedUtil.encodeInt(length)); byteout.write(value); return byteout.toByteArray(); }
private byte[] authAssertion() throws IOException, KeyStoreException, NoSuchAlgorithmException, UnrecoverableEntryException, InvalidKeyException, SignatureException { ByteArrayOutputStream byteout = new ByteArrayOutputStream(); byte[] value; int length; byteout.write(UnsignedUtil.encodeInt(TagsEnum.TAG_UAFV1_AUTH_ASSERTION.id)); value = buildAuthAssertion(); length = value.length; byteout.write(UnsignedUtil.encodeInt(length)); byteout.write(value); return byteout.toByteArray(); }
private byte[] buildAuthAssertion() throws IOException, KeyStoreException, NoSuchAlgorithmException, UnrecoverableEntryException, InvalidKeyException, SignatureException { ByteArrayOutputStream byteout = new ByteArrayOutputStream(); byte[] value; int length; byteout.write(UnsignedUtil.encodeInt(TagsEnum.TAG_UAFV1_SIGNED_DATA.id)); value = getSignatureData(); length = value.length; byteout.write(UnsignedUtil.encodeInt(length)); byteout.write(value); byte[] dataToSign = byteout.toByteArray(); byteout.write(UnsignedUtil.encodeInt(TagsEnum.TAG_SIGNATURE.id)); value = getSignature(dataToSign); length = value.length; byteout.write(UnsignedUtil.encodeInt(length)); byteout.write(value); return byteout.toByteArray(); }
/** * Returns the private key signature on JBMR2+ or else null. */ public static String getSigningKey(String alias) throws CertificateException, UnrecoverableEntryException, NoSuchAlgorithmException, KeyStoreException, IOException { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) { KeyStore.PrivateKeyEntry entry = getPrivateKeyEntry(alias); if (entry == null) { return null; } Certificate cert = entry.getCertificate(); if (cert == null) { return null; } byte[] input = cert.getEncoded(); return Base64.encodeToString(input, Base64.NO_WRAP); } else { return null; } }
private static KeyStore.PrivateKeyEntry getPrivateKeyEntry(String alias) throws KeyStoreException, CertificateException, NoSuchAlgorithmException, IOException, UnrecoverableEntryException { KeyStore ks = KeyStore.getInstance(SecurityConstants.KEYSTORE_PROVIDER_ANDROID_KEYSTORE); ks.load(null); KeyStore.Entry entry = ks.getEntry(alias, null); if (entry == null) { Log.w(TAG, "No key found under alias: " + alias); return null; } if (!(entry instanceof KeyStore.PrivateKeyEntry)) { Log.w(TAG, "Not an instance of a PrivateKeyEntry"); return null; } return (KeyStore.PrivateKeyEntry) entry; }
/** * 加密 */ public static String encrypt(String alias, String plainText) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException, CertificateException, UnrecoverableEntryException, KeyStoreException, IOException { if (TextUtils.isEmpty(plainText)) { return null; } KeyStore.PrivateKeyEntry entry = getPrivateKeyEntry(alias); if (entry == null) { return null; } PublicKey publicKey = entry.getCertificate().getPublicKey(); Cipher cipher = getCipher(); cipher.init(Cipher.ENCRYPT_MODE, publicKey); return Base64.encodeToString(cipher.doFinal(plainText.getBytes()), Base64.NO_WRAP); }
/** * 解密 */ public static String decrypt(String alias, String cipherText) throws InvalidKeyException, BadPaddingException, IllegalBlockSizeException, NoSuchAlgorithmException, NoSuchPaddingException, CertificateException, UnrecoverableEntryException, KeyStoreException, IOException { if (TextUtils.isEmpty(cipherText)) { return null; } KeyStore.PrivateKeyEntry entry = getPrivateKeyEntry(alias); if (entry == null) { return null; } PrivateKey privateKey = entry.getPrivateKey(); Cipher cipher = getCipher(); cipher.init(Cipher.DECRYPT_MODE, privateKey); return new String(cipher.doFinal(Base64.decode(cipherText, Base64.NO_WRAP))); }
/** * 存储登录 Token */ public static void saveToken(Context context, Token token) { Constant.VALUE_TOKEN = token.getAccessToken(); try { token.setAccessToken( KeyStoreHelper.encrypt(Constant.KEYSTORE_KEY_ALIAS, token.getAccessToken())); token.setTokenType( KeyStoreHelper.encrypt(Constant.KEYSTORE_KEY_ALIAS, token.getTokenType())); token.setRefreshToken( KeyStoreHelper.encrypt(Constant.KEYSTORE_KEY_ALIAS, token.getRefreshToken())); } catch (InvalidKeyException | BadPaddingException | NoSuchAlgorithmException | IllegalBlockSizeException | UnrecoverableEntryException | KeyStoreException | IOException | NoSuchPaddingException | CertificateException e) { e.printStackTrace(); Constant.VALUE_TOKEN = ""; return; } PrefUtil prefUtil = PrefUtil.getInstance(context, Constant.Token.SHARED_PREFERENCES_NAME); prefUtil.putString(Constant.Token.ACCESS_TOKEN, token.getAccessToken()); prefUtil.putString(Constant.Token.TOKEN_TYPE, token.getTokenType()); prefUtil.putInt(Constant.Token.EXPIRES_IN, token.getExpiresIn()); prefUtil.putString(Constant.Token.REFRESH_TOKEN, token.getRefreshToken()); prefUtil.putInt(Constant.Token.CREATED_AT, token.getCreatedAt()); }
/** * 获取登录 Token */ public static Token getToken(Context context) { PrefUtil prefUtil = PrefUtil.getInstance(context, Constant.Token.SHARED_PREFERENCES_NAME); Token token = new Token(); token.setAccessToken(prefUtil.getString(Constant.Token.ACCESS_TOKEN, "")); token.setTokenType(prefUtil.getString(Constant.Token.TOKEN_TYPE, "")); token.setExpiresIn(prefUtil.getInt(Constant.Token.EXPIRES_IN, 0)); token.setRefreshToken(prefUtil.getString(Constant.Token.REFRESH_TOKEN, "")); token.setCreatedAt(prefUtil.getInt(Constant.Token.CREATED_AT, 0)); try { token.setAccessToken( KeyStoreHelper.decrypt(Constant.KEYSTORE_KEY_ALIAS, token.getAccessToken())); token.setTokenType( KeyStoreHelper.decrypt(Constant.KEYSTORE_KEY_ALIAS, token.getTokenType())); token.setRefreshToken( KeyStoreHelper.decrypt(Constant.KEYSTORE_KEY_ALIAS, token.getRefreshToken())); } catch (InvalidKeyException | BadPaddingException | NoSuchAlgorithmException | IllegalBlockSizeException | UnrecoverableEntryException | KeyStoreException | IOException | NoSuchPaddingException | CertificateException e) { e.printStackTrace(); } Constant.VALUE_TOKEN = token.getAccessToken(); return token; }
/** * Reads the keystore to obtain credentials * * @param conf Configuration provided by the Hadoop environment * @throws IOException * @throws OfficeWriterException * */ private void readKeyStore(Configuration conf) throws IOException, OfficeWriterException { if ((this.howc.getCryptKeystoreFile()!=null) && (!"".equals(this.howc.getCryptKeystoreFile()))) { LOG.info("Using keystore to obtain credentials instead of passwords"); HadoopKeyStoreManager hksm = new HadoopKeyStoreManager(conf); try { hksm.openKeyStore(new Path(this.howc.getCryptKeystoreFile()), this.howc.getCryptKeystoreType(), this.howc.getCryptKeystorePassword()); String password=""; if ((this.howc.getCryptKeystoreAlias()!=null) && (!"".equals(this.howc.getCryptKeystoreAlias()))) { password=hksm.getPassword(this.howc.getCryptKeystoreAlias(), this.howc.getCryptKeystorePassword()); } else { password=hksm.getPassword(this.howc.getFileName(), this.howc.getCryptKeystorePassword()); } this.howc.setPassword(password); } catch (NoSuchAlgorithmException | CertificateException | KeyStoreException | IllegalArgumentException | UnrecoverableEntryException | InvalidKeySpecException e) { LOG.error(e); throw new OfficeWriterException("Cannot read keystore to obtain credentials used to encrypt office documents "+e); } } }
/** * Reads the keystore to obtain credentials * * @param conf Configuration provided by the Hadoop environment * @throws IOException * @throws FormatNotUnderstoodException * */ private void readKeyStore(Configuration conf) throws IOException, FormatNotUnderstoodException { if ((this.hocr.getCryptKeystoreFile()!=null) && (!"".equals(this.hocr.getCryptKeystoreFile()))) { LOG.info("Using keystore to obtain credentials instead of passwords"); HadoopKeyStoreManager hksm = new HadoopKeyStoreManager(conf); try { hksm.openKeyStore(new Path(this.hocr.getCryptKeystoreFile()), this.hocr.getCryptKeystoreType(), this.hocr.getCryptKeystorePassword()); String pw=""; if ((this.hocr.getCryptKeystoreAlias()!=null) && (!"".equals(this.hocr.getCryptKeystoreAlias()))) { pw=hksm.getPassword(this.hocr.getCryptKeystoreAlias(), this.hocr.getCryptKeystorePassword()); } else { pw=hksm.getPassword(this.hocr.getFileName(), this.hocr.getCryptKeystorePassword()); } this.hocr.setPassword(pw); } catch (NoSuchAlgorithmException | CertificateException | KeyStoreException | IllegalArgumentException | UnrecoverableEntryException | InvalidKeySpecException e) { LOG.error(e); throw new FormatNotUnderstoodException("Cannot read keystore to obtain credentials to access encrypted documents "+e); } } }
@Test public void createKeyStoreforPasswords() throws IOException, NoSuchAlgorithmException, CertificateException, KeyStoreException, InvalidKeySpecException, UnrecoverableEntryException { Configuration conf = new Configuration(HadoopKeyStoreManagerTest.defaultConf); String tmpDir=tmpPath.toString(); Path outputFile= new Path(tmpDir,"keystore2.jceks"); HadoopKeyStoreManager hksm = new HadoopKeyStoreManager(conf); // create new key store hksm.openKeyStore(null, "JCEKS", "changeit"); hksm.setPassword("test.xlsx", "test2", "changeit"); hksm.store(outputFile, "changeit"); // open existing keystore hksm.openKeyStore(outputFile, "JCEKS", "changeit"); String expectedPassword="test2"; String password=hksm.getPassword("test.xlsx", "changeit"); assertEquals(expectedPassword,password,"Password is correctly read from new keystore"); }
/** * Gets the certificate of the given DeviceID. * * @param id the id * @return the certificate of the given DeviceID * @throws UnresolvableNamingException if the query fails */ @NonNull public X509Certificate getCertificate(DeviceID id) throws UnresolvableNamingException { try { if (id == null) { throw new UnresolvableNamingException("id == null"); } else if (id.equals(getOwnID())) { return getOwnCertificate(); } final X509Certificate certificate = requireComponent(KeyStoreController.KEY).getCertificate(id.getIDString()); if (certificate == null) { throw new UnresolvableNamingException("Certificate for Device " + id + " not found"); } return certificate; } catch (UnrecoverableEntryException | NoSuchAlgorithmException | KeyStoreException e) { throw new UnresolvableNamingException(e); } }
@NonNull private String decryptCurrentKeystoreVersion(String encryptedData) throws KeyStoreException { try { final Cipher cipher = Cipher.getInstance(TRANSFORMATION); final GCMParameterSpec spec = new GCMParameterSpec(128, encryptionIv.getBytes()); cipher.init(Cipher.DECRYPT_MODE, getSecretKey(), spec); final byte[] encryptedBytes = Base64.decode(encryptedData, Base64.DEFAULT); final byte[] decryptedBytes = cipher.doFinal(encryptedBytes); return new String(decryptedBytes, UTF_8); } catch (UnrecoverableEntryException | UnsupportedEncodingException | IllegalBlockSizeException | NoSuchPaddingException | InvalidAlgorithmParameterException | InvalidKeyException | java.security.KeyStoreException | BadPaddingException | NoSuchAlgorithmException e) { throw new KeyStoreException(new Throwable(e.getMessage())); } }
@Bean public ChatApplication chatApplication() throws IOException, NoSuchAlgorithmException, InvalidKeySpecException, KeyStoreException, FileNotFoundException, CertificateException, UnrecoverableEntryException, ConfigurationException { ChatApplication application = new ChatApplication(this.userRegister()); application.addHandler(LSRequest.LS_LOGIN, new LoginHandler(userDatabase, this.userRegister())); application.addHandler(LSRequest.LS_MESSAGE, new PersistentPayloadWrapper(new MessagingHandler(), this.userRegister(), this.userDatabase)); application.addHandler(LSRequest.LS_ASSOCIATE_LOOKUP, new AssociateLookupHandler(userDatabase, this.userRegister())); application.addHandler(LSRequest.LS_ADD_ASSOCIATE, new AddAssociateHandler(userDatabase)); application.addHandler(LSRequest.LS_LOOKUP_USER, new SearchUserHandler(userDatabase)); application.addHandler(LSRequest.LS_DELETE_ASSOCIATE, new DeleteAssociateHandler(userDatabase)); application.addHandler(LSRequest.LS_LOOKUP_KEY, new GetPublicKeyHandler(userDatabase)); application.addHandler(LSRequest.LS_RETRIEVE_UNSENT, new RetrieveUnsentPacketsHandler(userDatabase)); application.addFilter(new AuthenticationFilter()); return application; }
@Bean public HttpServer httpServer() throws IOException, NoSuchAlgorithmException, InvalidKeySpecException, KeyStoreException, FileNotFoundException, CertificateException, UnrecoverableEntryException, ConfigurationException { HttpServer server = HttpServer.createSimpleServer("./", 8080); WebSocketAddOn addon = new WebSocketAddOn(); server.getListeners().stream().forEach((listen) -> { listen.registerAddOn(addon); listen.setSecure(true); listen.setSSLEngineConfig( new SSLEngineConfigurator(this.sslConf()).setClientMode(false).setNeedClientAuth(false)); }); String messengerPath = configuration().getString(GlobalConfig.MESSENGER_PATH); if (messengerPath == null) { messengerPath = GlobalConfig.MESSENGER_PATH_DEFAULT; } ChatApplication application = this.chatApplication(); WebSocketEngine.getEngine().register("", messengerPath, application); return server; }
public void convertJKS2PKCS12(String jksKeyStoreFile,String pkcs12KeyStoreFile, String alias, String password) throws NoSuchAlgorithmException, CertificateException, FileNotFoundException, IOException, KeyStoreException, UnrecoverableEntryException{ // define 2 keystore formats KeyStore ks = KeyStore.getInstance("jks"); KeyStore nks = KeyStore.getInstance("pkcs12"); // Load the jks keystore and open the pkcs12 store ks.load(new FileInputStream(jksKeyStoreFile), password.toCharArray()); nks.load(null, password.toCharArray()); // Get the private key entry and store it in the new keystore KeyStore.PrivateKeyEntry pkEntry = (KeyStore.PrivateKeyEntry) ks.getEntry(alias, new KeyStore.PasswordProtection(password.toCharArray())); nks.setEntry(alias, pkEntry, new KeyStore.PasswordProtection(password.toCharArray())); // Store the new keystore FileOutputStream fos = new FileOutputStream(pkcs12KeyStoreFile); nks.store(fos, password.toCharArray() ); fos.close(); }
@Override public Entry engineGetEntry(String alias, ProtectionParameter protParam) throws KeyStoreException, NoSuchAlgorithmException, UnrecoverableEntryException { LOGGER.debug("engineGetEntry: {}", alias); if ("Authentication".equals(alias) || "Signature".equals(alias)) { PrivateKey privateKey = (PrivateKey) engineGetKey(alias, null); Certificate[] chain = engineGetCertificateChain(alias); PrivateKeyEntry privateKeyEntry = new PrivateKeyEntry(privateKey, chain); return privateKeyEntry; } if ("CA".equals(alias) || "Root".equals(alias) || "RRN".equals(alias)) { Certificate certificate = engineGetCertificate(alias); TrustedCertificateEntry trustedCertificateEntry = new TrustedCertificateEntry(certificate); return trustedCertificateEntry; } return super.engineGetEntry(alias, protParam); }
@SuppressWarnings("unused") @PostConstruct private void processKeyStoreAndMetadata() throws KeyStoreException, IOException, CertificateException, NoSuchAlgorithmException, UnrecoverableEntryException { dsPKEntry = apiKeyStoreAccessor.getPrivateKeyEntry(dsKeyStoreAlias, dsKeyStoreEntryPassword); clientCertPKEntry = apiKeyStoreAccessor.getPrivateKeyEntry(clientCertKeyStoreAlias, clientCertKeyStoreEntryPassword); encryptPKEntry = apiKeyStoreAccessor.getPrivateKeyEntry(encryptionCertKeyStoreAlias, encryptionCertKeyStoreEntryPassword); StringWriter writer = new StringWriter(); Template veTemplate = getTemplate(); VelocityContext context = new VelocityContext(); context.put(TEMPLATE_ISSUER_REFERENCE, issuerName); context.put(TEMPLATE_SIGNING_CERTIFICATE_REFERENCE, fetchCertificateText(dsPKEntry)); context.put(TEMPLATE_ENCRYPTION_CERTIFICATE_REFERENCE, fetchCertificateText(encryptPKEntry)); veTemplate.merge(context, writer); metadata = writer.toString(); }
public void loadPfx(String fileName, String password) throws IOException, NoSuchAlgorithmException, CertificateException, KeyStoreException, UnrecoverableEntryException { FileInputStream fis = new FileInputStream(fileName); try { loadPfx(fis, password); } finally { fis.close(); } }