List of usage examples for org.bouncycastle.util.encoders Base64 decode
public static byte[] decode(String data)
From source file:CryptoTests.java
@Test public void TestString() throws Exception { ByteArrayOutputStream target = new ByteArrayOutputStream(); KeyPair pair = CryptoUtils.generateRSAKeyPair(512); String name = "Aleksandar"; target.write(Base64.encode(name.getBytes())); String keyToString = new String(Base64.encode(pair.getPublic().getEncoded()), "UTF-8"); //keyToString = new String(keyToString.getBytes(), "UTF-8"); assert Arrays.equals(Base64.decode(keyToString), pair.getPublic().getEncoded()) : "Not equal"; }
From source file:Util.java
License:Apache License
/** * // Takes a screen shot if the driver's capabilities include Screen Shots * @param driver The Web Driver instance * @param outputType Either FILE or Base64 * @param folder The folder for images * @param filename The base file name (sans time stamp) * @return Error string starting with ERROR: if failed to create file or the file name that was created *//*from w w w .jav a 2 s.com*/ public static String takeScreenImage(WebDriver driver, String folder, String fileName) { String result = ""; WebDriver theDriver = Driver.getDriver(); if (!(theDriver instanceof WebDriver)) { return "ERROR: No Web Driver found at this step!"; } if (!((HasCapabilities) theDriver).getCapabilities().is(CapabilityType.TAKES_SCREENSHOT)) { return "ERROR: Driver " + Util.sq(theDriver.toString()) + " has no TAKES_SCREENSHOT capabilities. Screen shot not taken"; } String imagesFolder = (isBlank(folder)) ? DDTTestRunner.getReporter().sessionImagesFolderName() : folder; try { File testTempDir = new File(DDTSettings.asValidOSPath(imagesFolder, true)); if (testTempDir.exists()) { if (!testTempDir.isDirectory()) { return "ERROR: Image path exists but is not a directory"; } } else { testTempDir.mkdirs(); } } catch (Exception e) { return "ERROR: File operation (mkdir) failed. " + e.getCause(); } String actualFileName = fileName + " - " + new SimpleDateFormat("yyyyMMdd-HHmmss").format(new Date()) + ".png"; // create screenshot using a casted driver TakesScreenshot snapper = (TakesScreenshot) theDriver; if (DDTSettings.Settings().isLocal()) { File tempImageFile = snapper.getScreenshotAs(OutputType.FILE); if (tempImageFile.length() < (1L)) { return "ERROR: Failed to take screen shot on remote driver"; } File tmpFile = new File(imagesFolder, DDTSettings.asValidOSPath(actualFileName, true)); // testTempImage // move screenshot to our local store try { FileUtils.moveFile(tempImageFile, tmpFile); } catch (Exception e) { return "ERROR: Failed to move tmp file to image file. " + Util.sq(tmpFile.getAbsolutePath()) + " " + e.getCause().toString(); } if (tmpFile.length() < 1L) { return "ERROR: Failed to move tmp file to image file. " + Util.sq(tmpFile.getAbsolutePath()); } result = tmpFile.getAbsolutePath(); } else { // Create Base64 screen shot file on the remote driver and store it locally String tempImageFile = snapper.getScreenshotAs(OutputType.BASE64); if (tempImageFile.length() < (1L)) { return "ERROR: Failed to take screen shot on remote driver"; } Base64 decoder = new Base64(); byte[] imgBytes = (byte[]) decoder.decode(tempImageFile); File tmpFile = new File(imagesFolder, DDTSettings.asValidOSPath(actualFileName, true)); FileOutputStream osf = null; try { osf = new FileOutputStream(tmpFile); osf.write(imgBytes); osf.flush(); } catch (Exception e) { return "ERROR: Failed to create File Output Stream " + e.getCause(); } if (tmpFile.length() < 1L) { return "ERROR: File created from File Output Stream is empty!"; } result = tmpFile.getAbsolutePath(); } return result; }
From source file:Util.java
License:Apache License
/** * @param text - an encrypted text to be decrypted (Base64 logic) * @return a decrypted string - using Base64 logic) *//*w w w . ja v a 2 s.c om*/ public static String decrypt(String text) { String result = new String(Base64.decode(text.getBytes())); return result; }
From source file:ael.com.loterias.Library.c_PGP_KeyGenerator.java
License:GNU General Public License
public PublicKey getPublicKey() { byte[] sigBytes = Base64.decode(this.pubKeyString); X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(sigBytes); KeyFactory keyFact = null;//from w ww . j a v a 2 s . c om try { keyFact = KeyFactory.getInstance("RSA", "BC"); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (NoSuchProviderException e) { e.printStackTrace(); } try { return keyFact.generatePublic(x509KeySpec); } catch (InvalidKeySpecException e) { e.printStackTrace(); } return null; }
From source file:ael.com.loterias.Library.c_PGP_KeyGenerator.java
License:GNU General Public License
public PrivateKey getPrivateKey() { byte[] sigBytes = Base64.decode(this.privKeyString); X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(sigBytes); KeyFactory keyFact = null;//from ww w. j ava 2 s . co m try { keyFact = KeyFactory.getInstance("RSA", "BC"); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (NoSuchProviderException e) { e.printStackTrace(); } try { return keyFact.generatePrivate(x509KeySpec); } catch (InvalidKeySpecException e) { e.printStackTrace(); } return null; }
From source file:ael.com.loterias.Library.c_PGP_KeyGenerator.java
License:GNU General Public License
public String decrypt(PrivateKey pKey, String text) throws Exception { /*String RSA_PUBLIC_KEYx = "-----BEGIN PUBLIC KEY-----" +/*from ww w .j a v a 2s .c o m*/ "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAs83oPzPVBV4fLxUJB9Xi" + "/1+w3ghi6d+NEwnQA1rFho6Eb5nTChQ+Lk38lI0ogQdwjqLK0QhYy6UHQPiXE613" + "RfQayt2a/Qgfd6kmqJr01Vqgy09SYn/BvrorErzWjceyvK6F8MVDUWaspV3YP9QY" + "wdgihNs3vpjJJnQCKeTdr2cUwT1emNEyy6hfD6fBXYW7u19cj0I9guYFfhWx8IMB" + "oKEbg3BWdNHXc2DqRT3RN5HE8hwIw70rCdBHpiJixl38xeKpCdSYCCmnyMmpGF8V" + "7jKFoDlHppbkr8Nfq524o2DbIsKGnjqIxFLDpE4l24FsVtO0z4PkdcJmvqBRxCW1" + "BwIDAQAB" + "-----END PUBLIC KEY-----"; String RSA_PUBLIC_KEY = "-----BEGIN RSA PRIVATE KEY-----\n" + "MIIEogIBAAKCAQEAs83oPzPVBV4fLxUJB9Xi/1+w3ghi6d+NEwnQA1rFho6Eb5nT\n" + "ChQ+Lk38lI0ogQdwjqLK0QhYy6UHQPiXE613RfQayt2a/Qgfd6kmqJr01Vqgy09S\n" + "Yn/BvrorErzWjceyvK6F8MVDUWaspV3YP9QYwdgihNs3vpjJJnQCKeTdr2cUwT1e\n" + "mNEyy6hfD6fBXYW7u19cj0I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C63vxqja44wKBgFd3t+cc5sia2slwNnPG9RX52luxzN6YZgIudMTV\n" + "ltV2WmVFGrINpoBk1pstnpeojxIAs55gz2j4QGFHXC4hdxs+lbRcaEC8s/nxOwo2\n" + "1OqyzH9YOsqUG22vd71Bi+7VdmwBoolny523qG6QJwtmvGFX/2Gzh4RRFMhYnfS8\n" + "gQthAoGAee8HPnM+hhtBngyKjE81PvHLCqGkSuB5lyCKcvtIV7XeEIDiNb9lWTFa\n" + "L999yx6tGOKigKD/pRzGCFMXmi7ScgmTGk83s37XjmSCpgyECCWeZbpkGD/579ed\n" + "tRwLKtFKVH+sFxwOdeXe+cBWOhslECU5wuqu3m4k3KCwiQd+G80=\n" + "-----END RSA PRIVATE KEY-----\n"; String pubKeyPEM = RSA_PUBLIC_KEY.replace("-----BEGIN RSA PRIVATE KEY-----\n", ""); pubKeyPEM = pubKeyPEM.replace("-----END RSA PRIVATE KEY-----\n", ""); */ byte[] encoded = Base64.decode(this.getPrivateKeyAsString()); /* c_logging.getInstance().log(c_logging.LOG_INFO, "key no formateada: " + RSA_PUBLIC_KEY); c_logging.getInstance().log(c_logging.LOG_INFO, "key formateada: " + pubKeyPEM); */ X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(encoded); KeyFactory keyFact = KeyFactory.getInstance("RSA", "BC"); PublicKey privatekey = keyFact.generatePublic(x509KeySpec); //PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(encoded); //KeyFactory kf = KeyFactory.getInstance("RSA"); //PublicKey pubKey = kf.generatePublic(keySpec); Cipher cipher = Cipher.getInstance("RSA", "BC"); cipher.init(Cipher.DECRYPT_MODE, privatekey); byte[] decodedStr = Base64.decode(text); return new String(cipher.doFinal(decodedStr)); }
From source file:aff4.commonobjects.WarrantReader.java
License:Open Source License
public boolean isValid() throws IOException, NoSuchAlgorithmException, InvalidKeyException, SignatureException, TooManyValuesException, ParseException { Resource warrantURN = URN;//from w w w. j av a 2s . c o m Resource authority = (Resource) QueryTools.queryValue(volume, Node.ANY, warrantURN, AFF4.authority); boolean verified = false; Resource warrantGraph = volume.query(Node.ANY, warrantURN, AFF4.type, AFF4.Warrant).get(0).getGraph(); QuadList signedStatements = volume.query(warrantGraph, Node.ANY, Node.ANY, Node.ANY); GraphCanonicalizer standardiser = new GraphCanonicalizer(signedStatements); String canonicalData = standardiser.getCanonicalString(); byte[] bytes = canonicalData.getBytes("UTF-8"); AuthorityReader authorityReader = new AuthorityReader(volume, authority); Signature signature = Signature.getInstance("SHA256withRSA", new BouncyCastleProvider()); signature.initVerify(authorityReader.publicKey); signature.update(bytes); String sig = ((Literal) QueryTools.queryValue(volume, Node.ANY, warrantGraph, AFF4.signature)).asString(); byte[] signatureBytes = Base64.decode(sig); if (!signature.verify(signatureBytes)) { return false; } HashDigestAdapter hasher = new HashDigestAdapter(new SHA256Digest()); QuadList graphs = volume.query(Node.ANY, Node.ANY, AFF4.assertedBy, warrantURN); for (Quad graph : graphs) { Resource subjectGraph = graph.getSubject(); if (!subjectGraph.equals(warrantGraph)) { //String digestMethod = ((Literal)QueryTools.queryValue(volume, Node.ANY, subjectGraph, AFF4.digestMethod)).asString(); String digest = ((Literal) QueryTools.queryValue(volume, Node.ANY, subjectGraph, AFF4.hash)) .asString(); QuadList statements = volume.query(subjectGraph, null, null, null); standardiser = new GraphCanonicalizer(statements); hasher.reset(); hasher.update(standardiser.getCanonicalString()); hasher.doFinal(); String calculatedHash = hasher.getStringValue(); if (!calculatedHash.equals(digest)) { return false; } else { assertions.add(subjectGraph); } } } return true; }
From source file:Applet.utiles.Utiles.java
/** Mtodo que a partir de un certificado en Base 64, devuelve una instancia de * la clase X509Certificate./* w ww.jav a2s . c om*/ * @return X509Certificate * @param certBase64 * @throws CertificateException */ public static X509Certificate decodeCertificate(String certBase64) throws CertificateException { CertificateFactory cf = CertificateFactory.getInstance("X.509"); ByteArrayInputStream isCertCA = new ByteArrayInputStream(Base64.decode(certBase64)); X509Certificate caCert = (X509Certificate) cf.generateCertificate(isCertCA); return caCert; }
From source file:ataraxis.crypt.AtaraxisHeaderParser.java
License:Open Source License
/** * The private method to parse the file. * * @param inFile the input File/* ww w . j a v a 2s.c om*/ * @throws IOException if the file does not exist or can not be readed */ private void parseFile(File inFile) throws IOException { FileInputStream fis = new FileInputStream(inFile); InputStreamReader isr = new InputStreamReader(fis); BufferedReader br = new BufferedReader(isr); String firstLine = br.readLine(); if (firstLine != null && firstLine.equals("AtaraxiS Header Start")) { LOGGER.debug("matches AtaraxisHeaderStart"); headerLines.add(firstLine); String curLine = ""; curLine = br.readLine(); while (curLine != null && !curLine.equals("AtaraxiS Header End")) { headerLines.add(curLine); LOGGER.debug(curLine); if (curLine.startsWith("HeaderVersion:")) { String[] tempVersion = curLine.split(" "); headerVersion = tempVersion[1]; } else if (curLine.startsWith("IV:")) { String[] tempIV = curLine.split(" "); iv = Base64.decode(tempIV[1]); } curLine = br.readLine(); } if (curLine != null) { headerLines.add(curLine); fileContainsHeader = true; } } fis.close(); }
From source file:be.fedict.eid.dss.protocol.simple.client.SignatureResponseProcessor.java
License:Open Source License
/** * Process the incoming DSS response.//from w w w . java 2 s. co m * * @param request * the HTTP servlet request that holds the DSS response. * @param target * our target URL used for validation of the service signature. * @param base64encodedSignatureRequest * optional base64 encoded signature request used for validation * of the service signature. If <code>null</code> meaning * artifact binding was used, signatureRequestId becomes * required. * @param signatureRequestId * optional signature request ID case artifact binding was used. * @param relayState * optional relayState param * @return the signature response DTO. * @throws SignatureResponseProcessorException * in case something went wrong. */ public SignatureResponse process(HttpServletRequest request, String target, String base64encodedSignatureRequest, String signatureRequestId, String relayState) throws SignatureResponseProcessorException { /* * Decode all incoming parameters. */ String signatureStatus = request.getParameter(SIGNATURE_STATUS_PARAMETER); if (null == signatureStatus) { String msg = SIGNATURE_STATUS_PARAMETER + " parameter not present"; LOG.error(msg); throw new SignatureResponseProcessorException(msg); } LOG.debug("signature status: " + signatureStatus); if (!"OK".equals(signatureStatus)) { String msg = "invalid signature status: " + signatureStatus; LOG.error(msg); if ("USER_CANCELLED".equals(signatureStatus)) { throw new UserCancelledSignatureResponseProcessorException("user cancelled"); } throw new SignatureResponseProcessorException(msg); } String signatureResponse = request.getParameter(SIGNATURE_RESPONSE_PARAMETER); String signatureResponseId = request.getParameter(SIGNATURE_RESPONSE_ID_PARAMETER); if (null == signatureResponse && null == signatureResponseId) { String msg = "No " + SIGNATURE_RESPONSE_PARAMETER + " or " + SIGNATURE_RESPONSE_ID_PARAMETER + " parameter found!"; LOG.error(msg); throw new SignatureResponseProcessorException(msg); } String encodedSignatureCertificate = request.getParameter(SIGNATURE_CERTIFICATE_PARAMETER); if (null == encodedSignatureCertificate) { String msg = SIGNATURE_CERTIFICATE_PARAMETER + " parameter not present"; LOG.error(msg); throw new SignatureResponseProcessorException(msg); } /* * Validate RelayState if needed. */ String responseRelayState = request.getParameter(RELAY_STATE_PARAMETER); if (null != relayState) { if (!relayState.equals(responseRelayState)) { String msg = "Returned relayState \"" + responseRelayState + "\" " + "does not match expected RelayState: \"" + relayState + "\""; LOG.error(msg); throw new SignatureResponseProcessorException(msg); } } /* * Check service signature. */ String encodedServiceSigned = request.getParameter(SERVICE_SIGNED_PARAMETER); if (null != encodedServiceSigned) { LOG.debug("service signature present"); String serviceSigned; try { serviceSigned = URLDecoder.decode(encodedServiceSigned, "UTF-8"); } catch (UnsupportedEncodingException e) { throw new SignatureResponseProcessorException("URL decoder error: " + e.getMessage()); } String encodedServiceSignature = request.getParameter(SERVICE_SIGNATURE_PARAMETER); if (null == encodedServiceSignature) { throw new SignatureResponseProcessorException("missing " + SERVICE_SIGNATURE_PARAMETER); } byte[] serviceSignatureValue = Base64.decode(encodedServiceSignature); /* * Parse the service certificate chain. */ int serviceCertificateChainSize = Integer .parseInt(request.getParameter(SERVICE_CERTIFICATE_CHAIN_SIZE_PARAMETER)); List<X509Certificate> serviceCertificateChain = new LinkedList<X509Certificate>(); for (int idx = 1; idx <= serviceCertificateChainSize; idx++) { String encodedCertificate = request.getParameter(SERVICE_CERTIFICATE_PARAMETER_PREFIX + idx); byte[] certificateData = Base64.decode(encodedCertificate); X509Certificate certificate; try { certificate = (X509Certificate) this.certificateFactory .generateCertificate(new ByteArrayInputStream(certificateData)); } catch (CertificateException e) { throw new SignatureResponseProcessorException("cert decoding error: " + e.getMessage()); } serviceCertificateChain.add(certificate); } if (null == target) { throw new SignatureResponseProcessorException( "target parameter required for validation of service signature"); } if (null == base64encodedSignatureRequest && null == signatureRequestId) { throw new SignatureResponseProcessorException("base64encodedSignatureRequest or signatureRequestId " + "required for validation of service signature"); } try { verifyServiceSignature(serviceSigned, target, base64encodedSignatureRequest, signatureRequestId, signatureResponse, signatureResponseId, encodedSignatureCertificate, serviceSignatureValue, serviceCertificateChain); } catch (Exception e) { String msg = "service signature invalid: " + e.getMessage(); LOG.error(msg, e); throw new SignatureResponseProcessorException(msg); } } else { if (null != this.serviceFingerprint) { /* * In case of a service fingerprint being available, we really * require the eID DSS to send us a service signature. */ throw new SignatureResponseProcessorException( "Service fingerprint available but service signature is missing"); } } /* * Parse all incoming data. */ byte[] decodedSignatureResponse = null; if (null != signatureResponse) { decodedSignatureResponse = Base64.decode(signatureResponse); LOG.debug("decoded signature response size: " + decodedSignatureResponse.length); } byte[] decodedSignatureCertificate = Base64.decode(encodedSignatureCertificate); X509Certificate signatureCertificate; try { signatureCertificate = (X509Certificate) this.certificateFactory .generateCertificate(new ByteArrayInputStream(decodedSignatureCertificate)); } catch (CertificateException e) { String msg = SIGNATURE_CERTIFICATE_PARAMETER + " is not an X509 certificate"; LOG.error(msg, e); throw new SignatureResponseProcessorException(msg); } /* * Construct result DTO. */ return new SignatureResponse(decodedSignatureResponse, signatureResponseId, signatureCertificate); }