List of usage examples for java.security NoSuchAlgorithmException getMessage
public String getMessage()
From source file:org.opensocial.auth.OAuthScheme.java
protected HttpMessage getHttpMessage(OAuthMessage message, OAuthAccessor accessor, byte[] body, boolean signBodyHash) throws IOException, RequestException { if (body != null) { if (signBodyHash) { try { MessageDigest md = MessageDigest.getInstance("SHA-1"); byte[] hash = md.digest(body); byte[] encodedHash = new Base64().encode(hash); message.addParameter("oauth_body_hash", new String(encodedHash, "UTF-8")); } catch (java.security.NoSuchAlgorithmException e) { // Ignore exception } catch (java.io.UnsupportedEncodingException e) { // Ignore exception }// w ww . j a v a2 s. c o m } else if (message.getHeader(HttpMessage.CONTENT_TYPE).equals("application/x-www-form-urlencoded")) { message.addParameter(byteArrayToString(body), ""); } } try { message.addRequiredParameters(accessor); } catch (OAuthException e) { throw new RequestException("OAuth error thrown while signing request " + e.getMessage()); } catch (java.net.URISyntaxException e) { throw new RequestException("Malformed request URL " + message.URL + " could not be signed"); } return HttpMessage.newRequest(message, ParameterStyle.QUERY_STRING); }
From source file:JacksonJacksumTest.java
private AbstractChecksum getChecksum(String algorithmName, boolean alternate) { //assertTrue(JacksumAPI.getAvailableAlgorithms().containsKey(algorithmName)); try {/*from w ww . ja v a 2 s . c o m*/ return Algorithm.getAlgorithm(algorithmName).getChecksumInstance(algorithmName, alternate); } catch (NoSuchAlgorithmException ex) { Logger.getLogger(JacksonJacksumTest.class.getName()).throwing(JacksonJacksumTest.class.getName(), "getChecksum", ex); fail(ex.getMessage()); } return null; }
From source file:com.cws.esolutions.security.dao.certmgmt.impl.CertificateManagerImpl.java
/** * @see com.cws.esolutions.security.dao.certmgmt.interfaces.ICertificateManager#applyCertificateRequest(String, File, File, String) *///from w w w . ja va 2s.c o m public synchronized boolean applyCertificateRequest(final String commonName, final File certificateFile, final File keystoreFile, final String storePassword) throws CertificateManagementException { final String methodName = ICertificateManager.CNAME + "#applyCertificateRequest(final String commonName, final File certificateFile, final File keystoreFile, final String storePassword) throws CertificateManagementException"; if (DEBUG) { DEBUGGER.debug(methodName); DEBUGGER.debug("Value: {}", commonName); DEBUGGER.debug("Value: {}", certificateFile); DEBUGGER.debug("Value: {}", keystoreFile); } final File rootDirectory = certConfig.getRootDirectory(); final File certificateDirectory = FileUtils .getFile(certConfig.getCertificateDirectory() + "/" + commonName); final File storeDirectory = FileUtils.getFile(certConfig.getStoreDirectory() + "/" + commonName); if (DEBUG) { DEBUGGER.debug("rootDirectory: {}", rootDirectory); DEBUGGER.debug("certificateDirectory: {}", certificateDirectory); DEBUGGER.debug("storeDirectory: {}", storeDirectory); DEBUGGER.debug("certificateFile: {}", certificateFile); DEBUGGER.debug("keystoreFile: {}", keystoreFile); } boolean isComplete = false; FileInputStream certStream = null; FileOutputStream storeStream = null; FileInputStream keystoreInput = null; FileInputStream rootCertStream = null; FileInputStream intermediateCertStream = null; try { if (!(rootDirectory.exists())) { throw new CertificateManagementException( "Root certificate directory either does not exist or cannot be written to. Cannot continue."); } if (!(rootDirectory.canWrite())) { throw new CertificateManagementException( "Root certificate directory either does not exist or cannot be written to. Cannot continue."); } if (!(certConfig.getRootCertificateFile().exists())) { throw new CertificateManagementException("Root certificate file does not exist. Cannot continue."); } if (!(certConfig.getIntermediateCertificateFile().exists())) { throw new CertificateManagementException( "Intermediate certificate file does not exist. Cannot continue."); } if (!(storeDirectory.canWrite())) { throw new CertificateManagementException( "Keystore directory either does not exist or cannot be written to. Cannot continue."); } if (!(keystoreFile.canWrite())) { throw new CertificateManagementException( "Unable to write to applicable keystore. Cannot continue."); } keystoreInput = FileUtils.openInputStream(keystoreFile); certStream = FileUtils.openInputStream(certificateFile); if (DEBUG) { DEBUGGER.debug("keystoreInput: {}", keystoreInput); DEBUGGER.debug("certStream: {}", certStream); } KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType()); keyStore.load(keystoreInput, storePassword.toCharArray()); if (DEBUG) { DEBUGGER.debug("KeyStore: {}", keyStore); } Key privateKey = keyStore.getKey(commonName, storePassword.toCharArray()); CertificateFactory certFactory = CertificateFactory.getInstance(certConfig.getCertificateType()); if (DEBUG) { DEBUGGER.debug("CertificateFactory: {}", certFactory); } rootCertStream = FileUtils.openInputStream(FileUtils.getFile(certConfig.getRootCertificateFile())); intermediateCertStream = FileUtils .openInputStream(FileUtils.getFile(certConfig.getIntermediateCertificateFile())); if (DEBUG) { DEBUGGER.debug("rootCertStream: {}", rootCertStream); DEBUGGER.debug("intermediateCertStream: {}", intermediateCertStream); } X509Certificate[] responseCert = new X509Certificate[] { (X509Certificate) certFactory.generateCertificate(rootCertStream), (X509Certificate) certFactory.generateCertificate(intermediateCertStream), (X509Certificate) certFactory.generateCertificate(certStream) }; if (DEBUG) { DEBUGGER.debug("X509Certificate[]", (Object) responseCert); } storeStream = FileUtils.openOutputStream(keystoreFile); keyStore.setKeyEntry(commonName, privateKey, storePassword.toCharArray(), responseCert); keyStore.store(storeStream, storePassword.toCharArray()); isComplete = true; } catch (FileNotFoundException fnfx) { throw new CertificateManagementException(fnfx.getMessage(), fnfx); } catch (IOException iox) { throw new CertificateManagementException(iox.getMessage(), iox); } catch (NoSuchAlgorithmException nsax) { throw new CertificateManagementException(nsax.getMessage(), nsax); } catch (IllegalStateException isx) { throw new CertificateManagementException(isx.getMessage(), isx); } catch (KeyStoreException ksx) { throw new CertificateManagementException(ksx.getMessage(), ksx); } catch (CertificateException cx) { throw new CertificateManagementException(cx.getMessage(), cx); } catch (UnrecoverableKeyException ukx) { throw new CertificateManagementException(ukx.getMessage(), ukx); } finally { if (storeStream != null) { IOUtils.closeQuietly(storeStream); } if (intermediateCertStream != null) { IOUtils.closeQuietly(intermediateCertStream); } if (rootCertStream != null) { IOUtils.closeQuietly(rootCertStream); } if (certStream != null) { IOUtils.closeQuietly(certStream); } if (keystoreInput != null) { IOUtils.closeQuietly(keystoreInput); } } return isComplete; }
From source file:com.qut.middleware.esoe.sso.plugins.artifact.impl.ArtifactProcessorImpl.java
public void setEntityIdentifier(String entityIdentifier) { try {// w w w .j av a2s . co m // Digesting the (local) entity identifier is a one-time operation, so we do it here. this.sourceID = digestEntityIdentifier(entityIdentifier); this.entityIdentifier = entityIdentifier; if (this.sourceID.length != 20) { throw new IllegalArgumentException( "SHA1 hash of ESOE identifier resulted in an invalid result. Length should be 20 but was " + this.sourceID.length); } } catch (NoSuchAlgorithmException e) { throw new IllegalArgumentException( "Unable to digest ESOE identifier for source ID. The hash algorithm does not exist. " + e.getMessage(), e); } catch (UnsupportedEncodingException e) { throw new IllegalArgumentException( "Unable to digest ESOE identifier for source ID. The encoding is not supported. " + e.getMessage(), e); } }
From source file:au.edu.jcu.fascinator.plugin.harvester.directory.DerbyCache.java
private String hashFile(File file) throws IOException { InputStream data = new FileInputStream(file); try {//from w w w. j av a2 s. c o m MessageDigest digest = MessageDigest.getInstance("SHA"); byte[] buffer = new byte[BUFFER_SIZE]; int read = data.read(buffer, 0, BUFFER_SIZE); while (read > -1) { digest.update(buffer, 0, read); read = data.read(buffer, 0, BUFFER_SIZE); } return new String(Hex.encodeHex(digest.digest())); } catch (NoSuchAlgorithmException nsae) { throw new RuntimeException(nsae.getMessage()); } }
From source file:com.evolveum.midpoint.prism.crypto.ProtectorImpl.java
private boolean compareHashedPbkd(HashedDataType hashedDataType, String algorithmName, char[] clearChars) throws EncryptionException { DigestMethodType digestMethodType = hashedDataType.getDigestMethod(); byte[] salt = digestMethodType.getSalt(); Integer workFactor = digestMethodType.getWorkFactor(); byte[] digestValue = hashedDataType.getDigestValue(); int keyLen = digestValue.length * 8; SecretKeyFactory secretKeyFactory; try {/*from w w w. j a v a 2 s .c om*/ secretKeyFactory = SecretKeyFactory.getInstance(algorithmName); } catch (NoSuchAlgorithmException e) { throw new EncryptionException(e.getMessage(), e); } PBEKeySpec keySpec = new PBEKeySpec(clearChars, salt, workFactor, keyLen); SecretKey key; try { key = secretKeyFactory.generateSecret(keySpec); } catch (InvalidKeySpecException e) { throw new EncryptionException(e.getMessage(), e); } byte[] hashBytes = key.getEncoded(); return Arrays.equals(digestValue, hashBytes); }
From source file:be.fedict.eid.applet.service.impl.handler.AuthenticationDataMessageHandler.java
private byte[] digestPhoto(String digestAlgoName, byte[] photoFile) { MessageDigest messageDigest;/*from ww w .ja va 2 s. c om*/ try { messageDigest = MessageDigest.getInstance(digestAlgoName); } catch (NoSuchAlgorithmException e) { throw new RuntimeException("SHA error: " + e.getMessage(), e); } byte[] photoDigest = messageDigest.digest(photoFile); return photoDigest; }
From source file:com.evolveum.midpoint.prism.crypto.ProtectorImpl.java
private HashedDataType hashPbkd(ProtectedData<String> protectedData, String algorithmUri, String algorithmName) throws EncryptionException { char[] clearChars = getClearChars(protectedData); byte[] salt = generatePbkdSalt(); int iterations = getPbkdIterations(); SecretKeyFactory secretKeyFactory; try {//from ww w .ja va2 s.co m secretKeyFactory = SecretKeyFactory.getInstance(algorithmName); } catch (NoSuchAlgorithmException e) { throw new EncryptionException(e.getMessage(), e); } PBEKeySpec keySpec = new PBEKeySpec(clearChars, salt, iterations, getPbkdKeyLength()); SecretKey key; try { key = secretKeyFactory.generateSecret(keySpec); } catch (InvalidKeySpecException e) { throw new EncryptionException(e.getMessage(), e); } byte[] hashBytes = key.getEncoded(); HashedDataType hashedDataType = new HashedDataType(); DigestMethodType digestMethod = new DigestMethodType(); digestMethod.setAlgorithm(algorithmUri); digestMethod.setSalt(salt); digestMethod.setWorkFactor(iterations); hashedDataType.setDigestMethod(digestMethod); hashedDataType.setDigestValue(hashBytes); return hashedDataType; }
From source file:net.sourceforge.msscodefactory.cfasterisk.v2_4.CFAsteriskSMWar.CFAsteriskSMWarSetSystemPasswordHtml.java
/** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) *//*from w ww . j av a 2s. c o m*/ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { final String S_ProcName = "doPost"; ICFAsteriskSchemaObj schemaObj; HttpSession sess = request.getSession(false); if (sess == null) { sess = request.getSession(true); schemaObj = new CFAsteriskSchemaPooledObj(); sess.setAttribute("SchemaObj", schemaObj); } else { schemaObj = (ICFAsteriskSchemaObj) sess.getAttribute("SchemaObj"); if (schemaObj == null) { response.sendRedirect("CFAsteriskSMWarLoginHtml"); return; } } ICFAsteriskSchema dbSchema = null; try { CFSecurityAuthorization auth = schemaObj.getAuthorization(); if (auth != null) { response.sendRedirect("CFAsteriskSMWarSecurityMainHtml"); } else { dbSchema = (ICFAsteriskSchema) CFAsteriskSchemaPool.getSchemaPool().getInstance(); schemaObj.setBackingStore(dbSchema); schemaObj.beginTransaction(); ICFSecuritySecUserObj systemUser = schemaObj.getSecUserTableObj().readSecUserByULoginIdx("system"); String passwordHash = systemUser.getRequiredPasswordHash(); if ((passwordHash != null) && (passwordHash.length() > 0) && (!passwordHash.equals("bootstrap"))) { response.sendRedirect("CFAsteriskSMWarLoginHtml"); } else { ICFSecurityClusterObj resolvedCluster; String resolvedClusterDomainName; String resolvedClusterDescription; ICFSecuritySysClusterObj sysCluster = schemaObj.getSysClusterTableObj().readSysClusterByIdIdx(1, false); if (sysCluster == null) { resolvedCluster = null; resolvedClusterDomainName = (String) request.getParameter("ClusterDomainName"); resolvedClusterDescription = (String) request.getParameter("ClusterDescription"); } else { resolvedCluster = sysCluster.getRequiredContainerCluster(); if (resolvedCluster == null) { throw CFLib.getDefaultExceptionFactory().newNullArgumentException(getClass(), S_ProcName, "resolvedCluster"); } resolvedClusterDomainName = resolvedCluster.getRequiredFullDomainName(); resolvedClusterDescription = resolvedCluster.getRequiredDescription(); } String password = (String) request.getParameter("Password"); if (password == null) { password = ""; } String confirmPassword = (String) request.getParameter("ConfirmPassword"); if (confirmPassword == null) { confirmPassword = ""; } response.setContentType("text/html"); PrintWriter out = response.getWriter(); if (password.length() <= 0) { out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01//EN\">"); out.println("<HTML>"); out.println("<BODY>"); out.println("<form method=\"post\" formaction=\"CFAsteriskSMWarSetSystemPasswordHtml\">"); out.println("<H1 style=\"text-align:center\">" + ((resolvedClusterDescription == null) ? "" : resolvedClusterDescription) + " Security Manager</H1>"); out.println( "<H2 style=\"text-align:center\">Please initialize the \"system\" password and cluster details.</H2>"); out.println("<p>"); out.println("<center>"); out.println("<table style=\"width:60%\">"); out.println( "<tr><th style=\"text-align:left\">Password:</th><td><input type=\"password\" name=\"Password\"/></td></tr>"); out.println( "<tr><th style=\"text-align:left\">Confirm Password:</th><td><input type=\"password\" name=\"ConfirmPassword\"/></td></tr>"); out.println( "<tr><th style=\"text-align:left\">Cluster Domain Name:</th><td><input name=\"ClusterDomainName\"/></td></tr>"); out.println( "<tr><th style=\"text-align:left\">Cluster Description:</th><td><input name=\"ClusterDescription\"/></td></tr>"); out.println( "<tr><td colspan=\"2\" style=\"text-align:center\"><button type=\"submit\" name=\"Ok\"\">Ok</button></td></tr>"); out.println("</table>"); out.println("</center>"); out.println("</form>"); out.println("</BODY>"); out.println("</HTML>"); } else if (!password.equals(confirmPassword)) { out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01//EN\">"); out.println("<HTML>"); out.println("<BODY>"); out.println("<form method=\"post\" formaction=\"CFAsteriskSMWarSetSystemPasswordHtml\">"); out.println("<H1 style=\"text-align:center\">" + ((resolvedClusterDescription == null) ? "" : resolvedClusterDescription) + " Security Manager</H1>"); out.println( "<H2 style=\"text-align:center\">Please initialize the \"system\" password and cluster details.</H2>"); out.println("<p>"); out.println("<center>"); out.println("<table style=\"width:60%\">"); out.println( "<tr><th style=\"text-align:left\">Password:</th><td><input type=\"password\" name=\"Password\"/></td></tr>"); out.println( "<tr><th style=\"text-align:left\">Confirm Password:</th><td><input type=\"password\" name=\"ConfirmPassword\"/></td></tr>"); out.println( "<tr><th style=\"text-align:left\">Cluster Domain Name:</th><td><input name=\"ClusterDomainName\"/></td></tr>"); out.println( "<tr><th style=\"text-align:left\">Cluster Description:</th><td><input name=\"ClusterDescription\"/></td></tr>"); out.println( "<tr><td colspan=\"2\" style=\"text-align:center\"><button type=\"submit\" name=\"Ok\"\">Ok</button></td></tr>"); out.println("</table>"); out.println("</center>"); out.println("</form>"); out.println("</BODY>"); out.println("</HTML>"); } else { MessageDigest msgDigest = MessageDigest.getInstance("SHA-512"); msgDigest.update(password.getBytes("UTF-8")); byte[] hash = msgDigest.digest(); byte[] encodedHash = Base64.encodeBase64(hash); msgDigest.update(encodedHash); hash = msgDigest.digest(); encodedHash = Base64.encodeBase64(hash); String hashedAndEncodedPassword = new String(encodedHash); // Need to temporarily "log in" as system.system to set the password ICFSecurityClusterObj systemCluster = schemaObj.getClusterTableObj() .readClusterByUDomainNameIdx("system"); ICFSecurityTenantObj systemTenant = schemaObj.getTenantTableObj() .readTenantByUNameIdx(systemCluster.getRequiredId(), "system"); ICFSecuritySecSessionObj systemSession = schemaObj.getSecSessionTableObj().newInstance(); ICFSecuritySecSessionEditObj editSystemSession = (ICFSecuritySecSessionEditObj) systemSession .beginEdit(); editSystemSession.setRequiredContainerSecUser(systemUser); editSystemSession.setRequiredStart(Calendar.getInstance()); systemSession = editSystemSession.create(); editSystemSession.endEdit(); auth = new CFSecurityAuthorization(); auth.setSecCluster(systemCluster); auth.setSecTenant(systemTenant); auth.setSecSession(systemSession); schemaObj.setAuthorization(auth); if (resolvedCluster == null) { ICFSecurityClusterObj cluster = schemaObj.getClusterTableObj().newInstance(); ICFSecurityClusterEditObj editCluster = cluster.beginEdit(); editCluster.setRequiredFullDomainName(resolvedClusterDomainName); editCluster.setRequiredDescription(resolvedClusterDescription); cluster = editCluster.create(); editCluster.endEdit(); resolvedCluster = cluster; ICFSecurityTenantObj tenant = schemaObj.getTenantTableObj().newInstance(); ICFSecurityTenantEditObj editTenant = tenant.beginEdit(); editTenant.setRequiredContainerCluster(cluster); editTenant.setRequiredTenantName("system"); tenant = editTenant.create(); editTenant.endEdit(); sysCluster = schemaObj.getSysClusterTableObj().newInstance(); ICFSecuritySysClusterEditObj editSysCluster = sysCluster.beginEdit(); editSysCluster.setRequiredContainerCluster(resolvedCluster); editSysCluster.setRequiredSingletonId(1); sysCluster = editSysCluster.create(); editSysCluster.endEdit(); } ICFSecuritySecUserEditObj editSystemUser = (ICFSecuritySecUserEditObj) systemUser .beginEdit(); editSystemUser.setRequiredPasswordHash(hashedAndEncodedPassword); editSystemUser.update(); editSystemUser.endEdit(); editSystemSession = (ICFSecuritySecSessionEditObj) systemSession.beginEdit(); editSystemSession.setOptionalFinish(Calendar.getInstance()); editSystemSession.update(); editSystemSession.endEdit(); schemaObj.commit(); schemaObj.setAuthorization(null); out.println("<H1 style=\"text-align:center\">" + ((resolvedClusterDescription == null) ? "" : resolvedClusterDescription) + " Security Manager</H1>"); out.println("<H2 style=\"text-align:center\">Password set.</H2>"); out.println("<p style=\"text-align:center\">"); out.println( "You may now <A HRef=\"CFAsteriskSMWarLoginHtml\">log in to the security manager.</A>"); } } } } catch (NoSuchAlgorithmException e) { throw CFLib.getDefaultExceptionFactory().newRuntimeException(getClass(), S_ProcName, "Caught NoSuchAlgorithmException -- " + e.getMessage(), e); } catch (RuntimeException e) { throw CFLib.getDefaultExceptionFactory().newRuntimeException(getClass(), S_ProcName, "Caught RuntimeException -- " + e.getMessage(), e); } finally { if (dbSchema != null) { try { if (schemaObj.isTransactionOpen()) { schemaObj.rollback(); } } catch (RuntimeException e) { } schemaObj.setBackingStore(null); CFAsteriskSchemaPool.getSchemaPool().releaseInstance(dbSchema); } } }
From source file:be.fedict.eid.applet.service.impl.handler.AuthenticationDataMessageHandler.java
private void verifySignature(String signatureAlgo, byte[] signatureData, PublicKey publicKey, HttpServletRequest request, byte[]... data) throws ServletException { Signature signature;/*from w w w . j a v a2 s . co m*/ try { signature = Signature.getInstance(signatureAlgo); } catch (NoSuchAlgorithmException e) { throw new ServletException("algo error: " + e.getMessage(), e); } try { signature.initVerify(publicKey); } catch (InvalidKeyException e) { throw new ServletException("key error: " + e.getMessage(), e); } try { for (byte[] dataItem : data) { signature.update(dataItem); } boolean result = signature.verify(signatureData); if (false == result) { AuditService auditService = this.auditServiceLocator.locateService(); if (null != auditService) { String remoteAddress = request.getRemoteAddr(); auditService.identityIntegrityError(remoteAddress); } throw new ServletException("signature incorrect"); } } catch (SignatureException e) { throw new ServletException("signature error: " + e.getMessage(), e); } }