List of usage examples for java.security MessageDigest reset
public void reset()
From source file:org.apache.hadoop.hive.metastore.hbase.HBaseUtils.java
/** * Produce a hash for the storage descriptor * @param sd storage descriptor to hash//from ww w. jav a 2 s. c o m * @param md message descriptor to use to generate the hash * @return the hash as a byte array */ public static byte[] hashStorageDescriptor(StorageDescriptor sd, MessageDigest md) { // Note all maps and lists have to be absolutely sorted. Otherwise we'll produce different // results for hashes based on the OS or JVM being used. md.reset(); for (FieldSchema fs : sd.getCols()) { md.update(fs.getName().getBytes(ENCODING)); md.update(fs.getType().getBytes(ENCODING)); if (fs.getComment() != null) md.update(fs.getComment().getBytes(ENCODING)); } if (sd.getInputFormat() != null) { md.update(sd.getInputFormat().getBytes(ENCODING)); } if (sd.getOutputFormat() != null) { md.update(sd.getOutputFormat().getBytes(ENCODING)); } md.update(sd.isCompressed() ? "true".getBytes(ENCODING) : "false".getBytes(ENCODING)); md.update(Integer.toString(sd.getNumBuckets()).getBytes(ENCODING)); if (sd.getSerdeInfo() != null) { SerDeInfo serde = sd.getSerdeInfo(); if (serde.getName() != null) { md.update(serde.getName().getBytes(ENCODING)); } if (serde.getSerializationLib() != null) { md.update(serde.getSerializationLib().getBytes(ENCODING)); } if (serde.getParameters() != null) { SortedMap<String, String> params = new TreeMap<>(serde.getParameters()); for (Map.Entry<String, String> param : params.entrySet()) { md.update(param.getKey().getBytes(ENCODING)); md.update(param.getValue().getBytes(ENCODING)); } } } if (sd.getBucketCols() != null) { List<String> bucketCols = new ArrayList<>(sd.getBucketCols()); for (String bucket : bucketCols) md.update(bucket.getBytes(ENCODING)); } if (sd.getSortCols() != null) { SortedSet<Order> orders = new TreeSet<>(sd.getSortCols()); for (Order order : orders) { md.update(order.getCol().getBytes(ENCODING)); md.update(Integer.toString(order.getOrder()).getBytes(ENCODING)); } } if (sd.getSkewedInfo() != null) { SkewedInfo skewed = sd.getSkewedInfo(); if (skewed.getSkewedColNames() != null) { SortedSet<String> colnames = new TreeSet<>(skewed.getSkewedColNames()); for (String colname : colnames) md.update(colname.getBytes(ENCODING)); } if (skewed.getSkewedColValues() != null) { SortedSet<String> sortedOuterList = new TreeSet<>(); for (List<String> innerList : skewed.getSkewedColValues()) { SortedSet<String> sortedInnerList = new TreeSet<>(innerList); sortedOuterList.add(StringUtils.join(sortedInnerList, ".")); } for (String colval : sortedOuterList) md.update(colval.getBytes(ENCODING)); } if (skewed.getSkewedColValueLocationMaps() != null) { SortedMap<String, String> sortedMap = new TreeMap<>(); for (Map.Entry<List<String>, String> smap : skewed.getSkewedColValueLocationMaps().entrySet()) { SortedSet<String> sortedKey = new TreeSet<>(smap.getKey()); sortedMap.put(StringUtils.join(sortedKey, "."), smap.getValue()); } for (Map.Entry<String, String> e : sortedMap.entrySet()) { md.update(e.getKey().getBytes(ENCODING)); md.update(e.getValue().getBytes(ENCODING)); } } md.update(sd.isStoredAsSubDirectories() ? "true".getBytes(ENCODING) : "false".getBytes(ENCODING)); } return md.digest(); }
From source file:org.jflicks.tv.programdata.sd.SchedulesDirect.java
private Client getClient(String user, String password, String country, String zip) { Client result = null;//from www. ja va 2s. com if ((user != null) && (password != null) && (country != null) && (zip != null)) { try { MessageDigest md = MessageDigest.getInstance("SHA-1"); md.reset(); md.update(password.getBytes()); String sha = new String(Hex.encodeHex(md.digest())); Client c = new Client(); if (c.doToken(user, sha)) { if (c.doStatus()) { LogUtil.log(LogUtil.DEBUG, "SD json server status ok\n"); if (c.doHeadend(country, zip)) { result = c; } } } } catch (Exception ex) { LogUtil.log(LogUtil.WARNING, "getClient: " + ex.getMessage()); } } return (result); }
From source file:org.everrest.websockets.client.WSClient.java
private void validateResponseHeaders() throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(in)); String line = br.readLine();/*from ww w . j a v a 2 s. c o m*/ if (line != null && !line.startsWith("HTTP/1.1 101")) { throw new IOException("Invalid server response. Expected status is 101 'Switching Protocols'. "); } Map<String, String> headers = new HashMap<>(); while (!((line = br.readLine()) == null || line.isEmpty())) { int colon = line.indexOf(':'); if (colon > 0 && colon < line.length()) { headers.put(line.substring(0, colon).trim().toLowerCase(), line.substring(colon + 1).trim()); } } // 'Upgrade' header String header = headers.get("upgrade"); if (!"websocket".equals(header)) { throw new IOException(String .format("Invalid 'Upgrade' response header. Returned '%s' but 'websocket' expected. ", header)); } // 'Connection' header header = headers.get("connection"); if (!"upgrade".equals(header)) { throw new IOException(String.format( "Invalid 'Connection' response header. Returned '%s' but 'upgrade' expected. ", header)); } // 'Sec-WebSocket-Accept' header MessageDigest md; try { md = MessageDigest.getInstance("SHA-1"); } catch (NoSuchAlgorithmException e) { // should never happen. throw new IllegalStateException(e.getMessage(), e); } md.reset(); byte[] digest = md.digest((secWebSocketKey + GLOBAL_WS_SERVER_UUID).getBytes()); final String expectedWsSecurityAccept = Base64.encodeBase64String(digest); header = headers.get("sec-websocket-accept"); if (!expectedWsSecurityAccept.equals(header)) { throw new IOException("Invalid 'Sec-WebSocket-Accept' response header."); } }
From source file:org.bremersee.common.security.crypto.password.PasswordEncoderImpl.java
@Override public boolean userPasswordMatches(final byte[] userPassword, final String clearPassword) { if (userPassword == null && StringUtils.isBlank(clearPassword)) { return true; }//from ww w . j a v a 2 s . co m if (userPassword == null || StringUtils.isBlank(clearPassword)) { return false; } final String[] ap = getAlgorithmAndPassword(userPassword); final String localAlgorithm = ap[0]; final String password = ap[1]; if (NO_ENCRYPTION.equalsIgnoreCase(localAlgorithm)) { return StringUtils.isBlank(clearPassword) && password == null || clearPassword.equals(password); } final MessageDigest md = getMessageDigest(localAlgorithm); if (isSaltedSha(localAlgorithm)) { // extract the SHA hashed data into hs[0] // extract salt into hs[1] final byte[][] hs = split(Base64.decodeBase64(password), getPasswordHashSize(localAlgorithm)); final byte[] hash = hs[0]; final byte[] salt = hs[1]; // Update digest object with byte array of clear text string and salt md.reset(); md.update(clearPassword.getBytes()); md.update(salt); // Complete hash computation, this is now binary data final byte[] pwhash = md.digest(); if (log.isDebugEnabled()) { log.debug("Salted Hash extracted (in hex): " + Hex.encodeHexString(hash)); log.debug("Salt extracted (in hex): " + Hex.encodeHexString(salt)); log.debug("Hash length is: " + hash.length); log.debug("Salt length is: " + salt.length); log.debug("Salted Hash presented in hex: " + Hex.encodeHexString(pwhash)); } final boolean result = MessageDigest.isEqual(hash, pwhash); log.debug("Password matches? " + result); return result; } final byte[] digest = md.digest(CodingUtils.toBytesSilently(clearPassword, StandardCharsets.UTF_8)); return MessageDigest.isEqual(digest, Base64.decodeBase64(password)); }
From source file:org.apache.rampart.builder.SymmetricBindingBuilder.java
private String getSHA1(byte[] input) throws RampartException { MessageDigest sha = null; try {/*from w w w . j a v a2s. c o m*/ sha = MessageDigest.getInstance("SHA-1"); } catch (NoSuchAlgorithmException e1) { throw new RampartException("noSHA1availabe", e1); } sha.reset(); sha.update(input); byte[] data = sha.digest(); return Base64.encode(data); }
From source file:org.wso2.carbon.security.util.ServerCrypto.java
@Override /**/* w ww . ja va 2 s . com*/ * @see org.apache.ws.security.components.crypto.Crypto#getSKIBytesFromCert(java.security.cert.X509Certificate) */ public byte[] getSKIBytesFromCert(X509Certificate cert) throws WSSecurityException { /* * Gets the DER-encoded OCTET string for the extension value (extnValue) * identified by the passed-in oid String. The oid string is represented * by a set of positive whole numbers separated by periods. */ byte[] derEncodedValue = cert.getExtensionValue(SKI_OID); if (cert.getVersion() < 3 || derEncodedValue == null) { PublicKey key = cert.getPublicKey(); if (!(key instanceof RSAPublicKey)) { throw new WSSecurityException(1, "noSKIHandling", new Object[] { "Support for RSA key only" }); } byte[] encoded = key.getEncoded(); // remove 22-byte algorithm ID and header byte[] value = new byte[encoded.length - 22]; System.arraycopy(encoded, 22, value, 0, value.length); MessageDigest sha; try { sha = MessageDigest.getInstance("SHA-1"); } catch (NoSuchAlgorithmException ex) { throw new WSSecurityException(1, "noSKIHandling", new Object[] { "Wrong certificate version (<3) and no " + "SHA1 message digest availabe" }); } sha.reset(); sha.update(value); return sha.digest(); } /** * Strip away first four bytes from the DerValue (tag and length of * ExtensionValue OCTET STRING and KeyIdentifier OCTET STRING) */ byte abyte0[] = new byte[derEncodedValue.length - 4]; System.arraycopy(derEncodedValue, 4, abyte0, 0, abyte0.length); return abyte0; }
From source file:test.integ.be.e_contract.mycarenet.ehbox.EHealthBoxPublicationClientTest.java
@Test public void testPublishAnnex() throws Exception { // STS// ww w .ja va2s . co m EHealthSTSClient client = new EHealthSTSClient("https://wwwacc.ehealth.fgov.be/sts_1_1/SecureTokenService"); Security.addProvider(new BeIDProvider()); KeyStore keyStore = KeyStore.getInstance("BeID"); keyStore.load(null); PrivateKey authnPrivateKey = (PrivateKey) keyStore.getKey("Authentication", null); X509Certificate authnCertificate = (X509Certificate) keyStore.getCertificate("Authentication"); KeyStore eHealthKeyStore = KeyStore.getInstance("PKCS12"); FileInputStream fileInputStream = new FileInputStream(this.config.getEHealthPKCS12Path()); eHealthKeyStore.load(fileInputStream, this.config.getEHealthPKCS12Password().toCharArray()); Enumeration<String> aliasesEnum = eHealthKeyStore.aliases(); String alias = aliasesEnum.nextElement(); X509Certificate eHealthCertificate = (X509Certificate) eHealthKeyStore.getCertificate(alias); PrivateKey eHealthPrivateKey = (PrivateKey) eHealthKeyStore.getKey(alias, this.config.getEHealthPKCS12Password().toCharArray()); List<Attribute> attributes = new LinkedList<Attribute>(); attributes.add(new Attribute("urn:be:fgov:identification-namespace", "urn:be:fgov:ehealth:1.0:certificateholder:person:ssin")); attributes.add(new Attribute("urn:be:fgov:identification-namespace", "urn:be:fgov:person:ssin")); List<AttributeDesignator> attributeDesignators = new LinkedList<AttributeDesignator>(); attributeDesignators.add(new AttributeDesignator("urn:be:fgov:identification-namespace", "urn:be:fgov:ehealth:1.0:certificateholder:person:ssin")); attributeDesignators .add(new AttributeDesignator("urn:be:fgov:identification-namespace", "urn:be:fgov:person:ssin")); attributeDesignators.add(new AttributeDesignator("urn:be:fgov:certified-namespace:ehealth", "urn:be:fgov:person:ssin:nurse:boolean")); Element assertion = client.requestAssertion(authnCertificate, authnPrivateKey, eHealthCertificate, eHealthPrivateKey, attributes, attributeDesignators); assertNotNull(assertion); String assertionString = client.toString(assertion); // eHealthBox publication EHealthBoxPublicationClient publicationClient = new EHealthBoxPublicationClient( "https://services-acpt.ehealth.fgov.be/ehBoxPublication/v3"); ObjectFactory objectFactory = new ObjectFactory(); PublicationMessageType publicationMessage = objectFactory.createPublicationMessageType(); String publicationId = UUID.randomUUID().toString().substring(1, 13); LOG.debug("publication id: " + publicationId); publicationMessage.setPublicationId(publicationId); DestinationContextType destinationContext = objectFactory.createDestinationContextType(); publicationMessage.getDestinationContext().add(destinationContext); destinationContext.setQuality("NURSE"); destinationContext.setType("INSS"); destinationContext.setId(getUserIdentifier(authnCertificate)); ContentContextType contentContext = objectFactory.createContentContextType(); publicationMessage.setContentContext(contentContext); PublicationContentType publicationContent = objectFactory.createPublicationContentType(); contentContext.setContent(publicationContent); PublicationDocumentType publicationDocument = objectFactory.createPublicationDocumentType(); publicationContent.setDocument(publicationDocument); publicationDocument.setTitle("test"); publicationDocument.setMimeType("text/plain"); publicationDocument.setDownloadFileName("test.txt"); byte[] message = "hello world".getBytes(); publicationDocument.setEncryptableTextContent(message); MessageDigest messageDigest = MessageDigest.getInstance("SHA-256"); byte[] digest = messageDigest.digest(message); publicationDocument.setDigest(Base64.encodeBase64String(digest)); List<PublicationAnnexType> publicationAnnexList = publicationContent.getAnnex(); PublicationAnnexType publicationAnnex = objectFactory.createPublicationAnnexType(); publicationAnnexList.add(publicationAnnex); publicationAnnex.setDownloadFileName("test.txt"); publicationAnnex.setEncryptableTitle("hello world".getBytes()); publicationAnnex.setMimeType("application/octet-stream"); publicationAnnex.setEncryptableTextContent(message); messageDigest.reset(); digest = messageDigest.digest(message); publicationAnnex.setDigest(Base64.encodeBase64String(digest)); ContentSpecificationType contentSpecification = objectFactory.createContentSpecificationType(); contentContext.setContentSpecification(contentSpecification); contentSpecification.setContentType("DOCUMENT"); publicationClient.setCredentials(eHealthPrivateKey, assertionString); publicationClient.publish(publicationMessage); }
From source file:org.sakaiproject.nakamura.http.usercontent.ServerProtectionServiceImpl.java
@Modified public void modified(ComponentContext componentContext) throws NoSuchAlgorithmException, UnsupportedEncodingException, InvalidSyntaxException { @SuppressWarnings("unchecked") Dictionary<String, Object> properties = componentContext.getProperties(); disableProtectionForDevMode = PropertiesUtil.toBoolean(properties.get(DISABLE_XSS_PROTECTION_FOR_UI_DEV), false);/*from w w w .jav a 2 s. com*/ if (disableProtectionForDevMode) { LOGGER.warn("XSS Protection is disabled [modified]"); return; } String[] trustedHosts = PropertiesUtil.toStringArray(properties.get(TRUSTED_HOSTS_CONF), DEFAULT_TRUSTED_HOSTS); Builder<String, String> redirects = ImmutableMap.builder(); Builder<String, String> referrers = ImmutableMap.builder(); for (String h : trustedHosts) { String[] applicationContentHostPair = StringUtils.split(h, "=", 2); if (applicationContentHostPair == null || applicationContentHostPair.length != 2) { throw new IllegalArgumentException("Application Content Host Pair invalid " + h); } applicationContentHostPair[0] = applicationContentHostPair[0].trim(); applicationContentHostPair[1] = applicationContentHostPair[1].trim(); String[] proto = StringUtils.split(applicationContentHostPair[1], ":", 2); if (applicationContentHostPair[0].startsWith("http")) { throw new IllegalArgumentException( "Trusted host must not start with protocol: " + applicationContentHostPair[0]); } if (proto == null || proto.length != 2) { throw new IllegalArgumentException("Content Host Must contain protocol " + h); } String[] hostHeader = StringUtils.split(applicationContentHostPair[0], ":", 2); if (hostHeader == null || hostHeader.length == 0) { throw new IllegalArgumentException("Application Host Must contain port " + h); } // we don't allow redirect onto a different protocol, which implies // the app is on the same protocol as // the content. Also this ensures that the trusted host does not // discriminate on protocol. LOGGER.info("Adding {} {} ", applicationContentHostPair[0], applicationContentHostPair[1]); redirects.put(applicationContentHostPair[0], applicationContentHostPair[1]); if ("http".equals(proto[0])) { if (hostHeader.length > 1 && "80".equals(hostHeader[1])) { referrers.put(applicationContentHostPair[0], "http://" + hostHeader[0]); } else { referrers.put(applicationContentHostPair[0], "http://" + applicationContentHostPair[0]); } } else if ("https".equals(proto[0])) { // requests on default ports will not have the port in the referrer. if (hostHeader.length > 1 && "443".equals(hostHeader[1])) { referrers.put(applicationContentHostPair[0], "https://" + hostHeader[0]); } else { referrers.put(applicationContentHostPair[0], "https://" + applicationContentHostPair[0]); } } else { LOGGER.warn("Protocol was not recognised {} {} ", proto[0], h); throw new IllegalArgumentException("Protocol not recognised " + h); } } applicationContentRedirects = redirects.build(); applicationReferrerHeaders = referrers.build(); safeToStreamPaths = PropertiesUtil.toStringArray(properties.get(TRUSTED_PATHS_CONF), DEFAULT_TRUSTED_PATHS); safeToStreamExactPaths = ImmutableSet.copyOf(PropertiesUtil .toStringArray(properties.get(TRUSTED_EXACT_PATHS_CONF), DEFAULT_TRUSTED_EXACT_PATHS)); postWhiteList = PropertiesUtil.toStringArray(properties.get(WHITELIST_POST_PATHS_CONF), DEFAULT_WHITELIST_POST_PATHS); safeForAnonToPostPaths = PropertiesUtil.toStringArray(properties.get(ANON_WHITELIST_POST_PATHS_CONF), DEFAULT_ANON_WHITELIST_POST_PATHS); String transferSharedSecret = PropertiesUtil.toString(properties.get(TRUSTED_SECRET_CONF), DEFAULT_TRUSTED_SECRET_VALUE); if (DEFAULT_TRUSTED_SECRET_VALUE.equals(transferSharedSecret)) { LOGGER.error("Configuration Error ============================="); LOGGER.error("Configuration Error: Please set {} to secure Content Server in procuction ", TRUSTED_SECRET_CONF); LOGGER.error("Configuration Error ============================="); } LOGGER.info("Trusted Hosts {}", applicationContentRedirects); LOGGER.info("Trusted Stream Paths {} ", Arrays.toString(safeToStreamPaths)); LOGGER.info("Trusted Stream Resources {} ", safeToStreamExactPaths); LOGGER.info("POST Whitelist {} ", postWhiteList); LOGGER.info("Content Shared Secret [{}] ", transferSharedSecret); transferKeys = new Key[10]; MessageDigest md = MessageDigest.getInstance("SHA-512"); Base64 encoder = new Base64(true); byte[] input = transferSharedSecret.getBytes("UTF-8"); // create a static ring of 10 keys by repeatedly hashing the last key seed // starting with the transferSharedSecret for (int i = 0; i < transferKeys.length; i++) { md.reset(); byte[] data = md.digest(input); transferKeys[i] = new SecretKeySpec(data, HMAC_SHA512); input = encoder.encode(data); } bundleContext = componentContext.getBundleContext(); ServiceReference[] srs = bundleContext.getAllServiceReferences(ServerProtectionValidator.class.getName(), null); if (srs != null) { for (ServiceReference sr : srs) { bindServerProtectionValidator(sr); } } ServiceReference[] srsVeto = bundleContext.getAllServiceReferences(ServerProtectionVeto.class.getName(), null); if (srsVeto != null) { for (ServiceReference sr : srsVeto) { bindServerProtectionVeto(sr); } } }
From source file:org.oscelot.blackboard.lti.Utils.java
public static String getHash(String data, String secret, String algorithm, boolean asHex) { if ((secret == null) || (secret.length() <= 0)) { return ""; }//from ww w . jav a 2 s . c om String hash; // Append the shared secret data = data + secret; // Calculate the hash try { MessageDigest digest = MessageDigest.getInstance(algorithm); digest.reset(); byte hashdata[]; try { hashdata = digest.digest(data.getBytes("UTF-8")); } catch (UnsupportedEncodingException e) { hashdata = digest.digest(data.getBytes()); } if (asHex) { hash = arrayToHexString(hashdata); } else { hash = new String(Base64.encodeBase64(hashdata)); } } catch (NoSuchAlgorithmException e) { hash = ""; } return hash; }
From source file:org.apache.ws.security.components.crypto.CryptoBase.java
/** * Reads the SubjectKeyIdentifier information from the certificate. * <p/>// w w w .ja v a 2 s . c o m * If the the certificate does not contain a SKI extension then * try to compute the SKI according to RFC3280 using the * SHA-1 hash value of the public key. The second method described * in RFC3280 is not support. Also only RSA public keys are supported. * If we cannot compute the SKI throw a WSSecurityException. * * @param cert The certificate to read SKI * @return The byte array containing the binary SKI data */ public byte[] getSKIBytesFromCert(X509Certificate cert) throws WSSecurityException { // // Gets the DER-encoded OCTET string for the extension value (extnValue) // identified by the passed-in oid String. The oid string is represented // by a set of positive whole numbers separated by periods. // byte[] derEncodedValue = cert.getExtensionValue(SKI_OID); if (cert.getVersion() < 3 || derEncodedValue == null) { PublicKey key = cert.getPublicKey(); if (!(key instanceof RSAPublicKey)) { throw new WSSecurityException(1, "noSKIHandling", new Object[] { "Support for RSA key only" }); } byte[] encoded = key.getEncoded(); // remove 22-byte algorithm ID and header byte[] value = new byte[encoded.length - 22]; System.arraycopy(encoded, 22, value, 0, value.length); MessageDigest sha; try { sha = MessageDigest.getInstance("SHA-1"); } catch (NoSuchAlgorithmException ex) { throw new WSSecurityException(WSSecurityException.UNSUPPORTED_SECURITY_TOKEN, "noSKIHandling", new Object[] { "Wrong certificate version (<3) and no SHA1 message digest availabe" }, ex); } sha.reset(); sha.update(value); return sha.digest(); } // // Strip away first four bytes from the DerValue (tag and length of // ExtensionValue OCTET STRING and KeyIdentifier OCTET STRING) // byte abyte0[] = new byte[derEncodedValue.length - 4]; System.arraycopy(derEncodedValue, 4, abyte0, 0, abyte0.length); return abyte0; }