List of usage examples for org.bouncycastle.util.io Streams readAll
public static byte[] readAll(InputStream inStr) throws IOException
From source file:brooklyn.networking.cloudstack.HttpUtil.java
License:Apache License
public static HttpToolResponse invoke(org.jclouds.http.HttpRequest request) { HttpClient client = HttpUtil.createHttpClient(request.getEndpoint(), Optional.<Credentials>absent()); String method = request.getMethod(); try {/*from w ww . ja v a2s . c o m*/ if ("GET".equalsIgnoreCase(method)) { return HttpUtil.httpGet(client, request.getEndpoint(), request.getHeaders()); } else if ("POST".equalsIgnoreCase(method)) { return HttpUtil.httpPost(client, request.getEndpoint(), request.getHeaders(), Streams.readAll(request.getPayload().openStream())); } else { // TODO being lazy! throw new UnsupportedOperationException("Unsupported method: " + method + " for " + request); } } catch (Exception e) { throw Exceptions.propagate(e); } }
From source file:com.aqnote.shared.cryptology.cert.io.PKCSReader.java
License:Open Source License
public static PKCS12PfxPdu readPKCS12(InputStream istream, final char[] pwd) { if (istream == null || pwd == null) return null; try {//from w ww . j a v a2s. c o m PKCS12PfxPdu pfx = new PKCS12PfxPdu(Streams.readAll(istream)); if (!pfx.isMacValid(new BcPKCS12MacCalculatorBuilderProvider(BcDefaultDigestProvider.INSTANCE), pwd)) { logger.error(MSG(R.F, "readPKCS12", "PKCS#12 MAC test failed!")); return null; } return pfx; } catch (Throwable t) { logger.error(MSG(R.F, "readPKCS12", t.getMessage()), t); } return null; }
From source file:com.bekwam.resignator.util.CryptUtils.java
License:Apache License
private byte[] decrypt(byte[] encrypted, char[] passPhrase) throws IOException, PGPException, NoSuchProviderException { try (InputStream in = new ByteArrayInputStream(encrypted)) { InputStream decoderIn = PGPUtil.getDecoderStream(in); PGPObjectFactory pgpF = new PGPObjectFactory(decoderIn, new BcKeyFingerprintCalculator()); PGPEncryptedDataList enc;//from w w w. j a v a 2 s. c o m Object o = pgpF.nextObject(); if (o == null) { // decryption failed; there is no next object // // This could arise if there is a problem with the underlying file. // if (logger.isWarnEnabled()) { logger.warn( "Field could not be decrypted. (Config file modified outside of app?) Returning input bytes as encrypted bytes."); } return encrypted; } // // the first object might be a PGP marker packet. // if (o instanceof PGPEncryptedDataList) { enc = (PGPEncryptedDataList) o; } else { enc = (PGPEncryptedDataList) pgpF.nextObject(); // i don't think this will be used } PGPPBEEncryptedData pbe = (PGPPBEEncryptedData) enc.get(0); InputStream clear = pbe.getDataStream(new JcePBEDataDecryptorFactoryBuilder( new JcaPGPDigestCalculatorProviderBuilder().setProvider("BC").build()).setProvider("BC") .build(passPhrase)); return Streams.readAll(clear); } }
From source file:eu.betaas.taas.securitymanager.common.certificate.utils.PKCS12Utils.java
License:Apache License
/** * A method to read the PKCS12 file in InputStream and return it into * PKCS12PfxPdu object./* w w w .j a v a 2 s . c o m*/ * @param pfxIn: PKCS12 input file as InputStream * @return: * @throws Exception */ public static PKCS12PfxPdu readPKCS12FileBc(InputStream pfxIn) throws Exception { PKCS12PfxPdu pfxPdu = new PKCS12PfxPdu(Streams.readAll(pfxIn)); return pfxPdu; }
From source file:eu.betaas.taas.securitymanager.common.certificate.utils.PKCS12Utils.java
License:Apache License
/** * A method to load BcCredential (consists of certificate chain, end entity * alias and private key of end entity credential) from the PKCS12 file * @param pkcs12FileName: the PKCS12 file name * @param keyPasswd: the password of the key credential * @return/*w w w .j av a2 s. co m*/ * @throws Exception */ public static BcCredential loadPKCS12Credential(String pkcs12FileName, char[] keyPasswd, int certType) { PKCS12PfxPdu pfxPdu = null; // if(certType == APPS_CERT){ // log.info("Reading AppStoreCertInter.p12 file"); // InputStream is = PKCS12Utils.class.getResourceAsStream(pkcs12FileName); // log.info("AppStoreCertInter.p12 file has been converted to InputStream"); // pfxPdu = new PKCS12PfxPdu(Streams.readAll(is)); // log.info("Read the PKCS12PfxPdu..."); // } // else if(certType == GW_CERT){ // Try to put the AppStoreCertInter.p12 in the karaf, so no need to read // from the resource, e.g. getResourceAsStream log.debug("will start loading PKCS12 file..."); try { pfxPdu = new PKCS12PfxPdu(Streams.readAll(new FileInputStream(pkcs12FileName))); } catch (FileNotFoundException e) { // TODO Auto-generated catch block log.error("PKCS12 file: " + pkcs12FileName + " is not found!!"); e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block log.error("IOException in initializing PKCS12PfxPdu..."); e.printStackTrace(); } log.debug("Loading PKCS12 successfully..."); // } try { if (!pfxPdu.isMacValid(new BcPKCS12MacCalculatorBuilderProvider(BcDefaultDigestProvider.INSTANCE), keyPasswd)) { log.error("PKCS#12 MAC test failed!"); return null; } } catch (PKCSException e) { // TODO Auto-generated catch block e.printStackTrace(); } ContentInfo[] infos = pfxPdu.getContentInfos(); InputDecryptorProvider inputDecryptorProvider = new BcPKCS12PBEInputDecryptorProviderBuilder() .build(keyPasswd); String eeAlias = null; AsymmetricKeyParameter privCred = null; List<X509CertificateHolder> chainList = new ArrayList<X509CertificateHolder>(); // log.info("Start iterating over the ContentInfo..."); for (int i = 0; i != infos.length; i++) { if (infos[i].getContentType().equals(PKCSObjectIdentifiers.encryptedData)) { PKCS12SafeBagFactory dataFact = null; try { dataFact = new PKCS12SafeBagFactory(infos[i], inputDecryptorProvider); } catch (PKCSException e) { // TODO Auto-generated catch block log.error("Error in initiating PKCS12SafeBagFactory..."); e.printStackTrace(); } PKCS12SafeBag[] bags = dataFact.getSafeBags(); for (int b = 0; b != bags.length; b++) { PKCS12SafeBag bag = bags[b]; X509CertificateHolder certHldr = (X509CertificateHolder) bag.getBagValue(); chainList.add(certHldr); log.debug("Found a certificate and add it to certificate chain..."); } } else { PKCS12SafeBagFactory dataFact = new PKCS12SafeBagFactory(infos[i]); PKCS12SafeBag[] bags = dataFact.getSafeBags(); PKCS8EncryptedPrivateKeyInfo encInfo = (PKCS8EncryptedPrivateKeyInfo) bags[0].getBagValue(); PrivateKeyInfo info; AsymmetricKeyParameter privKey = null; try { info = encInfo.decryptPrivateKeyInfo(inputDecryptorProvider); privKey = PrivateKeyFactory.createKey(info); } catch (PKCSException e) { // TODO Auto-generated catch block log.error("Error in getting the decrypt private key info..."); e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block log.error("Error in loading private key..."); e.printStackTrace(); } Attribute[] attributes = bags[0].getAttributes(); for (int a = 0; a != attributes.length; a++) { Attribute attr = attributes[a]; if (attr.getAttrType().equals(PKCS12SafeBag.friendlyNameAttribute)) { eeAlias = ((DERBMPString) attr.getAttributeValues()[0]).getString(); privCred = privKey; log.debug("Get end entity alias"); log.debug("Priv. credential D: " + ((ECPrivateKeyParameters) privCred).getD().toString()); } } } } X509CertificateHolder[] chain = new X509CertificateHolder[chainList.size()]; chain = (X509CertificateHolder[]) chainList.toArray(chain); BcCredential cred = new BcCredential(eeAlias, privCred, chain); log.debug("Credential has been loaded!!"); return cred; }
From source file:org.cryptable.pki.communication.PKICMPMessages.java
License:Open Source License
/** * Process the certification in the PKIBody content. This is used by the initialization process * certification and keyupdate process//from w w w .ja va 2 s . co m * * @param pkiBody * @return * @throws IOException * @throws CMSException * @throws CRMFException * @throws InvalidKeySpecException * @throws NoSuchAlgorithmException * @throws CertificateException */ CertificationResult processCertification(PKIBody pkiBody) throws IOException, CMSException, CRMFException, InvalidKeySpecException, NoSuchAlgorithmException, CertificateException { CertificationResult certificationResult = new CertificationResult(); CertRepMessage certRepMessage = CertRepMessage.getInstance(pkiBody.getContent()); CertResponse[] certResponses = certRepMessage.getResponse(); certificationResult.setCertificateId(certResponses[0].getCertReqId().getValue()); CMPCertificate certificate = certResponses[0].getCertifiedKeyPair().getCertOrEncCert().getCertificate(); certificationResult.setX509Certificate(new JcaX509CertificateConverter() .getCertificate(new X509CertificateHolder(certificate.getX509v3PKCert()))); EncryptedValue encPrivateKey = certResponses[0].getCertifiedKeyPair().getPrivateKey(); if (encPrivateKey != null) { JceAsymmetricValueDecryptorGenerator jceAsymmetricValueDecryptorGenerator = new JceAsymmetricValueDecryptorGenerator( pkiKeyStore.getSenderPrivateKey()); InputDecryptor decryptor = jceAsymmetricValueDecryptorGenerator.getValueDecryptor( encPrivateKey.getKeyAlg(), encPrivateKey.getSymmAlg(), encPrivateKey.getEncSymmKey().getBytes()); InputStream dataIn = decryptor .getInputStream(new ByteArrayInputStream(encPrivateKey.getEncValue().getBytes())); byte[] data = Streams.readAll(dataIn); PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(data); KeyFactory keyFactory = KeyFactory.getInstance("RSA"); certificationResult.setPrivateKey(keyFactory.generatePrivate(pkcs8EncodedKeySpec)); } CMPCertificate[] caPubs = certRepMessage.getCaPubs(); for (CMPCertificate cmpCertificate : caPubs) { certificationResult.addX509CertificateToChain(new JcaX509CertificateConverter() .getCertificate(new X509CertificateHolder(cmpCertificate.getX509v3PKCert()))); } return certificationResult; }
From source file:org.cryptacular.util.KeyPairUtil.java
License:Open Source License
/** * Reads an encoded private key from an input stream. Both PKCS#8 and OpenSSL * "traditional" formats are supported in DER or PEM encoding. See {@link * #decodePrivateKey(byte[])} for supported asymmetric algorithms. * * @param in Input stream containing private key data. * * @return Private key./*w ww. j a v a2s . c o m*/ * * @throws IOException On IO errors reading data from file. */ public static PrivateKey readPrivateKey(final InputStream in) throws IOException { return decodePrivateKey(Streams.readAll(in)); }
From source file:org.cryptacular.util.KeyPairUtil.java
License:Open Source License
/** * Reads an encrypted private key from an input stream. Both PKCS#8 and * OpenSSL "traditional" formats are supported in DER or PEM encoding. See * {@link #decodePrivateKey(byte[])} for supported asymmetric algorithms. * * @param in Input stream containing private key data. * @param password Password used to encrypt private key. * * @return Private key./*from www . j av a 2s . c om*/ * * @throws IOException On IO errors reading data from file. */ public static PrivateKey readPrivateKey(final InputStream in, final char[] password) throws IOException { return decodePrivateKey(Streams.readAll(in), password); }
From source file:org.cryptacular.util.KeyPairUtil.java
License:Open Source License
/** * Reads a DER or PEM-encoded public key from data in the given stream. * * @param in Input stream containing an encoded key. * * @return Public key.//from w ww . j a v a 2 s. c o m * * @throws IOException On IO errors */ public static PublicKey readPublicKey(final InputStream in) throws IOException { return decodePublicKey(Streams.readAll(in)); }
From source file:org.cryptoworkshop.ximix.node.core.XimixNodeContext.java
License:Apache License
/** * Reload our previous state and register listener's if required. * * @param homeDirectory root of the node's config * @param passwd the password to be used to open the key file. * @param keyManager the key manager to be reloaded. *//*w ww .j a v a 2s. co m*/ private void setupKeyManager(final File homeDirectory, final char[] passwd, KeyManager keyManager) { final File keyDir = new File(homeDirectory, "keys"); final File store = new File(keyDir, keyManager.getID() + ".p12"); if (store.exists()) { try { keyManager.load(passwd, Streams.readAll(new FileInputStream(store))); } catch (Exception e) { getEventNotifier().notify(EventNotifier.Level.ERROR, "Loading Store: " + store, e); return; } } keyManager.addListener(new KeyManagerListener() { @Override public void keyAdded(KeyManager keyManager, String keyID) { if (homeDirectory != null) { try { byte[] enc = keyManager.getEncoded(passwd); if (!keyDir.exists()) { if (!keyDir.mkdir()) { throw new NodeContextException("Unable to create dir: " + keyDir); } } if (store.exists()) { if (!store.renameTo(new File(keyDir, keyManager.getID() + ".p12.bak"))) { throw new NodeContextException("Unable to rename store from: " + store + " to: " + keyManager.getID() + ".p12.bak"); } } FileOutputStream fOut = new FileOutputStream(store); fOut.write(enc); fOut.close(); } catch (Exception e) { getEventNotifier().notify(EventNotifier.Level.ERROR, "Setting up Key Manager: " + e.getMessage(), e); } } } }); }