invalid encoding for signature
Hi every body!
I am writing a java code which creates some signature using SHA1 and I want to store the signature in db. I used MYSQL and I put the signature in a column by VARCHAR type. when I fetch the signature to verify it, the 'Verification=signature.verify(Sign);" make an error which is :
invalid encoding for signature
Variable type of Sign is byte[]. but I fetch String type from DB. then I converted it to byte[] by :
Sign=rs.getString("sign").getBytes();
I think this conversion spoils the signature.What shall I do? How can I make the encoding proper?
this is the code:
Code :
//create signature
Signature signature = Signature.getInstance("DSA");
signature.initSign(privkey);
signature.update(datatoSign);
byte[] Sign=signature.sign();
mystatment.executeUpdate("UPDATE mytable SET sign = '"+Sign+"' ");
//Now I a will fetch the tuple AND verfiy the signature by public key
SQL="SELECT * FROM notebooks "
rs=(stat.executeQuery(SQL));
Sign=rs.getString("sign").getBytes();
boolean Verification;
signature.initVerify(pubkey);
signature.update(datatoSign);
Verification=signature.verify(Sign); //--------------this the error generating line
I am looking to here from you
Re: invalid encoding for signature
You're making it too difficult. Use something like Commons Codec, to base64 encode your string before you save it and base64 decode when you read it out of the database. Converting from byte[] to String between your database and your code can introduce conversion errors based on different character sets - which is what you suspect.
Creating a base64 encoded String looks something like:
Code :
byte[] theArray = ...;
String hash = new String( Base64.encodeBase64( theArray ) );
Re: invalid encoding for signature
Yes, you are right. So thanks for your useful comment.
I changed the code in this form:
Code :
//create signature
Signature signature = Signature.getInstance("DSA");
signature.initSign(privkey);
signature.update(datatoSign);
byte[] Sign=signature.sign();
//encode the Sign to Base64
String MySign=new String (Base64.encode(Sign));
mystatment.executeUpdate("UPDATE mytable SET sign = '"+MySign+"' ");
//Now I a will fetch the tuple AND verfiy the signature by public key
SQL="SELECT * FROM notebooks "
rs=(stat.executeQuery(SQL));
//decode the fetched signature from DB
TheSign=Base64.decode(rs.getString("sign"));
boolean Verification;
signature.initVerify(pubkey);
signature.update(datatoSign);
Verification=signature.verify(TheSign);