Sha1 hash function (Message Digest)

I am trying to create a program that lists the current java programs in a directory that is run through command line arguments, ( which works) however once i have populated all the java files i need to then turn the file names into sha1 message digests for the next step. I have the relevant code for this to work but i can not get it to compile is there something i have done wrong? or put the code in the wrong place?? here is my code feel free to amend it.
Thanks Mich
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.io.File;
import java.io.FilenameFilter;
import java.util.Scanner;
public class ListDirectories implements FilenameFilter {
static Scanner sc = new Scanner(System.in);
public static void main (String [] args) throws UnsupportedEncodingException, NoSuchAlgorithmException {
String path = args [0];
ListDirectories ff = new ListDirectories();
ff.process(path);
public void process(String dir) {
String objects[] = (new File(dir)).list(this);
for (int i = 0; i < objects.length; i++) {
System.out.println("TRACE:"+objects);
public boolean accept(File dir, String s) {
if (s.endsWith(".java")) {
return true;
return false;
//public void MessageDigest(){
MessageDigest md = MessageDigest.getInstance("SHA");
try {
md.update(objects);
MessageDigest objects = md.clone();
byte[] objectsDigest = objects.digest();
md.update(objects);
} catch (CloneNotSupportedException cnse) {
throw new DigestException("couldn't make digest of partial content");

import java.io.UnsupportedEncodingException;
import java.security.DigestException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.io.File;
import java.io.FilenameFilter;
import java.util.Scanner;
public class ListDirectories implements FilenameFilter {
     static Scanner sc = new Scanner(System.in);
     public static void main (String [] args) throws UnsupportedEncodingException, NoSuchAlgorithmException {
          String path = args [0];
          ListDirectories ff = new ListDirectories();
          ff.process(path);
     public void process(String dir) {
          String objects[] = (new File(dir)).list(this);
          for (int i = 0; i < objects.length; i++) {
               System.out.println("TRACE:"+objects);
     public boolean accept(File dir, String s) {
          if (s.endsWith(".java")) {
               return true;
          return false;
     public void MessageDigest(){
          MessageDigest md = MessageDigest.getInstance("SHA");
          try {
               MessageDigest objects = md.clone();
               md.update(objects);
               byte[] objectsDigest = objects.digest();
               md.update(objects);
          } catch (CloneNotSupportedException cnse) {
               throw new DigestException("couldn't make digest of partial content");
}this where the error occur
MessageDigest objects = md.clone();
md.update(objects);
byte[] objectsDigest = objects.digest();
md.update(objects);
The method update(byte) in the type MessageDigest is not applicable for the argumentsListDirectories.java     line 42     1187874400500     26683
The method update(byte) in the type MessageDigest is not applicable for the arguments ListDirectories.java     line 44     1187874400500     26684
Type mismatch: cannot convert from Object to MessageDigest     Test2     ListDirectories.java     line 41     1187874400500     26682

Similar Messages

  • Message Digest. HASH algorithms

    Please, Why I calculated hash (message digest) of word "Fausto", used java.security.MessageDigest is 5e064a44ab768f9e0d5a7e0639cc16e7 but used OpenSSL with this same word "Fausto", result is 0de02ffc6280f4d111680373fa60c0b9????
    Someone to say because happen this????
    Thanks..
    :-)

    Please, Why I calculated hash (message digest) of
    word "Fausto", used java.security.MessageDigest is
    5e064a44ab768f9e0d5a7e0639cc16e7 but used OpenSSL
    with this same word "Fausto", result is
    0de02ffc6280f4d111680373fa60c0b9????
    Someone to say because happen this????
    Thanks..
    :-)The OpenSSL result is the value you get by taking the MD5 of "Fausto\n". I suspect you are not using the -n option with echo. i.e. you should use
    echo -n Fausto | openssl md5

  • Message digest algorithm in Archive Link

    Good Morning.
    We are building interface with the SAP Content Server. We require some help from you on the following items.
    Referring to the SAP Content Server HTTP Interface API 4.5/4.6,
    The library for checking signatures can be obtained from SAP AG. Because the standard format PKCS#7 was used for the signature, other products can also be used for decoding.
    From page 8, can you lets us know where we can get them.
    We would also want to know what is the message digest algorithm in Archive Link.

    Hi,
    SAP content server is using DSS for signing URL parameters. The NIST FIPS-180-3 specification defines which hash functions can be used in DSS. My guess is that it's using SHA1. I doubt that it's using newer version like SHA-256.
    Cheers

  • How to decrypt to get the message digest?

    Ok, I'm aware that, message digest, is a one-way hash algorithm. From what I gathered, we can decrypt then use the MessageDigest method, IsEqual to compared the hash value to ensure they are the same right?
    But my problem is, right now, I has the code to encrypt and digitally signed on a xml.
    But no one has used it before to decrypt. So i need to find out how.
    Below is the code to generate the signed XML.
    Can anyone tell me how to decrypt it?
    Thanks...
        public boolean generateSignXmlDocument(String xmlDocPath, String newDocPath, KeyStore keystore, String alias, String password)
            boolean status = false;
            try
                DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
                dbf.setNamespaceAware(true);
                DocumentBuilder builder = dbf.newDocumentBuilder();
                File f = new File(xmlDocPath);
                Document doc = builder.parse(new FileInputStream(f));
                KeyPair kp = getPrivateKey(keystore, alias, password);
                DOMSignContext dsc = new DOMSignContext(kp.getPrivate(), doc.getDocumentElement());
                String providerName = System.getProperty("jsr105Provider", "org.jcp.xml.dsig.internal.dom.XMLDSigRI");
                log.info("Creating xml sign.....");
                log.debug("Provider Name " + providerName);
                XMLSignatureFactory fac = XMLSignatureFactory.getInstance("DOM", (Provider)Class.forName(providerName).newInstance());
                javax.xml.crypto.dsig.Reference ref = fac.newReference("", fac.newDigestMethod("http://www.w3.org/2000/09/xmldsig#sha1", null), Collections.singletonList(fac.newTransform("http://www.w3.org/2000/09/xmldsig#enveloped-signature", null)), null, null);
                javax.xml.crypto.dsig.SignedInfo si = fac.newSignedInfo(fac.newCanonicalizationMethod("http://www.w3.org/TR/2001/REC-xml-c14n-20010315#WithComments", null), fac.newSignatureMethod("http://www.w3.org/2000/09/xmldsig#rsa-sha1", null), Collections.singletonList(ref));
                KeyInfoFactory kif = fac.getKeyInfoFactory();
                javax.xml.crypto.dsig.keyinfo.KeyValue kv = kif.newKeyValue(kp.getPublic());
                javax.xml.crypto.dsig.keyinfo.KeyInfo ki = kif.newKeyInfo(Collections.singletonList(kv));
                XMLSignature signature = fac.newXMLSignature(si, ki);
                signature.sign(dsc);
                java.io.OutputStream os = new FileOutputStream(newDocPath);
                TransformerFactory tf = TransformerFactory.newInstance();
                Transformer trans = tf.newTransformer();
                trans.transform(new DOMSource(doc), new StreamResult(os));
                status = true;
            catch(Exception e)
                log.error(e);
            return status;
        }

    Kyle Treece wrote:
    It says that both IMAP and POP are enabled in my settings.
    what settings ? in gmail webmail interface? I'm talking about how your gmail account is configured in Mail on your computer. It's configured for POP. you need to delete it from Mail and then create a new account in Mail and make it IMAP. do not use automated account setup which Mail will offer to do. that will make the account POP again. enter all server info and account type by hand.
    see this link for details
    http://mail.google.com/support/bin/answer.py?answer=81379
    If I turn POP completely off, will it kick all the messages out of my iPhone?
    as I said, this is not about turning something on or off in webmail gmail. you have to configure your email client Mail correctly. it will have no effect on your iphone.

  • Need a 64 bit Message Digest

    I need a 64 (or 96) bit message digest function that acts like MD5 or something similar, but instead of spitting out 128 bit digests, it puts out either 64 or 96 bit digests. The problem is thus, we are currently using a piece of a proprietary library to create our pretty-close-to-unique keys, which happen to be 16 byte hexidecimal keys. The company that provides the proprietary library no longer exists, and has been sold to two different companies, therefore we are looking for a replacement. The only requirement is that the key remain 16 bytes, as we have customers that rely on that key.
    I've read that MD5 runs a 2^63 chance of collision.. is is possible to take the 128 bit key and simply shave off bits? does that merely increase my chance of collision to 2^47? (for 96 bit key) or 2^31 for a 64 bit key? Or is the distribution less even than that? The messages going in will be around 150 characters btw.
    Any Help would be appreciated!

    If you are bound by these requirements then the simplest solution is, as
    you said, to lop off unecessary bits from the 16/20 byte hash returned
    by MD2 or MD5. The probability of collision, all else being equal,
    can be computed directly from the number of bits used. For this reason
    I would suggest going for the 96 bit base 64 encoding.
    Alternately you could XOR the removed bits with the reamining 96 bits
    however this should not really increase the randomness if the original
    function is doing its job properly. Whether it is worthwhile depends on
    the quality of the original hash function.
    matfud

  • Secure hash function with salt to create a not spoofable PRC (SAP CRM)

    Hello SAP Security Community,
    SAP CRM Marketing provides a functionality called Personalized Response Code (PRC, 10 characters). This code can be used in mail, fax, sms or letters to customers. When the customer returns the PRC to the communication initiator, it can be mapped to a campaign and the business partner number of the customer. See also the [SAP Standard Help|http://help.sap.com/saphelp_crm700_ehp01/helpdata/EN/2a/c13463f09c4a1f9c45903e7a0a7230/frameset.htm].
    By default this standard implementation of the BAdI CRM_MKT_PRC_CONVERT is called:
    METHOD if_ex_crm_mkt_prc_convert~convert_prc.
      DATA lv_no      TYPE  crmt_mkt_icrh_prc_num.
      DATA lv_string  TYPE  string.
      DATA lv_pos     TYPE  int4.
      DATA lv_base31  TYPE  string VALUE '0123456789BCDFGHJKLMNPQRSTVWXYZ'.
    **** converting the numeric-base10 into base31
      lv_no = iv_prc.
      CLEAR lv_string.
      DO.
        lv_pos = lv_no MOD 31.
        lv_no  = lv_no DIV 31.
        CONCATENATE lv_base31+lv_pos(1) lv_string INTO lv_string.
        IF lv_no = 0.
          EXIT.
        ENDIF.
      ENDDO.
      MOVE lv_string TO ev_prc.
    ENDMETHOD.
    As you can see it does a simple base31 encoding of the provided input parameter iv_prc which is a number provided by the number range for PRC's.
    I want to use the PRC to make our customers registration process for a trade fair easier. We send out the PRC via a letter to the customers where we don't have an E-Mail address. The letter contains instructions which point the user to a Website that has an input field for the PRC. When the user submits the PRC I'd like to show him/her some personal information (Name, Address, E-Mail) that we lookup using the PRC in the CRM System. This information is then posted to a 3rd party website that has to be used to do the trade fair registration.
    If I would use the simple base31 encoding, then the current counter state could be easily decoded, the next number can be chosen and by applying base31 encoding again, the next valid PRC is created. This could then be misused to read personal information of another customer. I think what could solve this problem would be to use a secure hash function that allows also to be salted to create the PRC.
    Do you think I'm on the right track? Or would it be OK to use the classes described in [Note 1410294 - Support SHA2-family for Message Digest and HMAC|https://service.sap.com/sap/support/notes/1410294] and before doing the hashing add a random number to the PRC number that I've got from the number range? What problems do I run in as the PRC could not be longer than 12 characters? For sure I have to check that I don't create any PRC twice.
    Best regards
    Gregor

    Knowledge of PCR should not reveal any personal information to you.
    OK, but in this case the PCR is mapped to the campaign number and the BP-number. It would reveal the information.  Hence a second hash which only allows further processing if it matches. The second hash is a "signature" of the PCR.
    I don't agree with this. The security should NOT be based on hiding how system works. Only key should be secret. In this case it should all depend on quality of PRNG. Check Kerckhoffs's principle. Whenever I see proprietary algorithm in crypto I start to feel nervous about the system.
    Ok, you convinced me. That is also true, but you will have to save the key or the hash it produces to be able to verify it again when the user returns to the website - and in this case it is in clear text ABAP (unless Mr. Wolf wants to create an external program, like SAP does with C-calls).
    From the perspective of the user it is a password and they must be able to transfer it from a snail-mail readable text on paper into a website field.
    As Mr. Wolf has noticed, the next PCRs can be obtained by anyone who can decode standard code (knowing that the BADI is activated).
    I think a correctly placed split and concatenation does the trick for a 20 character field without knowing which part is the PCR and which is the signature (a human can still enter that into a website field).
    I think the big question (appart from the principle - which I agree with you on) is whether the admins and their family members are allowed to bid? Also do the bidders have acces to this system as technical consultants?? (for example to single test methods and function modules in the production system??).
    Also how does the process continue and finally get concluded? Typically there is some "horse trading" in the end anyway... 
    All these factors should influence the strength and complexity of the design, and maintenance of it IMO.
    But generally you are correct and I rest my case.
    @ Mr. Wolf: Are you enjoying the debate too much or are you going to give us more insight?
    Cheers,
    Jules

  • What is mean of Message Digest ?

    hi
    can any one tell
    what is mean of Message Digest ?
    shrinath

    If the OP doesn't know what a message digest is, odds
    are they don''t know what a hash value is either.I don't agree, a hash function is a fairly standard IT thingie, where as a Message digest is domain specific (crypto).
    But the lack of Google Fu does suggest a lack of IT knowledge. So some helpful links are included above.

  • Decrypting a Emcrypted Message Digest

    Hi,
    I have a Encrypted Message Digest which is obtained by hashing the data using SHA1 and then signed the resulted digest with private key. This is done using Entrust API's. Is there any way by which I can decrypt the Encrypted Message Digest using JAVA API's with public key.
    can someone give me any idea.
    Thanks in advance
    Nitin

    With what i could i understand,... you have an encrypted MD.(by private key). It could be like this..
    MessageDigest md= MessageDigest.getInstance("SHA-1");
    md.update("data".getBytes());
    byte[] hash= md.digest();
    Cipher c = Cipher.getInstance("RSA","BC");
    c.init(Cipher.ENCRYPT_MODE,privk);
    byte[] encrypted = c.doFinal(hash);
    Now u can decrypt using the public key to get the original MD like this:
    //initialise the cipher to decrypt mode
    c.init(Cipher.DECRYPT_MODE,pubk);
    byte[] decrypt= c.doFinal(encrypted);          
    Thats it !
    Vijay

  • Is message digest a strong cryptography

    for strong cryptography,security is base on the key rather than algorithm itself.but I use message digest,in main I pass in a plain text(args[0]),like this:
    byte[] buf= new byte[args[0].length()];
    buf=args[0].getBytes();
    MessageDigest algorithm=null;
    try {
    algorithm = MessageDigest.getInstance("SHA-1");
    }catch (NoSuchAlgorithmException e) {
    System.out.println(e);
    algorithm.reset();
    algorithm.update(buf);
    byte[] digest1 = algorithm.digest();
    the digest1 is the cipher text.but there looks no way to put key
    so,is the message digest not a strong cryptography?or can I put key for it?

    http://developer.java.sun.com/developer/qow/archive/28/i ndex.html
    they use messagedegist to encrypt password,do you
    think this is wrong?No, they don't encrypt the password. There is no key involved. SHA-1 is a message digest, a sort of a checksum but no encryption. They just make it unreadable by storing the hash of the password. By the way, the method they use is prone to a dictionary attack.
    Encryption is a two-way function. I encrypt a message M by using a key KE with an encryption function E() to produce a cipher text C:
    C := E(KE, M)
    I can decrypt this by using a decryption function D() with a decryption key KD:
    M := D(KD, C)
    This way, you can retrieve the original message from the cipher text.
    The cipher text C is as long as or longer than the oroginal message M.
    However, if you use a digest DS() on a message M you get a hash that has a fixed length:
    H := DS(M)
    This hash is not reversible! I.e. if you know the hash value H, you can not retrieve the message M. SHA-1 has a length of 20 bytes, regardless of the length of the message M. So, if you put one byte into SHA-1 or 1,000,000 bytes, H always has a length of 20 bytes. You can not retrieve the original bytes from that...
    However, if you just want to store passwords in a safe way a hash is a great method for this. You simply don't need to encrypt them if you just want to know wether a user has entered a password that is the same as a stored password.
    But using a hash is not enough. You also need a "salt" and an interation count. Look at PKCS#5 (http://www.rsasecurity.com/rsalabs/pkcs/pkcs-5/index.html) at the PBKDF2 chapter (5.2). It has a good introduction in chapters 1 to 4, as well.
    Regards,
    Frank

  • SHA-1 Message Digest

    Hi All,
    I have been given a task to create a SHA-1 (160 bit) Message Digest for a compiled executable. I have the SHA-1 string which contains 40 chars. Can someone shed some light?
    Much Appreciated.
    KayMan

    sabre150 said:
    Right, but do you know what you can do with asingle
    colliiding block?The only paper I have read on this is
    http://eprint.iacr.org/2004/356.pdf and it does not
    fill me with dread. Maybe it should! Taken to it's
    logical conclusion, any hash is flawed as soon as one
    colliding block is known and dangerous once the
    algorithm for creating the colliding block is
    published..Yes exactly.
    For some time now we have known that MD5 is flawed
    and we now know that SHA1 is flawed. I expect that in
    the next few years sha 256 will be found flawed. Possibly.
    As I
    understand it, at this time the theory of hashing is
    in it's infancy and falls well behind the theory of
    encryption and until the theory of hashing is more
    advanced I don't expect to get really secure hashes.Yep.
    Since I have now retired and only work on a very very
    part time basis I don't think it will fall to me to
    implement any of the upgrades.Of course; my point was to just to make a note that SHA-1 is seriously broken and should not be used if possible.

  • Encrypting a message digest

    Hi I'm trying to encrypt a message digest using RSA Encryption. For some reason when the encrypted message digest is decrypted it does not match the original. If this is hard to follow the following code illustrates this point:
    String input = "Testing message";
    MessageDigest hash = MessageDigest.getInstance("SHA1");
    hash.update( input.getBytes() );
    generator.initialize(512, random);
    KeyPair pair = generator.generateKeyPair();
    Key pubKey = pair.getPublic();
    Key privKey = pair.getPrivate();
    cipher.init(Cipher.ENCRYPT_MODE, privKey); // encrypt
    byte[] cipherText = cipher.doFinal( hash.digest() );
    // now decrypt
    cipher.init(Cipher.DECRYPT_MODE, pubKey);
    byte[] plainText = cipher.doFinal(cipherText);Here the byte array plainText does not match the original message digest from hash.digest() Any help on how to correct this problem would be great.
    thanks
    -B
    Edited by: BenWhethers on Dec 13, 2007 12:49 PM
    Edited by: BenWhethers on Dec 13, 2007 12:50 PM

    You don't provide testable code so I have made a guess as to the missing code and for me the decrypted digest is the same are the original.
            Cipher cipher = Cipher.getInstance("RSA");
            SecureRandom random = new SecureRandom();
            KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA");
            String input = "Testing message";
            MessageDigest hash = MessageDigest.getInstance("SHA1");
            hash.update( input.getBytes() );
            generator.initialize(512, random);
            KeyPair pair = generator.generateKeyPair();
            Key pubKey = pair.getPublic();
            Key privKey = pair.getPrivate();
            cipher.init(Cipher.ENCRYPT_MODE, privKey); // encrypt
            byte[] digest = hash.digest();
            byte[] cipherText = cipher.doFinal( digest );
            // now decrypt
            cipher.init(Cipher.DECRYPT_MODE, pubKey);
            byte[] plainText = cipher.doFinal(cipherText);
            System.out.println(Arrays.equals(plainText,digest ));

  • How do I get Message Digest from Signature?

    When signing some data, first one computes the message digest, then encrypts the message digest with his private key to get the signature. So, if I have the public key, I should be able to take the signature and decrypt it, yielding the original message digest. Correct?
    However, there doesn't seem to be any way to do this using standard JDK functionality (JDK1.3.1). The java.security.Signature object encapsulates the message digest computation and encryption into one operation, and encapsulates the signature verification into an operation; there doesn't seem to be a way to get at the message digest.
    I downloaded the Cryptix library and used the Cipher class to try to decrypt the signature, but kept getting errors. The code and error are as follows. Thanks for any ideas on how to get this to work.
    package misc;
    import java.util.*;
    import java.security.*;
    import xjava.security.*;
    import cryptix.provider.*;
    public class SignatureTest {
    public static void main(String[] args) {
    try {
    Security.addProvider(new Cryptix());
    // create data to sign
    byte[] data = new byte[] {1, 2, 3, 4, 5, 6, 7, 8, 9, 0};
    // get message digest
    MessageDigest md = MessageDigest.getInstance("SHA1");
    byte[] digest = md.digest(data);
    // generate keys
    KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
    KeyPair keyPair = kpg.generateKeyPair();
    PublicKey publicKey = keyPair.getPublic();
    PrivateKey privateKey = keyPair.getPrivate();
    // sign data
    Signature s = Signature.getInstance("SHA1withRSA");
    s.initSign(privateKey);
    s.update(data);
    byte[] signature = s.sign();
    // decrypt the signature to get the message digest
    Cipher c = Cipher.getInstance("RSA");
    c.initDecrypt(publicKey);
    byte[] decryptedSignature = c.crypt(signature);
    // message digest obtained earlier should be the same as the decrypted signature
    if (Arrays.equals(digest, decryptedSignature)) {
    System.out.println("successful");
    } else {
    System.out.println("unsuccessful");
    } catch (Exception ex) {
    ex.printStackTrace();
    java.security.InvalidKeyException: RSA: Not an RSA private key
         at cryptix.provider.rsa.RawRSACipher.engineInitDecrypt(RawRSACipher.java:233)
         at xjava.security.Cipher.initDecrypt(Cipher.java:839)
         at misc.SignatureTest.main(SignatureTest.java:35)

    I learned from someone how to do the decryption myself using BigInteger. The output shows that the decrypted signature is actually the message digest with some padding and other information prepended. See (quick and dirty) code and output below:
    package misc;
    import java.util.*;
    import java.security.*;
    import java.security.interfaces.*;
    import java.security.spec.*;
    import java.math.*;
    public class SignatureTest {
        public static void main(String[] args) {
            try {
                // create data to sign
                byte[] data = new byte[] {1, 2, 3, 4, 5, 6, 7, 8, 9, 0};
                // get message digest
                MessageDigest md = MessageDigest.getInstance("SHA1");
                byte[] digest = md.digest(data);
                System.out.println("Computed digest:");
                System.out.println(getHexString(digest));
                System.out.println();
                // generate keys
                KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
                KeyPair keyPair = kpg.generateKeyPair();
                PublicKey publicKey = keyPair.getPublic();
                PrivateKey privateKey = keyPair.getPrivate();
                // sign data
                Signature s = Signature.getInstance("SHA1withRSA");
                s.initSign(privateKey);
                s.update(data);
                byte[] signature = s.sign();
                System.out.println("Signature:");
                System.out.println(getHexString(signature));
                System.out.println();
                // decrypt the signature to get the message digest
                BigInteger sig = new BigInteger(signature);
                RSAPublicKey rsaPublicKey = (RSAPublicKey)publicKey;
                BigInteger result = sig.modPow(rsaPublicKey.getPublicExponent(), rsaPublicKey.getModulus());
                byte[] resultBytes = result.toByteArray();
                System.out.println("Result of decryption:");
                System.out.println(getHexString(resultBytes));
                System.out.println();
            } catch (Exception ex) {
                ex.printStackTrace();
        public static String getHexString(byte[] bytes) {
            StringBuffer sb = new StringBuffer();
            for (int i = 0; i < bytes.length; i++) {
                sb.append(Integer.toHexString(new Byte(bytes).intValue()));
    sb.append(" ");
    return sb.toString();
    Output:
    Computed digest:
    ffffffe8 ffffff9a ffffffd5 ffffffa9 63 1c 3e fffffffd ffffffde ffffffd7 ffffffe3 ffffffec ffffffce 79 ffffffb4 ffffffd0 fffffffe ffffffdc ffffffe1 ffffffbf
    Signature:
    60 75 13 7c ffffffaf 77 6e ffffffc1 ffffffd2 4a 42 ffffffe8 45 47 20 4f ffffffbf 46 4 12 47 ffffffa9 1 ffffffe7 ffffffae 58 fffffff2 fffffffe 28 ffffffd1 25 32 49 ffffff9f ffffffe3 4 ffffffbf ffffffce 5d ffffffd9 67 70 ffffff99 ffffffbf ffffffdb 2f d ffffffb8 ffffffa4 6e ffffff9f 28 24 7d 71 50 38 ffffffe4 5f ffffffab fffffff5 ffffff93 54 4c ffffffe4 ffffff9a 11 23 66 49 ffffff8c ffffffc3 49 68 c ffffffa4 36 ffffff8f ffffffb3 57 a 58 ffffffb2 ffffffac 3e 55 ffffffe4 ffffff91 16 5e 7b ffffffe9 ffffffa6 50 ffffff9a fffffff5 22 7b ffffffd4 60 ffffffe2 fffffffe 24 ffffffa9 ffffff92 69 4b ffffffd9 44 ffffffb2 57 ffffff91 53 ffffffb9 7 fffffff7 ffffffa3 ffffffd5 61 ffffff81 ffffffb7 ffffff95 5 5b 30 7f 55 71
    Result of decryption:
    1 ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff 0 30 21 30 9 6 5 2b e 3 2 1a 5 0 4 14 ffffffe8 ffffff9a ffffffd5 ffffffa9 63 1c 3e fffffffd ffffffde ffffffd7 ffffffe3 ffffffec ffffffce 79 ffffffb4 ffffffd0 fffffffe ffffffdc ffffffe1 ffffffbf

  • Verifying a Digital Signature using message digest

    Hi, i am new to java.
    I have a Digitally signed document, i wanna verify this signed document against the original one.
    i got the idea from this link:
    http://help.sap.com/saphelp_45b/helpdata/en/8d/517619da7d11d1a5ab0000e835363f/content.htm
    i signed a pdf doc with my SmartCard. the third party signing tool passed me the PKCS7 digital signature and i stored it in database. the problem arose when i retrieved this digital signature from DB and verified against the original doc using the message digest method. the base64 result strings are always not equal.
    I am sure about this:
    -the retrieved digital signature was GOOD.
    -the original doc was GOOD.
    but why i can't get the same 2 message digests? can somebody please help?
    below is part of my code:
    while (rsetDs.next())
         InputStream DSName2 = rsetDs.getBinaryStream(1);
         ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
         byte[] myByte = Base64.decode(byteStream.toString());
         ByteArrayInputStream newStream = new ByteArrayInputStream(myByte);
         CertificateFactory cf = CertificateFactory.getInstance("X.509");
         Collection c = cf.generateCertificates(newStream2);
         Iterator i = c.iterator();
         while (i.hasNext())
              Certificate cert = (Certificate)i.next();
              X509Certificate cert1 = (X509Certificate)cert;
              try
                   java.security.MessageDigest md = java.security.MessageDigest.getInstance("MD5");
                   /*=============DB MD (BEGIN)==================*/
                   byte [] pubkeyByte = cert1.getPublicKey().getEncoded();
                   md.update(myByte);
                   md.update(pubkeyByte);
                   byte[] raw = md.digest();
                   String db_md = Base64.encode(raw);
                   /*============DB MD (end)============*/
                   /*=============PDF MD (BEGIN)==================*/
                   DataInputStream m_disFile = new DataInputStream(new FileInputStream("C:\\" + "original_doc.pdf"));
                   int m_iNum = m_disFile.available();
                   byte[] msgBytes = new byte[m_iNum];
                   m_iNum = m_disFile.read(msgBytes, 0, m_iNum);
                   md.update(msgBytes);
                   byte[] digestMd = md.digest();
                   md.reset();
                   String pdf_md = Base64.encode(digestMd);
                   /*=============PDF MD (END)==================*/
    ..thanks in advance.

    PKCS#7 SignedData objects are far more complex then it looks like you are taking them. First the PKCS#7 SignedData object will contain the OID for the message digest algorithm used and for the encryption algorithm used. From the looks of your code you are simply assuming MD5.
    It also contains all of the data that was signed which is typically much more than just the document. It also of course contains the public keys and signatures which singed the document. In your case it will probably only have one public certificate and one signature.
    Also note that a signature is an encrypted hash. Looking at your code I do not see you use encryption at all or rather for verification decryption.
    Here is the basic process a signature takes.
    MessageDigest md = MessageDigest.getInstance(algOID);
    byte[] digest = md.digest(message.getBytes(charEncoding));
    Cipher c = Cipher.getInstance("RSA/2/PKCS1Padding");
    c.init(Cipher.ENCRYPT_MODE, priKey);
    byte[] signature = c.doFinal(digest);Note that the resulting byte array is not the message digest but the encrypted message digest. You must use the corresponding public key to decrypt the signature to get the message digest value. It is because the trusted public key can decrypt the correct message digest that we know it was encrypted by the holder of the private key. It is because the decrypted message digest value is equal to my computed message digest value that we know the document has not be altered...
    Now PKCS#7 SignedData does not take the message digest of the document, in your case your PDF. It creates a message digest on an ASN.1 object which includes the bytes of your document plus a bunch of meta data.
    For more info on the exact format of a PKCS#7 signature file check out
    http://www.rsasecurity.com/rsalabs/pkcs/pkcs-7/index.html
    Look through this doucment for SignedData as a starting place and follow through all of the sub objects that make up a SignedData object. This will give you an idea of what is involved.

  • How to encrypt password with hash function in Java?

    Hello, everybody!
    I will need to store user passwords in a database, but for stronger security I want to store these passwords hashed, so I know I will need a column for the password and for the salt value.
    So, I'd like that you indicate me a very good article or tutorial (preferable from Sun) that shows me how to use Java to encrypt and decrypt passwords with hash. It doesn't necessarily need to deal with database. I can implement this part myself after seeing how Java manage encryption with hash functions.
    Thank you very much.
    Marcos

    I will tell you more precisely what I want to get better for you to help me.
    As I said I implemented in .NET what I need to implement in Java now. In my
    database I have a table with this structure (I omitted that columns that are not
    necessary to our discussion):
    CREATE TABLE EMPLOYEES
    ID NOT NULL PRIMARY KEY,
    PASSWORD VARCHAR(40), -- password encrypted
    HASH_SALT VARCHAR(10) -- salt value used to encrypt password
    So, in the table I have a column to store the password encrypted and a column to
    store the salt value.
    Below is a little utility class (in C#) that I use to generate the salt and
    the hashed password.
    public static class PasswordUtilities
        public static string GenerateSalt()
            RNGCryptoServiceProvider encoder = new RNGCryptoServiceProvider();
            byte[] buffer = new byte[5];
            encoder.GetBytes(buffer);
            return Convert.ToBase64String(buffer);
        public static string EncryptPassword(string password, string salt)
            string encryptedPassword =
                FormsAuthentication.HashPasswordForStoringInConfigFile(
                password + salt, "SHA1");
            return encryptedPassword;
    }As you can see, the class is fairly simple. It only has two methods: one to
    generate the salt value that will be used to encrypt the password and another
    one to encrypt the password. The method HashPasswordForStoringInConfigFile of
    the FormsAuthentication class is what really hash the password with the salt
    value. This class belongs to the .NET library, so we can't see its source code,
    but it doesn't matter for our discussion as I know that we can implement
    something similar in Java.
    Below is a little sample code showing the use of the utility class above to
    encrypt a password.
    public class Encrypt
        public static void Main(string args[])
            string password = "Secret";
            string salt = PasswordUtilities.GenerateSalt();
            string encryptedPassword = PasswordUtilities.EncryptPassword(password, salt);
            // now I store 'encryptedPassword' in the PASSWORD column and 'salt'
            // in the HASH_SALT column in the EMPLOYEES table.
    }To verify if a password is correct I can use the code below:
    public class VerifyPassword
        public static void Main(string args[])
            string password = GetPasswordFromUser();
            // Let's assume that employee is an instance that corresponds to a row
            // in the database and the properties HashSalt and Password correspond
            // to the HASH_SALT and PASSWORD columns respectively.
            Employee employee = GetEmployeeFromDatabase(1);
            string salt = employee.HashSalt;
            string encryptedPassword = PasswordUtilities.EncryptPassword(password, salt);
            bool passwordMatch = employee.Password.Equals(encryptedPassword);
            System.Console.WriteLine(passwordMatch);
    }The only thing that interest me in this discussion is the PasswordUtilities class.
    As you saw its code is in C#, using the .NET framework libraries.
    What I want is to have this same little class coded in Java, to generate the salt
    value and to encrypt the password passed in using salt value generated. If you could
    help me to do that with articles that have what I want or with code that already do
    that I would really appreciate.
    Thank you in advance.
    Marcos

  • One way hash function in java

    Simply i want to save a password entered to a java program and save it in a MySQL database
    Here I want to encrypt that password and save it in the database.... I prefer one way hash function encryption because it fulfills my need.
    SHA-1 is the best in java now as I read from a article, is it?
    What I need is that if someone can post a complete code which uses SHA-1 (if it is the best preferred one).
    I've tried some codes published in the web but didn't work
    one code worked very well but when I entered characters like "@#$%%" it failed.
    Thank You!!!

    797241 wrote:
    I've search using your key terms and got a good code that works ("java sha-1 example")
    thanks for that
    I didn't got that when i was searchingHard to believe.
    So suggesting that working link was enough though you've put some other annoying comment tooIt is considered extremely bad mannered just to ask for code. If you have presented code that has problems and ask for help in fixing the problems you will normally get help but just to ask for code implies you are very lazy.
    thanks for that too
    I would rather prefer if you would have written "You are not going to get an answer, get the hell out of here!!!"Now that would have invoked the wrath of the moderators!
    P.S. Just using a SHA-1 digest is insecure as the result is open to a dictionary attack. You should use a randomly seeded digest with both the random value and digest value being stored in the database.

Maybe you are looking for