| obhiee@my-deja.com 2006-04-27, 7:06 pm |
| hullo.
i'm trying my hand at cryptography, and have a sample program posted
below
The program uses the private key from the default keystore to sign. The
certificate which contains the private key is exported and exists
outside the keystore. The public key from the exported certificate [to
which the private key belows] is used to verify the signature;
i think this should return a true since the content is signed using the
private key of the certificate. But for some reason, i can't figure
out, it returns a false.
Can someone please check what i'm doing wrong? I think it needs a pair
of eyes other than mine to find out what the problem may be (+:
abhishek
p.s. i've used jdk1.4.2_02.
import java.io.*;
import java.security.*;
import java.security.spec.*;
import java.security.acl.*;
import java.security.cert.*;
public class pki{
public static void main(String args[]){
if(args.length <=0){
System.err.println("Insufficient Arguments: Path to Certificate
required.");
}else try{
// read certificate into buffer
FileInputStream fis = new FileInputStream( args[ 0 ] );
byte[] eKey = new byte[ fis.available() ];
fis.read( eKey );
fis.close();
// finished reading the key from the specified stream
int iter = eKey.length ;
System.out.println();
// load keystore from specified location.
KeyStore ks = KeyStore.getInstance( "JKS" );
char[] kspwd = { 'c','h','a','n','g','e','i','t' };
ks.load(new FileInputStream( "c:/windows/.keystore" ), kspwd );
// get certificate from keystore
java.security.cert.Certificate certt = (
java.security.cert.Certificate )ks.getCertificate( "mykey" ) ;
// get private key from keystore
PrivateKey privKey = ( PrivateKey )ks.getKey( "mykey", kspwd );
// create an instance of signature
Signature dsaSig = Signature.getInstance( "SHA/DSA" );
// initialize signature
dsaSig.initSign( privKey );
// translate the string into a byte sequence
byte[] bArr = "My Message".getBytes();
// update signature with data to be signed
dsaSig.update( bArr );
// sign the data
byte[] signedBarr = dsaSig.sign( );
String signedStr = new String( signedBarr );
// use the public key from the certificate to verify the signature
dsaSig.initVerify( certt.getPublicKey() );
// output result of verification...
System.out.println( dsaSig.verify( signedBarr ) );
}catch( Exception e ){
e.printStackTrace( System.err );
}
}
}
|