List of usage examples for java.security NoSuchAlgorithmException getMessage
public String getMessage()
From source file:org.dasein.cloud.gogrid.GoGridMethod.java
private @Nonnull String stupidPHPMD5(@Nonnull String toSign) throws InternalException, CloudException { try {//from w w w . j a v a 2 s . c o m MessageDigest digest = MessageDigest.getInstance("MD5"); return hex(digest.digest(toSign.getBytes("CP1252"))); } catch (NoSuchAlgorithmException e) { logger.error("No support for MD5: " + e.getMessage()); e.printStackTrace(); throw new InternalException(e); } catch (UnsupportedEncodingException e) { logger.error("No support for CP1252: " + e.getMessage()); e.printStackTrace(); throw new InternalException(e); } }
From source file:org.xdi.oxauth.model.crypto.OxAuthCryptoProvider.java
@Override public boolean verifySignature(String signingInput, String encodedSignature, String alias, JSONObject jwks, String sharedSecret, SignatureAlgorithm signatureAlgorithm) throws Exception { boolean verified = false; if (signatureAlgorithm == SignatureAlgorithm.NONE) { return Util.isNullOrEmpty(encodedSignature); } else if (SignatureAlgorithmFamily.HMAC.equals(signatureAlgorithm.getFamily())) { String expectedSignature = sign(signingInput, null, sharedSecret, signatureAlgorithm); return expectedSignature.equals(encodedSignature); } else { // EC or RSA PublicKey publicKey = null; try {/*w w w. java 2 s . c o m*/ if (jwks == null) { publicKey = getPublicKey(alias); } else { publicKey = getPublicKey(alias, jwks); } if (publicKey == null) { return false; } byte[] signature = Base64Util.base64urldecode(encodedSignature); Signature verifier = Signature.getInstance(signatureAlgorithm.getAlgorithm(), "BC"); //Signature verifier = Signature.getInstance(signatureAlgorithm.getAlgorithm()); verifier.initVerify(publicKey); verifier.update(signingInput.getBytes()); verified = verifier.verify(signature); } catch (NoSuchAlgorithmException e) { LOG.error(e.getMessage(), e); verified = false; } catch (SignatureException e) { LOG.error(e.getMessage(), e); verified = false; } catch (InvalidKeyException e) { LOG.error(e.getMessage(), e); verified = false; } catch (Exception e) { LOG.error(e.getMessage(), e); verified = false; } } return verified; }
From source file:be.fedict.hsm.ws.impl.DigitalSignatureServicePortImpl.java
@Override @WebMethod(operationName = "get-certificate-chain") @WebResult(name = "Response", targetNamespace = "urn:oasis:names:tc:dss:1.0:core:schema", partName = "GetCertificateChainResponse") public ResponseBaseType getCertificateChain( @WebParam(name = "GetCertificateChainRequest", targetNamespace = "urn:be:fedict:hsm-proxy:ws:dss:profiles:hsm-proxy:1.0", partName = "GetCertificateChainRequest") GetCertificateChainRequest getCertificateChainRequest) { String requestId = getCertificateChainRequest.getRequestID(); AnyType optionalInputs = getCertificateChainRequest.getOptionalInputs(); if (null == optionalInputs) { LOG.error("missing dss:OptionalInputs"); return errorResponse(ResultMajor.REQUESTER_ERROR); }/*from w w w . j a v a 2 s . c o m*/ List<Object> optionalInputsContent = optionalInputs.getAny(); String alias = null; for (Object object : optionalInputsContent) { if (object instanceof KeySelector) { KeySelector keySelector = (KeySelector) object; KeyInfoType keyInfo = keySelector.getKeyInfo(); if (null == keyInfo) { LOG.error("missing ds:KeyInfo"); return errorResponse(ResultMajor.REQUESTER_ERROR); } List<Object> keyInfoContent = keyInfo.getContent(); for (Object keyInfoObject : keyInfoContent) { if (keyInfoObject instanceof JAXBElement) { JAXBElement jaxbElement = (JAXBElement) keyInfoObject; alias = (String) jaxbElement.getValue(); } } } } if (null == alias) { LOG.error("missing dss:KeySelector/ds:KeyInfo/ds:KeyName"); return errorResponse(ResultMajor.REQUESTER_ERROR); } LOG.debug("get certificate chain for alias: " + alias); Certificate[] certificateChain; try { certificateChain = this.signatureService.getCertificateChain(alias); } catch (NoSuchAlgorithmException e) { LOG.error("no such algo: " + e.getMessage()); return errorResponse(ResultMajor.REQUESTER_ERROR); } if (null == certificateChain) { LOG.error("no cert chain found"); return errorResponse(ResultMajor.REQUESTER_ERROR); } ResponseBaseType response = this.objectFactory.createResponseBaseType(); response.setRequestID(requestId); response.setProfile(DSSConstants.HSM_PROXY_DSS_PROFILE_URI); Result result = this.objectFactory.createResult(); response.setResult(result); result.setResultMajor(ResultMajor.SUCCESS.getUri()); KeyInfoType keyInfo = this.xmldsigObjectFactory.createKeyInfoType(); AnyType optionalOutputs = this.objectFactory.createAnyType(); optionalOutputs.getAny().add(this.xmldsigObjectFactory.createKeyInfo(keyInfo)); response.setOptionalOutputs(optionalOutputs); List<Object> keyInfoContent = keyInfo.getContent(); X509DataType x509Data = this.xmldsigObjectFactory.createX509DataType(); keyInfoContent.add(this.xmldsigObjectFactory.createX509Data(x509Data)); List<Object> x509DataContent = x509Data.getX509IssuerSerialOrX509SKIOrX509SubjectName(); for (Certificate certificate : certificateChain) { try { x509DataContent .add(this.xmldsigObjectFactory.createX509DataTypeX509Certificate(certificate.getEncoded())); } catch (CertificateEncodingException e) { LOG.error("certificate encoding error: " + e.getMessage()); return errorResponse(ResultMajor.RESPONDER_ERROR); } } return response; }
From source file:edu.emory.cci.aiw.cvrg.eureka.services.resource.UserResource.java
/** * Changes a user's password.// ww w .j a va 2 s . c o m * * @param request the incoming servlet request * @param passwordChangeRequest the request to use to make the password * change * * @throws HttpStatusException Thrown when a password cannot be properly * hashed, or the passwords are mismatched. */ @RolesAllowed({ "researcher", "admin" }) @Path("/passwordchange") @POST public void changePassword(@Context HttpServletRequest request, PasswordChangeRequest passwordChangeRequest) { String username = request.getUserPrincipal().getName(); LocalUserEntity user = this.localUserDao.getByName(username); if (user == null) { LOGGER.error("User " + username + " not found"); throw new HttpStatusException(Response.Status.NOT_FOUND); } else this.localUserDao.refresh(user); String newPassword = passwordChangeRequest.getNewPassword(); String oldPasswordHash; String newPasswordHash; try { oldPasswordHash = StringUtil.md5(passwordChangeRequest.getOldPassword()); newPasswordHash = StringUtil.md5(newPassword); } catch (NoSuchAlgorithmException e) { LOGGER.error(e.getMessage(), e); throw new HttpStatusException(Response.Status.INTERNAL_SERVER_ERROR, e); } if (user.getPassword().equals(oldPasswordHash)) { user.setPassword(newPasswordHash); user.setPasswordExpiration(this.getExpirationDate()); if (this.properties.getI2b2URL() != null) { this.i2b2Client.changePassword(user.getEmail(), newPassword); } this.localUserDao.update(user); try { this.emailSender.sendPasswordChangeMessage(user); } catch (EmailException ee) { LOGGER.error(ee.getMessage(), ee); } } else { throw new HttpStatusException(Response.Status.BAD_REQUEST, "Error while changing password. Old password is incorrect."); } }
From source file:net.lldp.checksims.algorithm.linesimilarity.LineSimilarityChecker.java
/** * Detect similarities using line similarity comparator. * * @param a First submission to check//ww w . j a va2 s . co m * @param b Second submission to check * @return Results of the similarity detection * @throws TokenTypeMismatchException Thrown comparing two submissions with different token types * @throws InternalAlgorithmError Thrown on error obtaining a hash algorithm instance */ @Override public AlgorithmResults detectSimilarity(Pair<Submission, Submission> ab, PercentableTokenListDecorator a, PercentableTokenListDecorator b) throws TokenTypeMismatchException, InternalAlgorithmError { checkNotNull(a); checkNotNull(b); //TokenList linesA = a.getContentAsTokens(); //TokenList linesB = b.getContentAsTokens(); //TokenList finalA = TokenList.cloneTokenList(linesA); //TokenList finalB = TokenList.cloneTokenList(linesB); /* if(!a.getTokenType().equals(b.getTokenType())) { throw new TokenTypeMismatchException("Token list type mismatch: submission " + a.getName() + " has type " + linesA.type.toString() + ", while submission " + b.getName() + " has type " + linesB.type.toString()); } else */ if (a.equals(b)) { a.getDataCopy().stream().forEach((token) -> token.setValid(false)); b.getDataCopy().stream().forEach((token) -> token.setValid(false)); return new AlgorithmResults(ab, a, b); } MessageDigest hasher; // Get a hashing instance try { hasher = MessageDigest.getInstance("SHA-512"); } catch (NoSuchAlgorithmException e) { throw new InternalAlgorithmError("Error instantiating SHA-512 hash algorithm: " + e.getMessage()); } // Create a line database map // Per-method basis to ensure we have no mutable state in the class Map<String, List<SubmissionLine>> lineDatabase = new HashMap<>(); // Hash all lines in A, and put them in the lines database addLinesToMap(a.getDataCopy(), lineDatabase, ab.getLeft(), hasher); // Hash all lines in B, and put them in the lines database addLinesToMap(b.getDataCopy(), lineDatabase, ab.getRight(), hasher); // Number of matched lines contained in both //int identicalLinesA = 0; //int identicalLinesB = 0; // Check all the keys for (String key : lineDatabase.keySet()) { // If more than 1 line has the hash... if (lineDatabase.get(key).size() != 1) { int numLinesA = 0; int numLinesB = 0; // Count the number of that line in each submission for (SubmissionLine s : lineDatabase.get(key)) { if (s.submission.equals(ab.getLeft())) { numLinesA++; } else if (s.submission.equals(ab.getRight())) { numLinesB++; } else { throw new RuntimeException("Unreachable code!"); } } if (numLinesA == 0 || numLinesB == 0) { // Only one of the submissions includes the line - no plagiarism here continue; } // Set matches invalid for (SubmissionLine s : lineDatabase.get(key)) { if (s.submission.equals(ab.getLeft())) { a.getDataCopy().get(s.lineNum).setValid(false); } else if (s.submission.equals(ab.getRight())) { b.getDataCopy().get(s.lineNum).setValid(false); } else { throw new RuntimeException("Unreachable code!"); } } //identicalLinesA += numLinesA; //identicalLinesB += numLinesB; } } //int invalTokensA = (int)a.getDataCopy().stream().filter((token) -> !token.isValid()).count(); //int invalTokensB = (int)b.getDataCopy().stream().filter((token) -> !token.isValid()).count(); /* if(invalTokensA != identicalLinesA) { throw new InternalAlgorithmError("Internal error: number of identical tokens (" + identicalLinesA + ") does not match number of invalid tokens (" + invalTokensA + ")"); } else if(invalTokensB != identicalLinesB) { throw new InternalAlgorithmError("Internal error: number of identical tokens (" + identicalLinesB + ") does not match number of invalid tokens (" + invalTokensB + ")"); } */ return new AlgorithmResults(ab, a, b); }
From source file:org.trellisldp.http.impl.MutatingLdpHandler.java
protected CompletionStage<Void> persistContent(final BinaryMetadata metadata, final Digest digest) { if (isNull(digest)) { return persistContent(metadata); }//from w ww .j a v a 2 s . c o m try { final String alg = of(digest).map(Digest::getAlgorithm).map(String::toUpperCase) .filter(isEqual("SHA").negate()).orElse("SHA-1"); return getServices().getBinaryService().setContent(metadata, entity, MessageDigest.getInstance(alg)) .thenApply(MessageDigest::digest).thenApply(getEncoder()::encodeToString) .thenCompose(serverComputed -> { if (digest.getDigest().equals(serverComputed)) { LOGGER.debug("Successfully persisted digest-verified bitstream: {}", metadata.getIdentifier()); return completedFuture(null); } return getServices().getBinaryService().purgeContent(metadata.getIdentifier()) .thenAccept(future -> { throw new BadRequestException( "Supplied digest value does not match the server-computed digest: " + serverComputed); }); }); } catch (final NoSuchAlgorithmException ex) { throw new BadRequestException("Invalid digest algorithm: " + ex.getMessage()); } }
From source file:com.appdynamics.monitors.azure.statsCollector.AzureServiceBusStatsCollector.java
private SSLSocketFactory getSSLSocketFactory(String keyStoreName, String password) { KeyStore ks = getKeyStore(keyStoreName, password); KeyManagerFactory keyManagerFactory = null; try {/*from w w w.j a va 2 s . c o m*/ keyManagerFactory = KeyManagerFactory.getInstance("SunX509"); keyManagerFactory.init(ks, password.toCharArray()); SSLContext context = SSLContext.getInstance("TLS"); context.init(keyManagerFactory.getKeyManagers(), null, new SecureRandom()); return context.getSocketFactory(); } catch (NoSuchAlgorithmException e) { logger.error(e.getMessage(), e); throw new RuntimeException(e.getMessage(), e); } catch (KeyStoreException e) { logger.error(e.getMessage(), e); throw new RuntimeException(e.getMessage(), e); } catch (UnrecoverableKeyException e) { logger.error(e.getMessage(), e); throw new RuntimeException(e.getMessage(), e); } catch (KeyManagementException e) { logger.error(e.getMessage(), e); throw new RuntimeException(e.getMessage(), e); } }
From source file:com.amazonaws.services.s3.internal.crypto.S3CryptoModuleBase.java
protected final SecretKey generateCEK() { KeyGenerator generator;//from w ww . j a v a 2s.co m try { generator = KeyGenerator.getInstance(contentCryptoScheme.getKeyGeneratorAlgorithm()); generator.init(contentCryptoScheme.getKeyLengthInBits(), cryptoScheme.getSecureRandom()); return generator.generateKey(); } catch (NoSuchAlgorithmException e) { throw new AmazonClientException("Unable to generate envelope symmetric key:" + e.getMessage(), e); } }
From source file:ch.bfh.evoting.alljoyn.MessageEncrypter.java
/** * Key derivation method from the given password * @param password password to derive//from w ww .j a v a 2 s . c o m */ private void derivateKey(char[] password) { //Inspired from http://stackoverflow.com/questions/992019/java-256-bit-aes-password-based-encryption SecretKeyFactory factory; try { factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1"); //1000 iteration should be enough since the attack has to be done online and //salt changes for each group KeySpec spec = new PBEKeySpec(password, this.salt, 1000, 256); SecretKey tmp = factory.generateSecret(spec); secretKey = new SecretKeySpec(tmp.getEncoded(), "AES"); this.isReady = true; } catch (NoSuchAlgorithmException e) { Log.d(TAG, e.getMessage() + " "); e.printStackTrace(); } catch (InvalidKeySpecException e) { Log.d(TAG, e.getMessage() + " "); e.printStackTrace(); } }