List of usage examples for java.security NoSuchAlgorithmException printStackTrace
public void printStackTrace()
From source file:org.ejbca.core.protocol.cmp.CmpTestCase.java
protected static void checkCmpResponseGeneral(byte[] retMsg, String issuerDN, X500Name userDN, Certificate cacert, byte[] senderNonce, byte[] transId, boolean signed, String pbeSecret, String expectedSignAlg)/*from www .j a v a2s. com*/ throws IOException, InvalidKeyException, NoSuchAlgorithmException, NoSuchProviderException { assertNotNull("No response from server.", retMsg); assertTrue("Response was of 0 length.", retMsg.length > 0); boolean pbe = (pbeSecret != null); // // Parse response message // ASN1InputStream asn1InputStream = new ASN1InputStream(new ByteArrayInputStream(retMsg)); PKIMessage respObject = null; try { respObject = PKIMessage.getInstance(asn1InputStream.readObject()); } finally { asn1InputStream.close(); } assertNotNull(respObject); // The signer, i.e. the CA, check it's the right CA PKIHeader header = respObject.getHeader(); // Check that the message is signed with the correct digest alg if (StringUtils.isEmpty(expectedSignAlg)) { expectedSignAlg = PKCSObjectIdentifiers.sha1WithRSAEncryption.getId(); } // if cacert is ECDSA we should expect an ECDSA signature alg //if (AlgorithmTools.getSignatureAlgorithm(cacert).contains("ECDSA")) { // expectedSignAlg = X9ObjectIdentifiers.ecdsa_with_SHA1.getId(); //} else if(AlgorithmTools.getSignatureAlgorithm(cacert).contains("ECGOST3410")) { // expectedSignAlg = CryptoProObjectIdentifiers.gostR3411_94_with_gostR3410_2001.getId(); //} else if(AlgorithmTools.getSignatureAlgorithm(cacert).contains("DSTU4145")) { // expectedSignAlg = (new ASN1ObjectIdentifier(CesecoreConfiguration.getOidDstu4145())).getId(); //} if (signed) { AlgorithmIdentifier algId = header.getProtectionAlg(); assertNotNull( "Protection algorithm was null when expecting a signed response, this was propably an unprotected error message: " + header.getFreeText(), algId); assertEquals(expectedSignAlg, algId.getAlgorithm().getId()); } if (pbe) { AlgorithmIdentifier algId = header.getProtectionAlg(); assertNotNull( "Protection algorithm was null when expecting a pbe protected response, this was propably an unprotected error message: " + header.getFreeText(), algId); assertEquals("Protection algorithm id: " + algId.getAlgorithm().getId(), CMPObjectIdentifiers.passwordBasedMac.getId(), algId.getAlgorithm().getId()); // 1.2.840.113549.1.1.5 - SHA-1 with RSA Encryption } // Check that the signer is the expected CA assertEquals(header.getSender().getTagNo(), 4); X500Name expissuer = new X500Name(issuerDN); X500Name actissuer = new X500Name(header.getSender().getName().toString()); assertEquals(expissuer, actissuer); if (signed) { // Verify the signature byte[] protBytes = CmpMessageHelper.getProtectedBytes(respObject); DERBitString bs = respObject.getProtection(); Signature sig; try { sig = Signature.getInstance(expectedSignAlg, "BC"); sig.initVerify(cacert); sig.update(protBytes); boolean ret = sig.verify(bs.getBytes()); assertTrue(ret); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); assertTrue(false); } catch (NoSuchProviderException e) { e.printStackTrace(); assertTrue(false); } catch (InvalidKeyException e) { e.printStackTrace(); assertTrue(false); } catch (SignatureException e) { e.printStackTrace(); assertTrue(false); } } if (pbe) { ASN1OctetString os = header.getSenderKID(); assertNotNull(os); String keyId = CmpMessageHelper.getStringFromOctets(os); log.debug("Found a sender keyId: " + keyId); // Verify the PasswordBased protection of the message byte[] protectedBytes = CmpMessageHelper.getProtectedBytes(respObject); DERBitString protection = respObject.getProtection(); AlgorithmIdentifier pAlg = header.getProtectionAlg(); log.debug("Protection type is: " + pAlg.getAlgorithm().getId()); PBMParameter pp = PBMParameter.getInstance(pAlg.getParameters()); int iterationCount = pp.getIterationCount().getPositiveValue().intValue(); log.debug("Iteration count is: " + iterationCount); AlgorithmIdentifier owfAlg = pp.getOwf(); // Normal OWF alg is 1.3.14.3.2.26 - SHA1 log.debug("Owf type is: " + owfAlg.getAlgorithm().getId()); AlgorithmIdentifier macAlg = pp.getMac(); // Normal mac alg is 1.3.6.1.5.5.8.1.2 - HMAC/SHA1 log.debug("Mac type is: " + macAlg.getAlgorithm().getId()); byte[] salt = pp.getSalt().getOctets(); // log.info("Salt is: "+new String(salt)); byte[] raSecret = pbeSecret != null ? pbeSecret.getBytes() : new byte[0]; byte[] basekey = new byte[raSecret.length + salt.length]; System.arraycopy(raSecret, 0, basekey, 0, raSecret.length); for (int i = 0; i < salt.length; i++) { basekey[raSecret.length + i] = salt[i]; } // Construct the base key according to rfc4210, section 5.1.3.1 MessageDigest dig = MessageDigest.getInstance(owfAlg.getAlgorithm().getId(), BouncyCastleProvider.PROVIDER_NAME); for (int i = 0; i < iterationCount; i++) { basekey = dig.digest(basekey); dig.reset(); } // HMAC/SHA1 os normal 1.3.6.1.5.5.8.1.2 or 1.2.840.113549.2.7 String macOid = macAlg.getAlgorithm().getId(); Mac mac = Mac.getInstance(macOid, BouncyCastleProvider.PROVIDER_NAME); SecretKey key = new SecretKeySpec(basekey, macOid); mac.init(key); mac.reset(); mac.update(protectedBytes, 0, protectedBytes.length); byte[] out = mac.doFinal(); // My out should now be the same as the protection bits byte[] pb = protection.getBytes(); boolean ret = Arrays.equals(out, pb); assertTrue(ret); } // --SenderNonce // SenderNonce is something the server came up with, but it should be 16 // chars byte[] nonce = header.getSenderNonce().getOctets(); assertEquals(nonce.length, 16); // --Recipient Nonce // recipient nonce should be the same as we sent away as sender nonce nonce = header.getRecipNonce().getOctets(); assertEquals(new String(nonce), new String(senderNonce)); // --Transaction ID // transid should be the same as the one we sent nonce = header.getTransactionID().getOctets(); assertEquals(new String(nonce), new String(transId)); }
From source file:de.codecentric.jira.jenkins.plugin.servlet.OverviewServlet.java
public OverviewServlet(TemplateRenderer templateRenderer, JiraAuthenticationContext authenticationContext, PluginSettingsFactory settingsFactory, ApplicationProperties applicationProperties) { this.templateRenderer = templateRenderer; this.authenticationContext = authenticationContext; this.serverList = new ServerList(settingsFactory); this.client = new HttpClient(new MultiThreadedHttpConnectionManager()); //test if jiraversion < 4.3 IsPriorToJiraVersion isPrior = new IsPriorToJiraVersion(applicationProperties); isPrior.setmaxMajorVersion(4);/* w ww .j a v a2 s .c o m*/ isPrior.setmaxMinorVersion(3); this.old = isPrior.shouldDisplay(null); client.getParams().setAuthenticationPreemptive(true); //set SSLContext to accept all certificates try { SSLContext ctx = SSLContext.getInstance("TLS"); ctx.init(new KeyManager[0], new TrustManager[] { new DefaultTrustManager() }, new SecureRandom()); SSLContext.setDefault(ctx); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (KeyManagementException e) { e.printStackTrace(); } SecureProtocolSocketFactory secureProtocolSocketFactory = new SSLProtocolSocketFactory(); Protocol.registerProtocol("https", new Protocol("https", (ProtocolSocketFactory) secureProtocolSocketFactory, 443)); }
From source file:com.indicator_engine.learningcontextdata.ContextData.java
private String getGetData(String data) { String nonce = RandomString.randomString(55); String hash = ""; try {/*ww w . j a va2s.c om*/ hash = sha1( urlEncode(data) + appID + urlEncode(username) + urlEncode(nonce) + appSecret + sha1(password)); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } String getString = "?nonce=" + urlEncode(nonce) + "&aid=" + urlEncode(String.valueOf(appID)) + "&user=" + urlEncode(username) + "&data=" + urlEncode(data) + "&h=" + urlEncode(hash); return getString; }
From source file:be.integrationarchitects.web.dragdrop.servlet.impl.DragDropServletUtils.java
protected String getHash(File f3) throws IOException { MessageDigest m = null;// w w w. ja v a 2 s . com try { m = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); return null; } byte[] buff = new byte[1024]; FileInputStream fin = new FileInputStream(f3); int bytesread = 0; while ((bytesread = fin.read(buff)) > 0) { m.update(buff, 0, bytesread); } fin.close(); byte[] d = m.digest(); String str = new String(Hex.encodeHex(d)); return str; }
From source file:com.indicator_engine.learningcontextdata.ContextData.java
private ArrayList<NameValuePair> getPostData(String data) { ArrayList<NameValuePair> nvp = new ArrayList<NameValuePair>(); String nonce = RandomString.randomString(55); nvp.add(new BasicNameValuePair("nonce", convertToUTF8(nonce))); nvp.add(new BasicNameValuePair("aid", convertToUTF8(String.valueOf(appID)))); nvp.add(new BasicNameValuePair("user", convertToUTF8(username))); nvp.add(new BasicNameValuePair("data", convertToUTF8(data))); String hash;/* w w w. j ava2s .com*/ try { hash = sha1( urlEncode(data) + appID + urlEncode(username) + urlEncode(nonce) + appSecret + sha1(password)); nvp.add(new BasicNameValuePair("h", convertToUTF8(hash))); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } return nvp; }
From source file:org.digitalcampus.oppia.task.DownloadMediaTask.java
@Override protected Payload doInBackground(Payload... params) { Payload payload = params[0];/*w w w .j a v a 2s .c o m*/ for (Object o : payload.getData()) { Media m = (Media) o; File file = new File(MobileLearning.MEDIA_PATH, m.getFilename()); try { URL u = new URL(m.getDownloadUrl()); HttpURLConnection c = (HttpURLConnection) u.openConnection(); c.setRequestMethod("GET"); c.setDoOutput(true); c.connect(); c.setConnectTimeout( Integer.parseInt(prefs.getString(ctx.getString(R.string.prefs_server_timeout_connection), ctx.getString(R.string.prefServerTimeoutConnection)))); c.setReadTimeout( Integer.parseInt(prefs.getString(ctx.getString(R.string.prefs_server_timeout_response), ctx.getString(R.string.prefServerTimeoutResponse)))); int fileLength = c.getContentLength(); DownloadProgress dp = new DownloadProgress(); dp.setMessage(m.getFilename()); dp.setProgress(0); publishProgress(dp); FileOutputStream f = new FileOutputStream(file); InputStream in = c.getInputStream(); MessageDigest md = MessageDigest.getInstance("MD5"); in = new DigestInputStream(in, md); byte[] buffer = new byte[8192]; int len1 = 0; long total = 0; int progress = 0; while ((len1 = in.read(buffer)) > 0) { total += len1; progress = (int) (total * 100) / fileLength; if (progress > 0) { dp.setProgress(progress); publishProgress(dp); } f.write(buffer, 0, len1); } f.close(); dp.setProgress(100); publishProgress(dp); // check the file digest matches, otherwise delete the file // (it's either been a corrupted download or it's the wrong file) byte[] digest = md.digest(); String resultMD5 = ""; for (int i = 0; i < digest.length; i++) { resultMD5 += Integer.toString((digest[i] & 0xff) + 0x100, 16).substring(1); } Log.d(TAG, "supplied digest: " + m.getDigest()); Log.d(TAG, "calculated digest: " + resultMD5); if (!resultMD5.contains(m.getDigest())) { this.deleteFile(file); payload.setResult(false); payload.setResultResponse(ctx.getString(R.string.error_media_download)); } else { payload.setResult(true); payload.setResultResponse(ctx.getString(R.string.success_media_download, m.getFilename())); } } catch (ClientProtocolException e1) { e1.printStackTrace(); payload.setResult(false); payload.setResultResponse(ctx.getString(R.string.error_media_download)); } catch (IOException e1) { e1.printStackTrace(); this.deleteFile(file); payload.setResult(false); payload.setResultResponse(ctx.getString(R.string.error_media_download)); } catch (NoSuchAlgorithmException e) { if (!MobileLearning.DEVELOPER_MODE) { BugSenseHandler.sendException(e); } else { e.printStackTrace(); } payload.setResult(false); payload.setResultResponse(ctx.getString(R.string.error_media_download)); } } return payload; }
From source file:org.ejbca.core.protocol.ws.client.NestedCrmfRequestTestCommand.java
private void init(String args[]) { FileInputStream file_inputstream; try {// w w w . java2 s .com String pwd = args[ARG_KEYSTOREPASSWORD]; String certNameInKeystore = args[ARG_CERTNAMEINKEYSTORE]; file_inputstream = new FileInputStream(args[ARG_KEYSTOREPATH]); KeyStore keyStore = KeyStore.getInstance("PKCS12"); keyStore.load(file_inputstream, pwd.toCharArray()); System.out.println("Keystore size " + keyStore.size()); Enumeration aliases = keyStore.aliases(); while (aliases.hasMoreElements()) { System.out.println(aliases.nextElement()); } Key key = keyStore.getKey(certNameInKeystore, pwd.toCharArray()); getPrintStream().println("Key information " + key.getAlgorithm() + " " + key.getFormat()); PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(key.getEncoded()); KeyFactory keyFactory = KeyFactory.getInstance("RSA"); innerSignKey = keyFactory.generatePrivate(keySpec); innerCertificate = keyStore.getCertificate(certNameInKeystore); } catch (FileNotFoundException e2) { e2.printStackTrace(); } catch (KeyStoreException e) { e.printStackTrace(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (CertificateException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (UnrecoverableKeyException e) { e.printStackTrace(); } catch (InvalidKeySpecException e) { e.printStackTrace(); } try { KeyPair outerSignKeys = KeyTools.genKeys("1024", "RSA"); outerSignKey = outerSignKeys.getPrivate(); X509Certificate signCert = CertTools.genSelfCert("CN=cmpTest,C=SE", 5000, null, outerSignKeys.getPrivate(), outerSignKeys.getPublic(), PKCSObjectIdentifiers.sha256WithRSAEncryption.getId(), true, "BC"); writeCertificate(signCert, "/opt/racerts", "cmpTest.pem"); /* ArrayList<Certificate> certCollection = new ArrayList<Certificate>(); certCollection.add(signCert); byte[] pemRaCert = CertTools.getPEMFromCerts(certCollection); FileOutputStream out = new FileOutputStream(new File("/opt/racerts/cmpStressTest.pem")); out.write(pemRaCert); out.close(); */ } catch (NoSuchAlgorithmException e1) { e1.printStackTrace(); } catch (NoSuchProviderException e1) { e1.printStackTrace(); } catch (InvalidAlgorithmParameterException e1) { e1.printStackTrace(); } catch (InvalidKeyException e) { e.printStackTrace(); } catch (CertificateEncodingException e) { e.printStackTrace(); } catch (SignatureException e) { e.printStackTrace(); } catch (IllegalStateException e) { e.printStackTrace(); //} catch (FileNotFoundException e) { // e.printStackTrace(); //} catch (IOException e) { // e.printStackTrace(); //} catch (CertificateException e) { // e.printStackTrace(); } }
From source file:com.konakart.actions.gateways.BluepayAction.java
/** * Calculates a hex MD5 based on input./* ww w . j a v a2 s . co m*/ * * @param message * String to calculate MD5 of. */ private String md5(String message) throws java.security.NoSuchAlgorithmException { MessageDigest md5 = null; try { md5 = MessageDigest.getInstance("MD5"); } catch (java.security.NoSuchAlgorithmException ex) { ex.printStackTrace(); if (log.isDebugEnabled()) { log.debug(ex); } throw ex; } byte[] dig = md5.digest(message.getBytes()); StringBuffer cod = new StringBuffer(); for (int i = 0; i < dig.length; ++i) { cod.append(Integer.toHexString(0x0100 + (dig[i] & 0x00FF)).substring(1)); } return cod.toString(); }
From source file:org.telscenter.sail.webapp.domain.project.impl.DIYProjectCommunicatorImpl.java
private String generateUniqueIdMD5(Run run, HttpServletRequest request, String groupIdString) { String portalUrl = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort(); String uniqueportalUrl = portalUrl + "run:" + run.getId().toString() + "group:" + groupIdString; MessageDigest m = null;// w w w .j a v a 2s.c o m try { m = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } m.update(uniqueportalUrl.getBytes(), 0, uniqueportalUrl.length()); String uniqueIdMD5 = new BigInteger(1, m.digest()).toString(16); return uniqueIdMD5; }
From source file:org.cgiar.ccafs.marlo.action.superadmin.GuestUsersAction.java
@Override public String save() { User newUser;// ww w. ja va 2s . co m if (isNewUser) { newUser = new User(); newUser.setFirstName(user.getFirstName()); newUser.setLastName(user.getLastName()); newUser.setUsername(user.getUsername()); newUser.setActive(user.isActive()); newUser.setCgiarUser(user.isCgiarUser()); newUser.setAutoSave(user.isAutoSave()); newUser.setEmail(user.getEmail()); if (!user.isCgiarUser()) { newUser.setPassword(user.getPassword()); } newUser = userManager.saveUser(newUser); } else { newUser = userManager.getUser(user.getId()); newUser.setActive(user.isActive()); newUser.setAutoSave(user.isAutoSave()); if (!user.isCgiarUser()) { newUser.setPassword(user.getPassword()); } newUser = userManager.saveUser(newUser); } if (newUser.getId() != -1) { if (user.getCrpUser() != null) { for (CrpUser crpUser : user.getCrpUser()) { if (crpUser.getId() == -1) { GlobalUnit crp = crpManager.getGlobalUnitById(crpUser.getCrp().getId()); CrpUser newCrpUser = new CrpUser(); newCrpUser.setCrp(crp); newCrpUser.setUser(newUser); newCrpUser = crpUserManager.saveCrpUser(newCrpUser); if (newCrpUser.getId() != -1) { UserRole userRole = new UserRole(); List<Role> roles = new ArrayList<>(crp.getRoles()); Role guestRole = roles.stream().filter(r -> r.getAcronym().equals("G")) .collect(Collectors.toList()).get(0); userRole.setRole(guestRole); userRole.setUser(newUser); userRole = userRoleManager.saveUserRole(userRole); if (isNewUser && userRole.getId() != -1) { try { this.sendMailNewUser(newUser, crp); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } } } } } } } this.setInvalidFields(new HashMap<>()); this.addActionMessage(this.getText("saving.saved")); return SUCCESS; }