Home | Contact Us | FAQ | Search & Site Map | Link to Us
Sign In | Join | Other 45 Sites in Network
HomeAnnouncementsWhite Papers
Discussion GroupsFirst AidDatabasesJavaBeansGUIJava 3DVirtual MachineCORBASecurityToolsGeneral
Java DirectoryOpen Source ProjectsSample Book ChaptersUser GroupsWeb Resources
Related Topics
Databases.NETMore Topics ...

Java Forum / Security / January 2006

Tip: Looking for answers? Try searching our database.

signing and verifying message

Thread view: 
serafinek - 17 Oct 2005 23:45 GMT
Hello

I am trying to sign and verify simple text message. The problem is, that
it even most simple code doesn't work:

KeyPairGenerator gen = KeyPairGenerator.getInstance("RSA");
gen.initialize(512);
KeyPair pair = gen.generateKeyPair();
PrivateKey priv = pair.getPrivate();
PublicKey pub = pair.getPublic();

String hash= "alamakota";

Signature signature = Signature.getInstance("SHA1withRSA");
signature.initSign(priv);
signature.update(hash.getBytes());

byte[] raw = signature.sign();

Signature signature2 = Signature.getInstance("SHA1withRSA");
signature2.initVerify(pub);
if (signature2.verify(raw))
  konsola.append("\nThe signature is good.");
else
  konsola.append("\nThe signature is bad.");

and of course i can see "signature is bad".
What am i missing or don't understand?

Signature

serafinek

Tommy Grändefors - 18 Oct 2005 19:40 GMT
Hi,

You have forgotten to feed your signature2 object with the data that
was signed i.e. you must use 'signature2.update(hash.getBytes())'
before you call 'signature2.verify(raw)':

Signature signature2 = Signature.getInstance("SHA1withRSA");
signature2.initVerify(pub);
signature2.update(hash.getBytes());
if (signature2.verify(raw))
  konsola.append("\nThe signature is good.");
else
  konsola.append("\nThe signature is bad.");

Regards,
Tommy Grändefors
www.pheox.com

> Hello
>
[quoted text clipped - 24 lines]
> and of course i can see "signature is bad".
> What am i missing or don't understand?
serafinek - 18 Oct 2005 22:03 GMT
Hi
Thanks, now it's work :)

> Hi,
>
[quoted text clipped - 13 lines]
>  Tommy Grändefors
>  www.pheox.com
Muhammad Ijaz Khan - 05 Jan 2006 14:22 GMT
this problem is exactly opposite than mine :S
and I know I have some problem in my code but its too simple and still I
cant locate it.
can anybody see and tell me the issue? (very) below is my code
Regards,
Ijaz

> Hi
> Thanks, now it's work :)
[quoted text clipped - 16 lines]
>>  Tommy Grändefors
>>  www.pheox.com

=======================================================================================
package com.security.pki;

import java.security.InvalidKeyException;
import java.security.spec.*;
import java.security.PublicKey;
import java.security.SignatureException;
import java.security.NoSuchAlgorithmException;
import java.security.Signature;
import java.io.File;
import java.io.InputStream;
import java.io.IOException;
import java.io.FileInputStream;

/**
 * <p>Title: </p>
 *
 * <p>Description: </p>
 *
 * <p>Copyright: Copyright (c) 2006</p>
 *
 * <p>Company: </p>
 *
 * @author not attributable
 * @version 1.0
 */
public class OneMoreTest {
    public OneMoreTest() {
    }

    public static void main(String[] args) {
        PublicKey publicKey = null;

        try
        {
           byte[] signbuff = null;
           byte[] publicKeyBytes = null;
           byte[] msg = null;
           try
           {
                java.security.KeyFactory keyFactory =
java.security.KeyFactory.getInstance("RSA");

                File file = new File("public.key");
                publicKeyBytes = getBytesFromFile(file);

                EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(
                        publicKeyBytes);
                publicKey = keyFactory.generatePublic(publicKeySpec);

                file = new File("signature.sig");
                signbuff = getBytesFromFile(file);

                file = new File("message.msg");
                msg = getBytesFromFile(file);
           }
           catch (IOException e)
           {
               e.printStackTrace();
           }
           catch (InvalidKeySpecException ex)
           {
               ex.printStackTrace();
           }
           catch (NoSuchAlgorithmException ex)
           {
               ex.printStackTrace();
           }

           Signature signature = Signature.getInstance("SHA256WITHRSA");
           signature.initVerify(publicKey);
      // IF UNCOMMENT BELOW LINE VERIFY METHOD RETURNS FALSE :(
           //signature.update(msg, 0, msg.length);
           boolean val = signature.verify(signbuff);
           System.out.println(val);
        }
        catch (SignatureException e)
        {
            e.printStackTrace();
        }
        catch (InvalidKeyException e)
        {
            e.printStackTrace();
        }
        catch (NoSuchAlgorithmException e)
        {
            e.printStackTrace();
        }

    }
    public static byte[] getBytesFromFile(File file) throws IOException {
     InputStream is = new FileInputStream(file);

     // Get the size of the file
     long length = file.length();

     // You cannot create an array using a long type.
     // It needs to be an int type.
     // Before converting to an int type, check
     // to ensure that file is not larger than Integer.MAX_VALUE.
     if (length > Integer.MAX_VALUE) {
         // File is too large
     }

     // Create the byte array to hold the data
     byte[] bytes = new byte[(int)length];

     // Read in the bytes
     int offset = 0;
     int numRead = 0;
     while (offset < bytes.length
            && (numRead=is.read(bytes, offset, bytes.length-offset)) >=
0) {
         offset += numRead;
     }

     // Ensure all the bytes have been read in
     if (offset < bytes.length) {
         throw new IOException("Could not completely read file
"+file.getName());
     }

     // Close the input stream and return bytes
     is.close();
     return bytes;
 }

}
=====================================================================


Free Magazines

Get these publications absolutely FREE for up to 12 months. There are no hidden fees and no obligation. Simply choose a title, complete the application form and submit it. Read more ...

Oracle MagazineNetwork ComputingComputer WorldBio-IT WorldeWeekInformation WeekInfosecurity
 
Sign In
Join
My Latest Posts
My Monitored Threads
My Blog
My Photo Gallery
My Profile
My Homepage

Start New Thread
Enable EMail Alerts
Rate this Thread



©2008 Advenet LLC   Privacy Policy - Terms of Use
This website includes both content owned or controlled by Advenet as well as content owned or controlled by third parties.