Example usage for org.bouncycastle.crypto.digests SHA1Digest getDigestSize

List of usage examples for org.bouncycastle.crypto.digests SHA1Digest getDigestSize

Introduction

In this page you can find the example usage for org.bouncycastle.crypto.digests SHA1Digest getDigestSize.

Prototype

public int getDigestSize() 

Source Link

Usage

From source file:ch.bfh.unicert.certimport.CertificateIssuer.java

License:GNU General Public License

public Certificate createClientCertificate(IdentityData id, String keyStorePath, PublicKey pk, int validity,
        String applicationIdentifier, String[] roles, String uniBoardWsdlURL, String uniBoardServiceURL,
        String section) throws CertificateCreationException {

    X509Certificate caCert;/*from   w w w. jav a  2  s. c  o  m*/
    RSAPrivateCrtKey privKey;
    try {
        caCert = this.readIssuerCertificate(this.issuerId);
        privKey = this.readPrivateKey(this.issuerId, this.privKeyPass);
    } catch (KeyStoreException | NoSuchAlgorithmException | UnrecoverableKeyException ex) {
        logger.log(Level.SEVERE, null, ex);
        throw new CertificateCreationException("230 Could not create client certificate. Key error");
    }

    RSAPrivateCrtKeyParameters cipherParams = this.createIssuerCipherParams(privKey);

    X509Certificate clientCert;

    Hashtable extension = new Hashtable();

    extension.put(new DERObjectIdentifier(ExtensionOID.APPLICATION_IDENTIFIER.getOID()),
            new X509Extension(DERBoolean.FALSE, CertificateHelper.stringToDER(applicationIdentifier)));

    String completeRole = "";
    for (String role : roles) {
        completeRole += role + ", ";
    }
    completeRole = completeRole.substring(0, completeRole.length() - 2);
    extension.put(new DERObjectIdentifier(ExtensionOID.ROLE.getOID()),
            new X509Extension(DERBoolean.FALSE, CertificateHelper.stringToDER(completeRole)));

    extension.put(new DERObjectIdentifier(ExtensionOID.IDENTITY_PROVIDER.getOID()),
            new X509Extension(DERBoolean.FALSE, CertificateHelper.stringToDER(id.getIdentityProvider())));

    Map<String, String> extensionMap = new HashMap();
    if (id.getOtherValues() != null) {
        for (Entry<ExtensionOID, String> entry : id.getOtherValues().entrySet()) {
            extension.put(new DERObjectIdentifier(entry.getKey().getOID()),
                    new X509Extension(DERBoolean.FALSE, CertificateHelper.stringToDER(entry.getValue())));
            extensionMap.put(entry.getKey().getName(), entry.getValue());
        }
    }

    try {

        String x509NameString = "";
        x509NameString += "CN=" + id.getCommonName();

        if (id.getSurname() != null && !id.getSurname().equals("")) {
            x509NameString += ", SURNAME=" + id.getSurname();
        }
        if (id.getGivenName() != null && !id.getGivenName().equals("")) {
            x509NameString += ", GIVENNAME=" + id.getGivenName();
        }
        if (id.getUniqueIdentifier() != null && !id.getUniqueIdentifier().equals("")) {
            x509NameString += ", UID=" + id.getUniqueIdentifier();
        }
        if (id.getOrganisation() != null && !id.getOrganisation().equals("")) {
            x509NameString += ", O=" + id.getOrganisation();
        }
        if (id.getOrganisationUnit() != null && !id.getOrganisationUnit().equals("")) {
            x509NameString += ", OU=" + id.getOrganisationUnit();
        }
        if (id.getCountryName() != null && !id.getCountryName().equals("")) {
            x509NameString += ", C=" + id.getCountryName();
        }
        if (id.getState() != null && !id.getState().equals("")) {
            x509NameString += ", ST=" + id.getState();
        }
        if (id.getLocality() != null && !id.getLocality().equals("")) {
            x509NameString += ", L=" + id.getLocality();
        }

        X509Name x509Name = new X509Name(x509NameString);

        V3TBSCertificateGenerator certGen = new V3TBSCertificateGenerator();
        certGen.setSerialNumber(new DERInteger(BigInteger.valueOf(System.currentTimeMillis())));
        certGen.setIssuer(PrincipalUtil.getSubjectX509Principal(caCert));
        certGen.setSubject(x509Name);
        certGen.setExtensions(new X509Extensions(extension));
        DERObjectIdentifier sigOID = new DERObjectIdentifier("1.2.840.113549.1.1.5");
        AlgorithmIdentifier sigAlgId = new AlgorithmIdentifier(sigOID, new DERNull());
        certGen.setSignature(sigAlgId);
        certGen.setSubjectPublicKeyInfo(new SubjectPublicKeyInfo(
                (ASN1Sequence) new ASN1InputStream(new ByteArrayInputStream(pk.getEncoded())).readObject()));
        certGen.setStartDate(new Time(new Date(System.currentTimeMillis())));
        certGen.setEndDate(new Time(getExpiryDate(validity).getTime()));
        TBSCertificateStructure tbsCert = certGen.generateTBSCertificate();

        //Sign certificate
        SHA1Digest digester = new SHA1Digest();
        AsymmetricBlockCipher rsa = new PKCS1Encoding(new RSAEngine());
        ByteArrayOutputStream bOut = new ByteArrayOutputStream();
        DEROutputStream dOut = new DEROutputStream(bOut);
        dOut.writeObject(tbsCert);
        byte[] signature;
        byte[] certBlock = bOut.toByteArray();
        // first create digest
        digester.update(certBlock, 0, certBlock.length);
        byte[] hash = new byte[digester.getDigestSize()];
        digester.doFinal(hash, 0);
        // then sign it
        rsa.init(true, cipherParams);
        DigestInfo dInfo = new DigestInfo(new AlgorithmIdentifier(X509ObjectIdentifiers.id_SHA1, null), hash);
        byte[] digest = dInfo.getEncoded(ASN1Encodable.DER);
        signature = rsa.processBlock(digest, 0, digest.length);

        ASN1EncodableVector v = new ASN1EncodableVector();
        v.add(tbsCert);
        v.add(sigAlgId);
        v.add(new DERBitString(signature));

        // Create CRT data structure
        clientCert = new X509CertificateObject(new X509CertificateStructure(new DERSequence(v)));
        clientCert.verify(caCert.getPublicKey());
    } catch (IOException | InvalidCipherTextException | CertificateException | NoSuchAlgorithmException
            | InvalidKeyException | NoSuchProviderException | SignatureException e) {
        logger.log(Level.SEVERE, "Could not create client certificate: {0}", new Object[] { e.getMessage() });
        throw new CertificateCreationException("230 Could not create client certificate");
    }

    Certificate cert = new Certificate(clientCert, id.getCommonName(), id.getUniqueIdentifier(),
            id.getOrganisation(), id.getOrganisationUnit(), id.getCountryName(), id.getState(),
            id.getLocality(), id.getSurname(), id.getGivenName(), applicationIdentifier, roles,
            id.getIdentityProvider(), extensionMap);

    //post message on UniBoard if corresponding JNDI parameter is defined
    postOnUniBoard(cert, uniBoardWsdlURL, uniBoardServiceURL, section, (RSAPublicKey) caCert.getPublicKey(),
            privKey);

    return cert;

}

From source file:ch.bfh.unicert.issuer.CertificateIssuerBean.java

License:GNU General Public License

/**
 * Actually creates the requestor certificate.
 *
 * @param id requestor identity data/*  www. j a va  2s.c om*/
 * @param caCert certificate of the certification authority
 * @param cipherParams issuer private key parameters used for signing
 * @param pk public key of the requestor to certify
 * @param expiry the expiry date
 * @param applicationIdentifier the application identifier for which te certificate is issued
 * @param role role for which the certificate is issued
 * @return the certificate object containing the X509 certificate
 * @throws CertificateCreationException if an error occurs
 */
private Certificate createClientCertificate(IdentityData id, X509Certificate caCert,
        CipherParameters cipherParams, PublicKey pk, Calendar expiry, String applicationIdentifier,
        String[] roles) throws CertificateCreationException {

    X509Certificate clientCert;

    Hashtable extension = new Hashtable();

    extension.put(new DERObjectIdentifier(ExtensionOID.APPLICATION_IDENTIFIER.getOID()),
            new X509Extension(DERBoolean.FALSE, CertificateHelper.stringToDER(applicationIdentifier)));

    String completeRole = "";
    for (String role : roles) {
        completeRole += role + ", ";
    }
    completeRole = completeRole.substring(0, completeRole.length() - 2);
    extension.put(new DERObjectIdentifier(ExtensionOID.ROLE.getOID()),
            new X509Extension(DERBoolean.FALSE, CertificateHelper.stringToDER(completeRole)));

    extension.put(new DERObjectIdentifier(ExtensionOID.IDENTITY_PROVIDER.getOID()),
            new X509Extension(DERBoolean.FALSE, CertificateHelper.stringToDER(id.getIdentityProvider())));

    Map<String, String> extensionMap = new HashMap();
    if (id.getOtherValues() != null) {
        for (Entry<ExtensionOID, String> entry : id.getOtherValues().entrySet()) {
            extension.put(new DERObjectIdentifier(entry.getKey().getOID()),
                    new X509Extension(DERBoolean.FALSE, CertificateHelper.stringToDER(entry.getValue())));
            extensionMap.put(entry.getKey().getName(), entry.getValue());
        }
    }

    try {

        String x509NameString = "";
        x509NameString += "CN=" + id.getCommonName();

        if (id.getSurname() != null && !id.getSurname().equals("")) {
            x509NameString += ", SURNAME=" + id.getSurname();
        }
        if (id.getGivenName() != null && !id.getGivenName().equals("")) {
            x509NameString += ", GIVENNAME=" + id.getGivenName();
        }
        if (id.getUniqueIdentifier() != null && !id.getUniqueIdentifier().equals("")) {
            x509NameString += ", UID=" + id.getUniqueIdentifier();
        }
        if (id.getOrganisation() != null && !id.getOrganisation().equals("")) {
            x509NameString += ", O=" + id.getOrganisation();
        }
        if (id.getOrganisationUnit() != null && !id.getOrganisationUnit().equals("")) {
            x509NameString += ", OU=" + id.getOrganisationUnit();
        }
        if (id.getCountryName() != null && !id.getCountryName().equals("")) {
            x509NameString += ", C=" + id.getCountryName();
        }
        if (id.getState() != null && !id.getState().equals("")) {
            x509NameString += ", ST=" + id.getState();
        }
        if (id.getLocality() != null && !id.getLocality().equals("")) {
            x509NameString += ", L=" + id.getLocality();
        }

        X509Name x509Name = new X509Name(x509NameString);

        V3TBSCertificateGenerator certGen = new V3TBSCertificateGenerator();
        certGen.setSerialNumber(new DERInteger(BigInteger.valueOf(System.currentTimeMillis())));
        certGen.setIssuer(PrincipalUtil.getSubjectX509Principal(caCert));
        certGen.setSubject(x509Name);
        certGen.setExtensions(new X509Extensions(extension));
        DERObjectIdentifier sigOID = new DERObjectIdentifier("1.2.840.113549.1.1.5");
        AlgorithmIdentifier sigAlgId = new AlgorithmIdentifier(sigOID, new DERNull());
        certGen.setSignature(sigAlgId);
        certGen.setSubjectPublicKeyInfo(new SubjectPublicKeyInfo(
                (ASN1Sequence) new ASN1InputStream(new ByteArrayInputStream(pk.getEncoded())).readObject()));
        certGen.setStartDate(new Time(new Date(System.currentTimeMillis())));
        certGen.setEndDate(new Time(expiry.getTime()));
        TBSCertificateStructure tbsCert = certGen.generateTBSCertificate();

        //Sign certificate
        SHA1Digest digester = new SHA1Digest();
        AsymmetricBlockCipher rsa = new PKCS1Encoding(new RSAEngine());
        ByteArrayOutputStream bOut = new ByteArrayOutputStream();
        DEROutputStream dOut = new DEROutputStream(bOut);
        dOut.writeObject(tbsCert);
        byte[] signature;
        byte[] certBlock = bOut.toByteArray();
        // first create digest
        digester.update(certBlock, 0, certBlock.length);
        byte[] hash = new byte[digester.getDigestSize()];
        digester.doFinal(hash, 0);
        // then sign it
        rsa.init(true, cipherParams);
        DigestInfo dInfo = new DigestInfo(new AlgorithmIdentifier(X509ObjectIdentifiers.id_SHA1, null), hash);
        byte[] digest = dInfo.getEncoded(ASN1Encodable.DER);
        signature = rsa.processBlock(digest, 0, digest.length);

        ASN1EncodableVector v = new ASN1EncodableVector();
        v.add(tbsCert);
        v.add(sigAlgId);
        v.add(new DERBitString(signature));

        // Create CRT data structure
        clientCert = new X509CertificateObject(new X509CertificateStructure(new DERSequence(v)));
        clientCert.verify(caCert.getPublicKey());
    } catch (IOException | CertificateException | NoSuchAlgorithmException | InvalidKeyException
            | NoSuchProviderException | InvalidCipherTextException | SignatureException e) {
        logger.log(Level.SEVERE, "Could not create client certificate: {0}", new Object[] { e.getMessage() });
        throw new CertificateCreationException("230 Could not create client certificate");
    }

    return new Certificate(clientCert, id.getCommonName(), id.getUniqueIdentifier(), id.getOrganisation(),
            id.getOrganisationUnit(), id.getCountryName(), id.getState(), id.getLocality(), id.getSurname(),
            id.getGivenName(), applicationIdentifier, roles, id.getIdentityProvider(), extensionMap);

}

From source file:com.identarian.infocard.opensso.rp.InfocardClaims.java

License:CDDL license

public static String friendlyPPID(String ppid) {
    // code map/* w w  w.j ava  2 s  .  co  m*/
    char[] ss = { 'Q', 'L', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'J',
            'K', 'M', 'N', 'P', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z' };

    // base 64 decoding
    byte[] b = Base64.decode(ppid.getBytes());

    // sha1 decoding
    SHA1Digest digEng = new SHA1Digest();
    digEng.update(b, 0, b.length);
    byte[] b1 = new byte[digEng.getDigestSize()];
    digEng.doFinal(b1, 0);

    // convert the bytes to ints
    StringBuffer sb = new StringBuffer();
    for (int i = 0; i < 10; i++) {
        int ii = byte2int(b1[i]) % 32;
        if (i == 3 || i == 7) {
            sb.append("-");
        }
        // mapping of the int to mapping code
        sb.append(ss[ii]);
    }
    return sb.toString();
}

From source file:com.yacme.ext.oxsit.cust_it.comp.security.cert.X509CertDisplayBase_IT.java

License:Open Source License

protected void initThumbPrints() {
    //obtain a byte block of the entire certificate data
    ByteArrayOutputStream bOut = new ByteArrayOutputStream();
    DEROutputStream dOut = new DEROutputStream(bOut);
    try {/*from w w  w . j av  a 2 s.c o  m*/
        dOut.writeObject(m_aX509);
        byte[] certBlock = bOut.toByteArray();

        //now compute the certificate SHA1 & MD5 digest
        SHA1Digest digsha1 = new SHA1Digest();
        digsha1.update(certBlock, 0, certBlock.length);
        byte[] hashsha1 = new byte[digsha1.getDigestSize()];
        digsha1.doFinal(hashsha1, 0);
        m_sSHA1Thumbprint = Helpers.printHexBytes(hashsha1);
        MD5Digest digmd5 = new MD5Digest();
        digmd5.update(certBlock, 0, certBlock.length);
        byte[] hashmd5 = new byte[digmd5.getDigestSize()];
        digmd5.doFinal(hashmd5, 0);
        m_sMD5Thumbprint = Helpers.printHexBytes(hashmd5);
    } catch (IOException e) {
        m_aLogger.severe("initThumbPrints", e);
    }
}

From source file:cybervillains.ca.ThumbprintUtil.java

License:Open Source License

/**
 * Generates a SHA1 thumbprint of a certificate for long-term mapping.
 * //from  w w  w .  j  av a  2s.  c o m
 * @param cert
 * @return
 * @throws CertificateEncodingException
 */
public static String getThumbprint(final X509Certificate cert) throws CertificateEncodingException {

    if (cert == null) {
        return null;
    }

    byte[] rawOctets = cert.getEncoded();

    SHA1Digest digest = new SHA1Digest();

    byte[] digestOctets = new byte[digest.getDigestSize()];

    digest.update(rawOctets, 0, rawOctets.length);

    digest.doFinal(digestOctets, 0);

    return new String(Base64.encode(digestOctets));
}

From source file:dorkbox.util.crypto.CryptoDSA.java

License:Apache License

/**
 * The message will have the SHA1 hash calculated and used for the signature.
 * <p/>//from   w ww  .ja  v  a 2 s .c  o m
 * Note: this is here just for keeping track of how this is done. This should NOT be used, and instead use ECC crypto.
 * <p/>
 * The returned signature is the {r,s} signature array.
 */
public static BigInteger[] generateSignature(DSAPrivateKeyParameters privateKey, SecureRandom secureRandom,
        byte[] message) {
    ParametersWithRandom param = new ParametersWithRandom(privateKey, secureRandom);

    DSASigner dsa = new DSASigner();

    dsa.init(true, param);

    SHA1Digest sha1Digest = new SHA1Digest();
    byte[] checksum = new byte[sha1Digest.getDigestSize()];

    sha1Digest.update(message, 0, message.length);
    sha1Digest.doFinal(checksum, 0);

    return dsa.generateSignature(checksum);
}

From source file:dorkbox.util.crypto.CryptoDSA.java

License:Apache License

/**
 * The message will have the SHA1 hash calculated and used for the signature.
 * <p/>//from  ww  w . j a  v a 2 s.c  o  m
 * Note: this is here just for keeping track of how this is done. This should NOT be used, and instead use ECC crypto.
 *
 * @param signature
 *                 is the {r,s} signature array.
 *
 * @return true if the signature is valid
 */
public static boolean verifySignature(DSAPublicKeyParameters publicKey, byte[] message,
        BigInteger[] signature) {
    SHA1Digest sha1Digest = new SHA1Digest();
    byte[] checksum = new byte[sha1Digest.getDigestSize()];

    sha1Digest.update(message, 0, message.length);
    sha1Digest.doFinal(checksum, 0);

    DSASigner dsa = new DSASigner();

    dsa.init(false, publicKey);

    return dsa.verifySignature(checksum, signature[0], signature[1]);
}

From source file:dorkbox.util.crypto.RsaTest.java

License:Apache License

@SuppressWarnings("deprecation")
@Test/*from  ww  w  .  j  a  v a  2 s  .c  om*/
public void Rsa() {
    byte[] bytes = "hello, my name is inigo montoya".getBytes();

    AsymmetricCipherKeyPair key = CryptoRSA.generateKeyPair(new SecureRandom(entropySeed.getBytes()), 1024);

    RSAKeyParameters public1 = (RSAKeyParameters) key.getPublic();
    RSAPrivateCrtKeyParameters private1 = (RSAPrivateCrtKeyParameters) key.getPrivate();

    RSAEngine engine = new RSAEngine();
    SHA1Digest digest = new SHA1Digest();
    OAEPEncoding rsaEngine = new OAEPEncoding(engine, digest);

    // test encrypt/decrypt
    byte[] encryptRSA = CryptoRSA.encrypt(rsaEngine, public1, bytes, logger);
    byte[] decryptRSA = CryptoRSA.decrypt(rsaEngine, private1, encryptRSA, logger);

    if (Arrays.equals(bytes, encryptRSA)) {
        fail("bytes should not be equal");
    }

    if (!Arrays.equals(bytes, decryptRSA)) {
        fail("bytes not equal");
    }

    // test signing/verification
    PSSSigner signer = new PSSSigner(engine, digest, digest.getDigestSize());

    byte[] signatureRSA = CryptoRSA.sign(signer, private1, bytes, logger);
    boolean verify = CryptoRSA.verify(signer, public1, signatureRSA, bytes);

    if (!verify) {
        fail("failed signature verification");
    }
}

From source file:net.wstech2.me.httpsclient.CertificateValidatorUtils.java

License:Apache License

/**
 * /*ww w  .  j  a  v a2 s . c o  m*/
 * Inspected and display various informations from the Certificate passed as
 * parameter. Keys are presented in HEX values and ASN1 structures dumped
 * using ASN1Dump.dumpAsString.
 * 
 * This method is intended for debug purposes only.
 * 
 * 
 * @param cert
 *            The X509CertificateStructure to be inspected.
 * 
 */
public static void dumpCertificateInfo(org.bouncycastle.asn1.x509.Certificate cert) {
    boolean valid = false;
    TBSCertificate tbs = cert.getTBSCertificate();
    RSAEngine engine = new RSAEngine();
    SHA1Digest digest = new SHA1Digest();

    GenericSigner signer = new GenericSigner((engine), digest);
    RSAPublicKey signingKey;
    try {
        signingKey = RSAPublicKey.getInstance(cert.getSubjectPublicKeyInfo().parsePublicKey());

        HttpsConnectionUtils.logDebug("Public Key:[[" + cert.getSubjectPublicKeyInfo().parsePublicKey() + "]]");

        RSAKeyParameters keySpec = new RSAKeyParameters(false, signingKey.getModulus(),
                signingKey.getPublicExponent());
        signer.init(false, keySpec);
        HttpsConnectionUtils.logDebug("TBS DER object:[[" + tbs.getEncoded("DER") + "]]");

        signer.update(tbs.getEncoded(), 0, tbs.getEncoded().length);

        valid = signer.verifySignature(cert.getSignature().getBytes());

        HttpsConnectionUtils.logDebug("signer.verifySignature:[[" + valid + "]]");

        SHA1Digest d2 = new SHA1Digest();
        d2.update(tbs.getEncoded("DER"), 0, tbs.getEncoded("DER").length);
        byte[] hash = new byte[d2.getDigestSize()];
        d2.doFinal(hash, 0);
        HttpsConnectionUtils.logDebug("tbs.getDEREncoded() HASH:[[" + new String(Hex.encode(hash)) + "]]");
        DEROctetString asn1Hash = new DEROctetString(hash);
        HttpsConnectionUtils.logDebug(
                "ASN1 DEROctetString hash:[[" + new String(Hex.encode(asn1Hash.getEncoded("DER"))) + "]]");

        d2 = new SHA1Digest();
        d2.update(cert.getEncoded(), 0, cert.getEncoded().length);
        hash = new byte[d2.getDigestSize()];
        d2.doFinal(hash, 0);
        HttpsConnectionUtils.logDebug("cert.getEncoded() HASH:[[" + new String(Hex.encode(hash)) + "]]");

        byte[] signature = cert.getSignature().getBytes();
        HttpsConnectionUtils
                .logDebug("cert.getSignature().getBytes():[[" + new String(Hex.encode(signature)) + "]]");

        PKCS1Encoding engine2 = new PKCS1Encoding(new RSAEngine());
        engine2.init(false, keySpec);
        byte[] decryptedHash = engine2.processBlock(signature, 0, signature.length);
        HttpsConnectionUtils.logDebug("decryptedHash:[[" + new String(Hex.encode(decryptedHash)) + "]]");

        ASN1Object o = ASN1Primitive.fromByteArray(decryptedHash);
        HttpsConnectionUtils.logDebug(
                "decryptedHash.getDEREncoded():[[" + new String(Hex.encode(o.getEncoded("DER"))) + "]]");

        HttpsConnectionUtils.logDebug(
                "ASN1Dump.dumpAsString(decryptedHash,true):[[" + ASN1Dump.dumpAsString(o, true) + "]]");

        HttpsConnectionUtils.logDebug("engine.getInputBlockSize():[[" + engine2.getInputBlockSize() + "]]");

        HttpsConnectionUtils.logDebug("engine.getOutputBlockSize():[[" + engine2.getOutputBlockSize() + "]]");

        ASN1Sequence asn1SignSeq = (ASN1Sequence) ASN1Sequence.fromByteArray(decryptedHash);
        HttpsConnectionUtils
                .logDebug("Signature ASN1 Sequence:[[" + ASN1Dump.dumpAsString(asn1SignSeq, true) + "]]");

        AlgorithmIdentifier algorithm = AlgorithmIdentifier.getInstance(asn1SignSeq.getObjectAt(0));
        HttpsConnectionUtils.logDebug("AlgorithmIdentifier:[[" + ASN1Dump.dumpAsString(algorithm, true) + "]]");

        DEROctetString signedHash = (DEROctetString) DEROctetString.getInstance(asn1SignSeq.getObjectAt(1));
        HttpsConnectionUtils.logDebug("signedHash:[[" + ASN1Dump.dumpAsString(signedHash, true) + "]]");

    } catch (Exception e) {
        e.printStackTrace();
    }

}

From source file:org.jcryptool.visual.hashing.views.HashingView.java

License:Open Source License

private String computeHash(String hashName, String inputText, Text hashText) {
    hash = hash.getName(hashName);/*from   w  ww.j  a  v  a  2s  . com*/
    byte[] digest = null;
    switch (hash) {
    case MD2:
        MD2Digest md2 = new MD2Digest();
        md2.update(inputText.getBytes(), 0, inputText.getBytes().length);
        digest = new byte[md2.getDigestSize()];
        md2.doFinal(digest, 0);

        break;
    case MD4:
        MD4Digest md4 = new MD4Digest();
        md4.update(inputText.getBytes(), 0, inputText.getBytes().length);
        digest = new byte[md4.getDigestSize()];
        md4.doFinal(digest, 0);

        break;
    case MD5:
        MD5Digest md5 = new MD5Digest();
        md5.update(inputText.getBytes(), 0, inputText.getBytes().length);
        digest = new byte[md5.getDigestSize()];
        md5.doFinal(digest, 0);

        break;
    case SHA1:
        SHA1Digest sha1 = new SHA1Digest();
        sha1.update(inputText.getBytes(), 0, inputText.getBytes().length);
        digest = new byte[sha1.getDigestSize()];
        sha1.doFinal(digest, 0);

        break;
    case SHA256:
        SHA256Digest sha256 = new SHA256Digest();
        sha256.update(inputText.getBytes(), 0, inputText.getBytes().length);
        digest = new byte[sha256.getDigestSize()];
        sha256.doFinal(digest, 0);

        break;
    case SHA512:
        SHA512Digest sha512 = new SHA512Digest();
        sha512.update(inputText.getBytes(), 0, inputText.getBytes().length);
        digest = new byte[sha512.getDigestSize()];
        sha512.doFinal(digest, 0);

        break;
    case SHA3_224:
        SHA3.Digest224 sha3_224 = new SHA3.Digest224();
        sha3_224.update(inputText.getBytes(), 0, inputText.getBytes().length);
        digest = new byte[sha3_224.getDigestLength()];
        digest = sha3_224.digest();

        break;
    case SHA3_256:
        SHA3.Digest256 sha3_256 = new SHA3.Digest256();
        sha3_256.update(inputText.getBytes(), 0, inputText.getBytes().length);
        digest = new byte[sha3_256.getDigestLength()];
        digest = sha3_256.digest();

        break;
    case SHA3_384:
        SHA3.Digest384 sha3_384 = new SHA3.Digest384();
        sha3_384.update(inputText.getBytes(), 0, inputText.getBytes().length);
        digest = new byte[sha3_384.getDigestLength()];
        digest = sha3_384.digest();

        break;
    case SHA3_512:
        SHA3.Digest512 sha3_512 = new SHA3.Digest512();
        sha3_512.update(inputText.getBytes(), 0, inputText.getBytes().length);
        digest = new byte[sha3_512.getDigestLength()];
        digest = sha3_512.digest();

        break;
    case SKEIN_256:
        Skein.Digest_256_256 skein_256 = new Skein.Digest_256_256();
        skein_256.update(inputText.getBytes(), 0, inputText.getBytes().length);
        digest = new byte[skein_256.getDigestLength()];
        digest = skein_256.digest();

        break;
    case SKEIN_512:
        Skein.Digest_512_512 skein_512 = new Skein.Digest_512_512();
        skein_512.update(inputText.getBytes(), 0, inputText.getBytes().length);
        digest = new byte[skein_512.getDigestLength()];
        digest = skein_512.digest();

        break;
    case SKEIN_1024:
        Skein.Digest_1024_1024 skein_1024 = new Skein.Digest_1024_1024();
        skein_1024.update(inputText.getBytes(), 0, inputText.getBytes().length);
        digest = new byte[skein_1024.getDigestLength()];
        digest = skein_1024.digest();

        break;
    case RIPEMD160:
        RIPEMD160Digest ripemd160 = new RIPEMD160Digest();
        ripemd160.update(inputText.getBytes(), 0, inputText.getBytes().length);
        digest = new byte[ripemd160.getDigestSize()];
        ripemd160.doFinal(digest, 0);

        break;
    case SM3:
        SM3Digest sm3 = new SM3Digest();
        sm3.update(inputText.getBytes(), 0, inputText.getBytes().length);
        digest = new byte[sm3.getDigestSize()];
        sm3.doFinal(digest, 0);

        break;
    case TIGER:
        TigerDigest tiger = new TigerDigest();
        tiger.update(inputText.getBytes(), 0, inputText.getBytes().length);
        digest = new byte[tiger.getDigestSize()];
        tiger.doFinal(digest, 0);

        break;
    case GOST3411:
        GOST3411Digest gost3411 = new GOST3411Digest();
        gost3411.update(inputText.getBytes(), 0, inputText.getBytes().length);
        digest = new byte[gost3411.getDigestSize()];
        gost3411.doFinal(digest, 0);

        break;
    case WHIRLPOOL:
        WhirlpoolDigest whirlpool = new WhirlpoolDigest();
        whirlpool.update(inputText.getBytes(), 0, inputText.getBytes().length);
        digest = new byte[whirlpool.getDigestSize()];
        whirlpool.doFinal(digest, 0);

        break;
    default:
        break;
    }

    String hashHexValue = new String(Hex.encode(digest));
    if (btnHexadezimal.getSelection()) {
        String hashValueOutput = hashHexValue.toUpperCase().replaceAll(".{2}", "$0 "); //$NON-NLS-1$ //$NON-NLS-2$
        hashText.setText(hashValueOutput);
    } else if (btnDezimal.getSelection()) {
        String hashValue = hexToDecimal(hashHexValue);
        hashValue = hashValue.replaceAll(".{3}", "$0 "); //$NON-NLS-1$ //$NON-NLS-2$
        hashText.setText(hashValue);
    } else if (btnBinary.getSelection()) {
        String hashValue = hexToBinary(hashHexValue);
        hashValue = hashValue.replaceAll(".{8}", "$0#"); //$NON-NLS-1$ //$NON-NLS-2$
        hashText.setText(hashValue);
    }

    return hashHexValue;
}