Example usage for java.security MessageDigest getAlgorithm

List of usage examples for java.security MessageDigest getAlgorithm

Introduction

In this page you can find the example usage for java.security MessageDigest getAlgorithm.

Prototype

public final String getAlgorithm() 

Source Link

Document

Returns a string that identifies the algorithm, independent of implementation details.

Usage

From source file:org.fcrepo.http.api.FedoraBatch.java

/**
 * Retrieve multiple datastream bitstreams in a single request as a
 * multipart/mixed response.//from  ww  w .jav a 2  s.  c o  m
 *
 * @param pathList
 * @param requestedChildren
 * @param request
 * @return
 * @throws RepositoryException
 * @throws NoSuchAlgorithmException
 */
@GET
@Produces("multipart/mixed")
@Timed
public Response getBinaryContents(@PathParam("path") final List<PathSegment> pathList,
        @QueryParam("child") final List<String> requestedChildren, @Context final Request request)
        throws RepositoryException, NoSuchAlgorithmException {

    final List<Datastream> datastreams = new ArrayList<>();

    try {
        final String path = toPath(pathList);
        // TODO: wrap some of this JCR logic in an fcrepo abstraction;

        final Node node = nodeService.getObject(session, path).getNode();

        Date date = new Date();

        final MessageDigest digest = MessageDigest.getInstance("SHA-1");

        final NodeIterator ni;

        if (requestedChildren.isEmpty()) {
            ni = node.getNodes();
        } else {
            ni = node.getNodes(requestedChildren.toArray(new String[requestedChildren.size()]));
        }

        // complain if no children found
        if (ni.getSize() == 0) {
            return status(Status.BAD_REQUEST).build();
        }

        // transform the nodes into datastreams, and calculate cache header
        // data
        while (ni.hasNext()) {

            final Node dsNode = ni.nextNode();
            final Datastream ds = datastreamService.asDatastream(dsNode);

            if (!ds.hasContent()) {
                continue;
            }

            digest.update(ds.getContentDigest().toString().getBytes(UTF_8));

            if (ds.getLastModifiedDate().after(date)) {
                date = ds.getLastModifiedDate();
            }

            datastreams.add(ds);
        }

        final URI digestURI = ContentDigest.asURI(digest.getAlgorithm(), digest.digest());
        final EntityTag etag = new EntityTag(digestURI.toString());

        final Date roundedDate = new Date();
        roundedDate.setTime(date.getTime() - date.getTime() % 1000);

        ResponseBuilder builder = request.evaluatePreconditions(roundedDate, etag);

        final CacheControl cc = new CacheControl();
        cc.setMaxAge(0);
        cc.setMustRevalidate(true);

        if (builder == null) {
            final MultiPart multipart = new MultiPart();

            for (final Datastream ds : datastreams) {
                final BodyPart bodyPart = new BodyPart(ds.getContent(), MediaType.valueOf(ds.getMimeType()));
                bodyPart.setContentDisposition(ContentDisposition.type(ATTACHMENT).fileName(ds.getPath())
                        .creationDate(ds.getCreatedDate()).modificationDate(ds.getLastModifiedDate())
                        .size(ds.getContentSize()).build());
                multipart.bodyPart(bodyPart);
            }

            builder = ok(multipart, MULTIPART_FORM_DATA);
        }

        return builder.cacheControl(cc).lastModified(date).tag(etag).build();

    } finally {
        session.logout();
    }
}

From source file:org.jscep.client.Client.java

/**
 * Sends a CSR to the SCEP server for enrolling in a PKI.
 * <p>//w  w w  .  j  a  v a 2s .c  o m
 * This method enrols the provider <tt>CertificationRequest</tt> into the
 * PKI represented by the SCEP server.
 *
 * @param identity
 *            the identity of the client.
 * @param key
 *            the private key to sign the SCEP request.
 * @param csr
 *            the CSR to enrol.
 * @param profile
 *            the SCEP server profile.
 * @return the certificate store returned by the server.
 * @throws ClientException
 *             if any client error occurs.
 * @throws TransactionException
 *             if there is a problem with the SCEP transaction.
 * @see CertStoreInspector
 */
public EnrollmentResponse enrol(final X509Certificate identity, final PrivateKey key,
        final PKCS10CertificationRequest csr, final String profile)
        throws ClientException, TransactionException {
    LOGGER.debug("Enrolling certificate with CA");

    if (isSelfSigned(identity)) {
        LOGGER.debug("Certificate is self-signed");
        X500Name csrSubject = csr.getSubject();
        X500Name idSubject = X500Utils.toX500Name(identity.getSubjectX500Principal());

        if (!csrSubject.equals(idSubject)) {
            LOGGER.error(
                    "The self-signed certificate MUST use the same subject name as in the PKCS#10 request.");
        }
    }
    // TRANSACTIONAL
    // Certificate enrollment
    final Transport transport = createTransport(profile);
    PkiMessageEncoder encoder = getEncoder(identity, key, profile);
    PkiMessageDecoder decoder = getDecoder(identity, key, profile);
    final EnrollmentTransaction trans = new EnrollmentTransaction(transport, encoder, decoder, csr);

    try {
        MessageDigest digest = getCaCapabilities(profile).getStrongestMessageDigest();
        byte[] hash = digest.digest(csr.getEncoded());

        LOGGER.debug("{} PKCS#10 Fingerprint: [{}]", digest.getAlgorithm(), Hex.encodeHexString(hash));
    } catch (IOException e) {
        LOGGER.error("Error getting encoded CSR", e);
    }

    return send(trans);
}

From source file:org.lockss.hasher.TestSimpleHasher.java

public void testMakeDigest() throws Exception {
    HasherResult result = new HasherResult();
    MessageDigest digest = new SimpleHasher(null)
            .makeDigestAndRecordStream(LcapMessage.getDefaultHashAlgorithm(), false, result);

    assertTrue(digest instanceof MessageDigest);
    assertFalse(digest instanceof RecordingMessageDigest);
    assertEquals(LcapMessage.getDefaultHashAlgorithm(), digest.getAlgorithm());
    assertEquals(20, digest.getDigestLength());
    assertNull(result.getRecordFile());//w  w  w  . j  a v  a  2s  . c o m
    assertNull(result.getRecordStream());

    result = new HasherResult();
    digest = new SimpleHasher(null).makeDigestAndRecordStream(LcapMessage.getDefaultHashAlgorithm(), true,
            result);

    assertTrue(digest instanceof MessageDigest);
    assertTrue(digest instanceof RecordingMessageDigest);
    assertEquals("SHA-1", digest.getAlgorithm());
    assertEquals(20, digest.getDigestLength());
    assertTrue(result.getRecordFile().getName().startsWith("HashCUS"));
    assertTrue(result.getRecordFile().getName().endsWith(".tmp"));
    assertNotNull(result.getRecordStream());
    // Clean up the result file.
    result.getRecordFile().delete();
    IOUtil.safeClose(result.getRecordStream());

    result = new HasherResult();
    digest = new SimpleHasher(null).makeDigestAndRecordStream("SHA", false, result);

    assertTrue(digest instanceof MessageDigest);
    assertFalse(digest instanceof RecordingMessageDigest);
    assertEquals("SHA", digest.getAlgorithm());
    assertEquals(20, digest.getDigestLength());
    assertNull(result.getRecordFile());
    assertNull(result.getRecordStream());

    result = new HasherResult();
    digest = new SimpleHasher(null).makeDigestAndRecordStream("SHA1", false, result);

    assertTrue(digest instanceof MessageDigest);
    assertFalse(digest instanceof RecordingMessageDigest);
    assertEquals("SHA1", digest.getAlgorithm());
    assertEquals(20, digest.getDigestLength());
    assertNull(result.getRecordFile());
    assertNull(result.getRecordStream());

    result = new HasherResult();
    digest = new SimpleHasher(null).makeDigestAndRecordStream("MD5", false, result);

    assertTrue(digest instanceof MessageDigest);
    assertFalse(digest instanceof RecordingMessageDigest);
    assertEquals("MD5", digest.getAlgorithm());
    assertEquals(16, digest.getDigestLength());
    assertNull(result.getRecordFile());
    assertNull(result.getRecordStream());

    result = new HasherResult();
    digest = new SimpleHasher(null).makeDigestAndRecordStream("SHA-256", false, result);

    assertTrue(digest instanceof MessageDigest);
    assertFalse(digest instanceof RecordingMessageDigest);
    assertEquals("SHA-256", digest.getAlgorithm());
    assertEquals(32, digest.getDigestLength());
    assertNull(result.getRecordFile());
    assertNull(result.getRecordStream());

    try {
        digest = new SimpleHasher(null).makeDigestAndRecordStream(null, false, result);
        fail("Null algorithm should throw NullPointerException");
    } catch (NullPointerException npe) {
        // Expected.
    }

    try {
        digest = new SimpleHasher(null).makeDigestAndRecordStream("SHA256", false, result);
        fail("Invalid algorithm should throw NoSuchAlgorithmException");
    } catch (NoSuchAlgorithmException nsae) {
        // Expected.
    }

    try {
        digest = new SimpleHasher(null).makeDigestAndRecordStream("FGL", false, result);
        fail("Invalid algorithm should throw NoSuchAlgorithmException");
    } catch (NoSuchAlgorithmException nsae) {
        // Expected.
    }
}

From source file:org.projectforge.common.Crypt.java

private static String encode(final String s, final String alg) {
    try {//from w w  w  . jav a 2s.c  om
        final MessageDigest md = MessageDigest.getInstance(alg);
        md.reset();
        md.update(s.getBytes());
        final byte[] d = md.digest();

        String ret = "";

        for (int val : d) {
            final char[] hex = new char[] { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C',
                    'D', 'E', 'F' };
            if (val < 0) {
                val = 256 + val;
            }
            final char hi = hex[val / 16];
            final char lo = hex[val % 16];
            ret = hi + "" + lo + ret;
        }
        return md.getAlgorithm() + '{' + ret + '}';
    } catch (final NoSuchAlgorithmException ex) {
        log.fatal(ex);
        return "NONE{" + s + "}";
    }
}

From source file:org.sonatype.nexus.proxy.maven.maven2.M2GroupRepository.java

protected void storeMergedMetadataItemDigest(ResourceStoreRequest request, MessageDigest digest,
        List<StorageItem> sources)
        throws IOException, UnsupportedStorageOperationException, IllegalOperationException {
    String digestFileName = request.getRequestPath() + "." + digest.getAlgorithm().toLowerCase();

    // see nexus-configuration mime-types.properties (defaulted to text/plain, as central reports them)
    String mimeType = getMimeUtil().getMimeType(digestFileName);

    byte[] bytes = (new String(Hex.encodeHex(digest.digest())) + "\n").getBytes("UTF-8");

    ContentLocator contentLocator = new ByteArrayContentLocator(bytes, mimeType);

    ResourceStoreRequest req = new ResourceStoreRequest(digestFileName);

    req.getRequestContext().setParentContext(request.getRequestContext());

    // Metadata checksum files are not composite ones, they are derivatives of the Metadata (and metadata file _is_
    // composite one)
    DefaultStorageFileItem digestFileItem = new DefaultStorageFileItem(this, req, true, false, contentLocator);

    storeItem(false, digestFileItem);/*from  w  w  w . jav a 2 s.  c o m*/
}

From source file:utils.Hash.java

/**
 * Outputs a MD5 digest//from w ww. j av a  2s  . co m
 * @param toHash String to hash
 * @return Hashed String
 */
public static String md5ThisString(String toHash) {
    String hashed = null;
    byte[] byteArray = new byte[512];
    MessageDigest md;
    try {
        md = MessageDigest.getInstance("MD5");
        log.debug("Hashing Value With " + md.getAlgorithm());
        byteArray = toHash.getBytes();
        md.update(byteArray);
        byteArray = md.digest();
    } catch (NoSuchAlgorithmException e) {
        log.fatal("Could not Find MD5 Algorithm: " + e.toString());
    }
    hashed = new String(byteArray, Charset.forName("US-ASCII"));

    return hashed;
}

From source file:utils.Hash.java

/**
 * Outputs a SHA256 digest//from   w  ww  .  j  a v  a2s  . co m
 * @param toHash String to hash
 * @return Hashed string
 */
public static String thisString(String toHash) {
    String hashed = null;
    byte[] byteArray = new byte[256];
    MessageDigest md;
    try {
        md = MessageDigest.getInstance("SHA");
        log.debug("Hashing Value With " + md.getAlgorithm());
        byteArray = toHash.getBytes();
        md.update(byteArray);
        byteArray = md.digest();
    } catch (NoSuchAlgorithmException e) {
        log.fatal("Could not Find SHA Algorithm: " + e.toString());
    }
    hashed = new String(byteArray, Charset.forName("US-ASCII"));

    return hashed;
}