List of usage examples for java.security MessageDigest reset
public void reset()
From source file:org.wso2.carbon.webapp.ext.cxf.crypto.CXFServerCrypto.java
/** * @see org.apache.ws.security.components.crypto.Crypto#getSKIBytesFromCert(java.security.cert.X509Certificate) *//* w ww .j a v a 2s . com*/ 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:org.wso2.carbon.dataservices.core.auth.JWTAuthorizationProvider.java
/** * Get the alias for the X509 certificate thumb * @param thumb//from ww w . j a v a 2s . c o m * @param keyStore * @return * @throws org.apache.axis2.AxisFault */ private String getAliasForX509CertThumb(byte[] thumb, KeyStore keyStore) throws AxisFault { Certificate cert = null; MessageDigest sha = null; try { sha = MessageDigest.getInstance("SHA-1"); } catch (NoSuchAlgorithmException e1) { log.error("noSHA1availabe"); throw new AxisFault("noSHA1availabe"); } try { for (Enumeration<String> e = keyStore.aliases(); e.hasMoreElements();) { String alias = (String) e.nextElement(); Certificate[] certs = keyStore.getCertificateChain(alias); if (certs == null || certs.length == 0) { // no cert chain, so lets check if getCertificate gives us a result. cert = keyStore.getCertificate(alias); if (cert == null) { return null; } } else { cert = certs[0]; } if (!(cert instanceof X509Certificate)) { continue; } sha.reset(); try { sha.update(cert.getEncoded()); } catch (CertificateEncodingException e1) { log.error("Error encoding certificate"); throw new AxisFault("Error encoding certificate"); } byte[] data = sha.digest(); if (new String(thumb).equals(hexify(data))) { return alias; } } } catch (KeyStoreException e) { log.error("KeyStore exception while getting alias for X509CertThumb"); throw new AxisFault("KeyStore exception while getting alias for X509CertThumb"); } return null; }
From source file:org.dcm4chee.storage.tar.TarContainerProvider.java
@Override public void extractEntries(RetrieveContext ctx, String name, ExtractTask extractTask, InputStream in) throws IOException { TarArchiveInputStream tar = new TarArchiveInputStream(in); TarArchiveEntry entry = skipDirectoryEntries(tar); if (entry == null) throw new IOException("No entries in " + name); String entryName = entry.getName(); Map<String, byte[]> checksums = null; String checksumEntry = container.getChecksumEntry(); MessageDigest digest = null; if (checksumEntry != null) { if (checksumEntry.equals(entryName)) { try { digest = MessageDigest .getInstance(ctx.getStorageSystem().getStorageSystemGroup().getDigestAlgorithm()); } catch (NoSuchAlgorithmException e) { throw new RuntimeException(e); }/*from www . j a va 2 s . c o m*/ checksums = ContainerEntry.readChecksumsFrom(tar); } else LOG.warn("Misssing checksum entry in %s", name); entry = skipDirectoryEntries(tar); } for (; entry != null; entry = skipDirectoryEntries(tar)) { entryName = entry.getName(); InputStream in0 = tar; byte[] checksum = null; if (checksums != null && digest != null) { checksum = checksums.remove(entryName); if (checksum == null) throw new ChecksumException( "Missing checksum for container entry: " + entryName + " in " + name); digest.reset(); in0 = new DigestInputStream(tar, digest); } extractTask.copyStream(entryName, in0); if (checksums != null && digest != null) { if (!Arrays.equals(digest.digest(), checksum)) { throw new ChecksumException( "Checksums do not match for container entry: " + entry.getName() + " in " + name); } } extractTask.entryExtracted(entryName); } }
From source file:com.yoctopuce.YoctoAPI.YCallbackHub.java
private void loadCallbackCache(InputStream in) throws YAPI_Exception, IOException { ByteArrayOutputStream buffer = new ByteArrayOutputStream(); int nRead;//from w w w . j a v a2 s . c o m byte[] data = new byte[16384]; while ((nRead = in.read(data, 0, data.length)) != -1) { buffer.write(data, 0, nRead); } buffer.flush(); String data_str = buffer.toString(_yctx._defaultEncoding); if (data_str.length() == 0) { String errmsg = "RegisterHub(callback) used without posting YoctoAPI data"; _output("\n!YoctoAPI:" + errmsg + "\n"); _callbackCache = null; throw new YAPI_Exception(YAPI.IO_ERROR, errmsg); } else { try { _callbackCache = new JSONObject(data_str); } catch (JSONException ex) { String errmsg = "invalid data:[\n" + ex.toString() + data_str + "\n]"; _output("\n!YoctoAPI:" + errmsg + "\n"); _callbackCache = null; throw new YAPI_Exception(YAPI.IO_ERROR, errmsg); } if (!_http_params.getPass().equals("")) { MessageDigest mdigest; try { mdigest = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException ex) { throw new YAPI_Exception(YAPI.NOT_SUPPORTED, "No MD5 provider"); } // callback data signed, verify signature if (!_callbackCache.has("sign")) { String errmsg = "missing signature from incoming YoctoHub (callback password required)"; _output("\n!YoctoAPI:" + errmsg + "\n"); _callbackCache = null; throw new YAPI_Exception(YAPI.UNAUTHORIZED, errmsg); } String sign = _callbackCache.optString("sign"); String pass = _http_params.getPass(); String salt; if (pass.length() == 32) { salt = pass.toLowerCase(); } else { mdigest.reset(); mdigest.update(pass.getBytes(_yctx._deviceCharset)); byte[] md5pass = mdigest.digest(); salt = YAPIContext._bytesToHexStr(md5pass, 0, md5pass.length); } data_str = data_str.replace(sign, salt); mdigest.reset(); mdigest.update(data_str.getBytes(_yctx._deviceCharset)); byte[] md5 = mdigest.digest(); String check = YAPIContext._bytesToHexStr(md5, 0, md5.length); if (!check.equals(sign)) { String errmsg = "invalid signature from incoming YoctoHub (invalid callback password)"; _output("\n!YoctoAPI:" + errmsg + "\n"); _callbackCache = null; throw new YAPI_Exception(YAPI.UNAUTHORIZED, errmsg); } } } }
From source file:org.cloudifysource.dsl.internal.tools.download.ChecksumVerifier.java
/** * calculates the file hash. //from w w w. j a v a 2s . com * @return * the file hash. * @throws ChecksumVerifierException * if calculation fails. * */ public String calculateFileDigest() throws ChecksumVerifierException { final String hashFileName = this.hashFile.getName(); final String hashFileExt = getFileExtention(hashFileName); final String checksumAlgorithm = ChecksumAlgorithm.toAlgorithm(hashFileExt); if (checksumAlgorithm == null) { throw new ChecksumVerifierException("Validation checksum method " + hashFileExt + " is not supported." + " Hash file extention should match one of the following values: " + ChecksumAlgorithm.names()); } MessageDigest messageDigest; try { messageDigest = MessageDigest.getInstance(checksumAlgorithm); } catch (NoSuchAlgorithmException e) { throw new ChecksumVerifierException( "Algorithm " + checksumAlgorithm + " does not exist or is not supported.", e); } if (messageDigest == null) { throw new ChecksumVerifierException( "Unable to create Message Digest for algorithm " + checksumAlgorithm); } final byte[] buffer = new byte[(int) this.file.length()]; FileInputStream fis = null; try { fis = new FileInputStream(this.file); fis.read(buffer); } catch (FileNotFoundException e) { logger.warning("Could not find file to digest."); throw new IllegalStateException("Resource was not found.", e); } catch (IOException e) { throw new ChecksumVerifierException("Failed calculating file hash.", e); } finally { IOUtils.closeQuietly(fis); } messageDigest.reset(); messageDigest.update(buffer); final byte[] digest = messageDigest.digest(); return Hex.encodeHexString(digest); }
From source file:edu.byu.wso2.apim.extensions.JWTDecoder.java
private String getAliasForX509CertThumb(KeyStore keyStore, byte[] thumb, MessageContext synapseContext) { SynapseLog synLog = getLog(synapseContext); Certificate cert = null;/*from ww w .jav a 2 s. c om*/ MessageDigest sha = null; try { sha = MessageDigest.getInstance("SHA-1"); } catch (NoSuchAlgorithmException e) { handleSigVerificationException(e, synapseContext); } try { for (Enumeration<String> e = keyStore.aliases(); e.hasMoreElements();) { String alias = e.nextElement(); Certificate[] certs = keyStore.getCertificateChain(alias); if (certs == null || certs.length == 0) { // no cert chain, so lets check if getCertificate gives us a result. cert = keyStore.getCertificate(alias); if (cert == null) { return null; } } else { cert = certs[0]; } if (!(cert instanceof X509Certificate)) { continue; } sha.reset(); try { sha.update(cert.getEncoded()); } catch (CertificateEncodingException e1) { //throw new Exception("Error encoding certificate"); } byte[] data = sha.digest(); if (new String(thumb).equals(hexify(data))) { if (synLog.isTraceOrDebugEnabled()) { synLog.traceOrDebug("Found matching alias: " + alias); } return alias; } } } catch (KeyStoreException e) { if (log.isErrorEnabled()) { log.error("Error getting alias from keystore", e); } } return null; }
From source file:it.crs4.seal.read_sort.FastaChecksummer.java
public void calculate() throws FormatException, java.io.IOException { if (input == null) throw new IllegalStateException("FastaChecksummer input not set"); contigHashes = new HashMap<String, ChecksumEntry>(); String currentContig = null;// w w w .j a va 2s. c o m java.security.MessageDigest hasher = null; try { hasher = java.security.MessageDigest.getInstance(checksumAlgorithm); } catch (java.security.NoSuchAlgorithmException e) { throw new RuntimeException( "Unexpected NoSuchAlgorithmException when asking for " + checksumAlgorithm + " algorithm"); } String line = input.readLine(); if (line == null) throw new FormatException("empty Fasta"); try { while (line != null) { if (line.startsWith(">")) // start a new contig { if (currentContig != null) { // Hadoop 0.20,2 ships with Apache commons version 1.3, which doesn't // have encodeHexString String cs = new String(Hex.encodeHex(hasher.digest())); contigHashes.put(currentContig, new ChecksumEntry(currentContig, cs)); } Matcher m = ContigNamePattern.matcher(line); if (m.matches()) { currentContig = m.group(1); hasher.reset(); } else throw new FormatException("Unexpected contig name format: " + line); } else { if (currentContig == null) throw new FormatException( "Sequence outside any fasta record (header is missing). Line: " + line); else hasher.update(line.getBytes("US-ASCII")); } line = input.readLine(); } if (currentContig != null) // store the last contig { String cs = new String(Hex.encodeHex(hasher.digest())); contigHashes.put(currentContig, new ChecksumEntry(currentContig, cs)); } } catch (java.io.UnsupportedEncodingException e) { throw new RuntimeException("Unexpected UnsupportedEncodingException! Line: " + line); } }
From source file:org.panbox.desktop.common.sharemgmt.ShareManagerImpl.java
private IPerson getOwnerForShare(MessageDigest md, byte[] ownerFp, VolumeParams p) { IPerson owner = null;/*from ww w . j a va2s . c o m*/ for (PanboxContact contact : identity.getAddressbook().getContacts()) { byte[] c = md.digest(contact.getCertSign().getPublicKey().getEncoded()); md.reset(); if (Arrays.equals(ownerFp, c)) { owner = contact; p.setOwnerAlias(owner.getEmail()).setOwnerSignatureKey(owner.getPublicKeySign()); break; } } return owner; }
From source file:org.jasig.resource.aggr.ResourcesAggregatorImpl.java
/** * Aggregate the specified Deque of elements into a single element. The provided MessageDigest is used for * building the file name based on the hash of the file contents. The callback is used for type specific * operations.//from ww w .j a v a 2 s. c o m */ protected <T extends BasicInclude> T aggregateList(final MessageDigest digest, final Deque<T> elements, final List<File> skinDirectories, final File outputRoot, final File alternateOutput, final String extension, final AggregatorCallback<T> callback) throws IOException { if (null == elements || elements.size() == 0) { return null; } // reference to the head of the list final T headElement = elements.getFirst(); if (elements.size() == 1 && this.resourcesDao.isAbsolute(headElement)) { return headElement; } final File tempFile = File.createTempFile("working.", extension); final File aggregateOutputFile; try { //Make sure we're working with a clean MessageDigest digest.reset(); TrimmingWriter trimmingWriter = null; try { final BufferedOutputStream bufferedFileStream = new BufferedOutputStream( new FileOutputStream(tempFile)); final MessageDigestOutputStream digestStream = new MessageDigestOutputStream(bufferedFileStream, digest); final OutputStreamWriter aggregateWriter = new OutputStreamWriter(digestStream, this.encoding); trimmingWriter = new TrimmingWriter(aggregateWriter); for (final T element : elements) { final File resourceFile = this.findFile(skinDirectories, element.getValue()); FileInputStream fis = null; try { fis = new FileInputStream(resourceFile); final BOMInputStream bomIs = new BOMInputStream(new BufferedInputStream(fis)); if (bomIs.hasBOM()) { logger.debug("Stripping UTF-8 BOM from: " + resourceFile); } final Reader resourceIn = new InputStreamReader(bomIs, this.encoding); if (element.isCompressed()) { IOUtils.copy(resourceIn, trimmingWriter); } else { callback.compress(resourceIn, trimmingWriter); } } catch (IOException e) { throw new IOException( "Failed to read '" + resourceFile + "' for skin: " + skinDirectories.get(0), e); } finally { IOUtils.closeQuietly(fis); } trimmingWriter.write(SystemUtils.LINE_SEPARATOR); } } finally { IOUtils.closeQuietly(trimmingWriter); } if (trimmingWriter.getCharCount() == 0) { return null; } // temp file is created, get checksum final String checksum = Base64.encodeBase64URLSafeString(digest.digest()); digest.reset(); // create a new file name final String newFileName = checksum + extension; // Build the new file name and path if (alternateOutput == null) { final String elementRelativePath = FilenameUtils.getFullPath(headElement.getValue()); final File directoryInOutputRoot = new File(outputRoot, elementRelativePath); // create the same directory structure in the output root directoryInOutputRoot.mkdirs(); aggregateOutputFile = new File(directoryInOutputRoot, newFileName).getCanonicalFile(); } else { aggregateOutputFile = new File(alternateOutput, newFileName).getCanonicalFile(); } //Move the aggregate file into the correct location FileUtils.deleteQuietly(aggregateOutputFile); FileUtils.moveFile(tempFile, aggregateOutputFile); } finally { //Make sure the temp file gets deleted FileUtils.deleteQuietly(tempFile); } final String newResultValue = RelativePath.getRelativePath(outputRoot, aggregateOutputFile); this.logAggregation(elements, newResultValue); return callback.getAggregateElement(newResultValue, elements); }