Message digest -- BigInteger

Hi,
I am wondering about the encoding of a message digest output bytes (such as from SHA-1). Is it a two's complement or what? I want to convert it to a BigInteger object for further math calculation. Is there any convention or convinient way to do that?
Thanks.
Liang

Technically it is not a integer, but a bit string (read FIPS 180-1 or RFC 3174.)
But you can interpret it as a big integer (as its two's-complement binary), if you want to do so.
If the most significant bit of the SHA-1 hash is 1, the number will be negative, so if you want to use only positive numbers, you can add a 0-byte to interpret the SHA-1 as a positive number always.
Check the Javadoc.
BigInteger(byte[] val)
Translates a byte array containing the two's-complement binary representation of a BigInteger into a BigInteger.
For instance, the SHA-1 of "Hello, world!" is 943A702D 06F34599 AEE1F8DA 8EF9F729 6031D699; if you want to make the BigInteger's constructor interpret it as a positive number, copy the SHA-1 to a 21-byte array, making the first byte 0, as 00943A702D 06F34599 AEE1F8DA 8EF9F729 6031D699.

Similar Messages

  • 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.

  • Failed to verify AS2 message Reason message-digest attribute value

    Hi All,
    I have scenario from AS2---->PI--
    >ECC(AS2 to Proxy) .I tested in QA system successfully but messages not reached to PI system.Communcation channel montering error message is Failed to verify AS2 message. Reason: message-digest attribute value does not match calculated value (Software version: 1.0.2). This scenario working fine producation server using with receiver file adapter.After transported from QA to PROD error got occured.Please provide your inputs on this issue
    Regards,
    Ramesh

    Thank you,
    I've followed all the steps in the link for the section : For a new wallet, please follow.
    SSL is not used, the B2B sends to a proxy server which uses SSL to the Trading Partner.
    This is a future production system; the same setup and configuration has been successfully used in development and test.
    The configuration all looks the same between environments, but dev and test work while this fails.
    The previous configuration did not have the TP's public cert in the wallet, so I added it according to the link.
    However the same error occurs.
    Is there any chance this behaviour is related to this : metalink docid : 803466.1 / Oracle B2B certificate for ebMS will expire July 17 2009
    This is AS2, not using ebXML, but I do see references to the phaos security tool kit in the logs.
    Currently all environments use MLR#7.
    Edited by: tdba2 on Aug 1, 2009 11:58 PM

  • Message Digest Error (plz help)

    Hi,
    I am from India and working on Gemplus Java cards (211 PK) . and using the Gemplus RAD III Kit 3.2
    For Java card Application development (key pair generation and Message DIgest) , I am using the Javacard.security package and MessageDigest class for creating the message digest.
    But I am facing some problems.
    So, I am attaching the .java File. The source Code gets compiled properly but raises a Null Pointer Exception at RunTime (See attached text file) .
    Could you please tell me what the error is?
    Being in India, do these cards support Limited Cryptography or is Message Digesting allowed.
    My .java file (i.e. My source code)
    import java.io.*;
    import java.io.FileInputStream;
    import javacard.security.MessageDigest;
    import javacard.security.CryptoException;
    class MsgDigest
    public static void main(String args[])
         FileInputStream fIn; // File Input stream
         FileOutputStream fOut; // File output stream
         boolean          resRead; //result of "Is file readable?"
         int           resCompare; //resultof comparing 2 file's equality
         String           fNm,temp; //open file name,temparary variable for other testing
         long           fLength; //open file length
         int     resReadFile;// result of reading the file through read()
         int               fileLength=0; //file Length in int
    int          cnt=0;
    try
    //open the file on which message digest is to be performed
              fNm=new String("c:\\sample.txt");
              File fSamp=new File(fNm);
    //checking it for reading operation
              resRead=fSamp.canRead();
              System.out.println(resRead);
    //creating input stream of file and writting it into another file output.txt
    fIn=new FileInputStream(fNm);
    fLength=fNm.length();
         System.out.println("in long file size is : " fLength"\n");
         fOut= new FileOutputStream("C:\\output.txt");
    //reading the file and calculating the length
    do
                   resReadFile=fIn.read();
                   if (resReadFile!=-1)
                   fOut.write(resReadFile);
                   fileLength=fileLength+1;
         }while (resReadFile!=-1);
         fIn.close();
    //reading the file and storing it in a byte array
    fIn=new FileInputStream(fNm);
         System.out.println("in int File size is : "+fileLength+ "\n");
         byte readData[]=new byte[fileLength]; //data in file stored in this byte array
         int i;
         i=fIn.read(readData);
         System.out.println("bytes in readData : "+i+"\n");
    //creating message digest object and update message Digest to work on our message : readData
    byte midData[]=new byte[fileLength];
    MessageDigest md;
    try
         md = MessageDigest.getInstance(MessageDigest.ALG_SHA,false);
    catch(Exception e1)
         e1.printStackTrace();
    //md.update(readData,(short)0,(short)(readData.length));
    //md.doFinal(readData,(short)0,(short)(readData.length),midData,(short)0);
    }//try
    catch (CryptoException e)
              System.err.println("ERROR : "+e);
              System.exit(1);
    catch (FileNotFoundException e)
              System.err.println("ERROR : "+e);
              System.exit(1);
    catch (ArrayIndexOutOfBoundsException e)
              System.err.println("ERROR : "+e);
              System.exit(1);
    catch (Exception e)
              System.err.println("ERROR : "+e);
              System.exit(1);
    }//main
    }//class
    Getting THIS error
    true
    in long file size is : 13
    in int File size is : 241
    bytes in readData : 241
    javacard.security.CryptoException
    at javacard.security.CryptoException.throwIt(Unknown Source)
    at javacard.security.MessageDigest.getInstance(Unknown Source)
    at MsgDigest.main(MsgDigest.java, Compiled Code)
    Press any key to continue...

    The Java card specification says that when calling MessageDigest.getInstance, the exception CryptoException will be thrown if the alg. is not supported or when the shared access mode is not supported. Can you pls check if Gemplus RAD III Kit 3.2 supports SHA-1 alg. ?
    Also, the code that you have written is not compliant with Java Card spec. Because in Java card applets, we cannot use java.io.FileInputStream, etc., main method , etc. If I guess, you may be compiling the java file to class file by linking it to javacard package and executing class file using java interpreter like we do normally for executing a java application. This is not the way that Java applets are written, please go through the Java card spec for developing and compiling java applets.

  • Newbie question about message digests

    I understand that a digest is a one-way process, that a message digest is a "fingerprint" of the original message but that there is no way to recover the original (I think Ronald Rivest's document says it is "conjectured to be computationally infeasible" to do so). So far so good.
    But I also read this about digest algorithms: "it is virtually impossible to create a message with a predetermined digest." ( http://tinyurl.com/39thq )
    What does this mean, given that a particular message will always hash to the same digest?
    Thanks for any guidance.
    -javahombre

    Great, now I see! Thanks!
    This sounds especially true now that I see the explanation. For example, I notice that even different case for the "same" string matters: "test" vs. "Test" comes out to different hash.
    As for picking completely different strings that hash to the same digest, that seems almost inconceivable.
    Thanks again,
    javahombre

  • 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

  • URGENT: inconsistencies between Message Digests

    Hi
    I'm developing a system wherein the contents of a JMS message are fed into a MessageDigest, and signed by a Signature with the sending node's Private Key. The signed bytes from the Signature are then set as a message property.
    The node that receives the message then creates a MessageDigest from the message body text, and using another Signature, performs verification of the new MessageDigest with the signed bytes obtained from the JMS message property that was set.
    The problem is that, despite explicitly using the UTF-8 encryption when converting from byte[] to String in my code, the MessageDigest of the message body is always different (and differs upon each program run, even when the message body contents are the same for repeated runs). I've checked and the text being used to create the message digest on each node is exactly the same (including when checking the bytes), yet as I have said, the digests are always different. However, I am running one node on Windows XP, and another node on Solaris, but I can't see how this might affect things if I've explicitly used UTF-8 encoding, and have the same Provider (SUN version 1.2) in use on both platforms.
    Are any aspects of Message Digests time-dependent/platform-dependent/randomly-generated?
    Should I not even be using Message Digests/Signatures and instead use Ciphers?
    Can anyone help me out here? I would be extremely grateful for any assistance!
    Thanks,
    Simon Parkin

    Thanks for the help.
    I removed the MessageDigest code ... and I'm still having problems (in a different area now).
    I hate having to do this, but here is the code listing for the functions I've created (minus the Exception catching code):
    public String signedDigest(String messageText)
         PrivateKey key = (PrivateKey)KEYSTORE.getKey(LOCAL_ALIAS, LOCAL_PASSWORD.toCharArray());
         Signature kSig = Signature.getInstance(SIGNATURE_ALGORITHM);
         kSig.initSign(key);
         kSig.update(messageText.trim().getBytes("UTF-8"));     
         byte[] signedBytes = kSig.sign();
         return new String(signedBytes, "UTF-8").trim();
    public boolean verifyContent(String messageText, String signedDigest, String receiverID)
         Certificate kCert = KEYSTORE.getCertificate(receiverID);     
         PublicKey kPub = kCert.getPublicKey();
         Signature kVer = Signature.getInstance(SIGNATURE_ALGORITHM);
         kVer.initVerify(kPub);
         kVer.update(messageText.trim().getBytes("UTF-8"));          
         boolean result = kVer.verify(signedDigest.trim().getBytes("UTF-8"));
         return result;
    'signedDigest' creates the signed content in the sending node, and 'verifyContent' checks it at the receiver end. Now I've checked the content of the 'signedBytes' produced in 'signedDigest', and compared it to 'signedDigest.getBytes("UTF-8)' in 'verifyContent', and they are exactly the same, yet the verification never returns true. I'm using the right keys, and the 'messageText' used at both ends is the same, so I still can't understand why this isn't working.
    Any further help would be very much appreciated.
    Simon Parkin

  • Message Digest MD5 Problem

    My application downloads a zip file from given URL and also gets message digest (MD5) for the file.
    Then, it creates another message digest and compares them.
    I have tried files from tomcat.apache.org
    The results are below:
    apache-tomcat-6.0.20-deployer.zip (downloaded)
    1b3287c53a12e935a8c965b15af39f07 --> code from the website
    1b3287c53a12e935a8c965b15af39f7 --> code by the application
    apache-tomcat-6.0.20.zip (downloaded)
    714b973e98d47ec2df6d5e1486019f22 --> code from the website
    714b973e98d47ec2df6d5e148619f22 --> code by the application
    I could not understand why 0's are missing in my code. Should I try another files except from Apache?

    try{
                 MessageDigest algo = MessageDigest.getInstance("MD5");
                 algo.reset();
                 algo.update(data);
                 byte messageDigest[] = algo.digest();
                 StringBuffer hexString = new StringBuffer();
                 for (int i=0;i<messageDigest.length;i++) {
                      hexString.append(Integer.toHexString(0xFF & messageDigest));
         System.out.println(hexString.toString());
    catch(NoSuchAlgorithmException e) {
         e.printStackTrace();
    }I have got the content of the file in a byte array --> data.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

  • Need help about the SHA Message Digest ? & what is use of Message Diagest ?

    need help about the SHA Message Digest ? & what is use of Message Diagest ?
    1>i have one program of making message digest
    2>which requires two files name
    3>one for input like txt
    4> second is out put file of message digest
    can any one tell what is the use of second generated file .

    MessageDigest md = MessageDigest.getInstance("SHA");
    FileInputStream fis = new FileInputStream(args[0]);
    byte[] b = new byte[1024];
    int readed = -1;
    while((readed = fis.read(b)) > 0)
         md.update(b, 0, readed);
    fis.close();
    FileOutputStream fos = new FileOutputStream(args[1]);
    byte[] d = md.digest();
    StringBuffer sb = new StringBuffer();
    for(int i = 0; i < d.length; i++) {
         String str = Integer.toHexString(d[i] & 0xff);
         sb.append(str.length() < 2 ? "0" + str : str);
    fos.write(sb.toString().getBytes());
    fos.close();

  • 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

  • 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

Maybe you are looking for