Skip to Main Content

Java Security

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

Need help with SHA1

843811Nov 8 2007 — edited Nov 8 2007
Hi

I have a string that is passed to the SHA-1 encryption algorithm and returns a key. This key will be matched with a key generated from a PHP application which also uses SHA-1. I am sure my code is correct and the encryption works because i compared the key produced for the text "e" and it matched exactly the same key someone had displayed on this forum. However when i append some characters (i must append these characters to my text) to be encrypted, the key fails to match the PHP key.

I think its to do with the encoding of the string but i tried converting it to UTF-8, ASCII etc. when converting it to bytes (when passing it to the encryption algorithm) but no luck. Check out the variable bold"append"*bold* below. Those are the characters i need to append to my text and I believe that is causing the problem. The PHP version does not escape the "\" but i obviously have to. Could that be the cause? Any ideas?
String text= new String("san100200");
String append = "sans)3_J-M?9L7\\D6_DV_^1z\\_QX^SWW$_0N_A\\�EYz"; // this is what i think is causing the problem
text = text + append;
char[] DIGITS = {
    '0', '1', '2', '3', '4', '5', '6', '7',
       '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'
};

java.security.MessageDigest d =null;
try {
d = java.security.MessageDigest.getInstance("SHA-1");
} catch (NoSuchAlgorithmException e) {
	// TODO Auto-generated catch block
	e.printStackTrace();
}
d.reset();
d.update(text.getBytes());
byte[] hashBytes = d.digest();
int l = hashBytes.length;
StringBuffer s = new StringBuffer();
// two characters form the hex value.
for (int i = 0; i < l; i++) {
    s.append(DIGITS[(0xF0 & hashBytes) >>> 4 ]);
s.append(DIGITS[ 0x0F & hashBytes[i] ]);
}
System.out.println(s.toString());

Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Dec 6 2007
Added on Nov 8 2007
1 comment
326 views