1

I am creating a blackberry application which sends the request to the server. So authentication of the user is required. So for doing this i want to encrypt UserID and password using SHA1 in blackberry. The encrypted data which is made using SHA1 algorithm on UserID and password is then passed to the server.

My problem is how do i implement this. Can someone give the sample code for implementing this in blackberry.

Mat
  • 202,337
  • 40
  • 393
  • 406
user913436
  • 33
  • 6

2 Answers2

2

SHA1 is not an encryption algorithm. It is hash-function.

http://en.wikipedia.org/wiki/SHA1

If you are talking about Basic Authentication, then you need to use Base64 algorithm to hash username and password.

Here is discussed topic about this issue: HTTP authentication in J2ME

Community
  • 1
  • 1
  • Sorry for using wrong words, I'll correct it. So i don't need encrypted string but hashed value which i can encode it... So how do i do it..Please put some sample code for example – user913436 Oct 02 '11 at 09:03
  • Use [SHA1Digest](http://www.blackberry.com/developers/docs/4.1api/net/rim/device/api/crypto/SHA1Digest.html) class. And there is a [link to sample code](http://www.blackberry.com/developers/docs/4.1api/net/rim/device/api/crypto/doc-files/CryptoTest.html#sampleSHA1MAC). –  Oct 02 '11 at 09:07
2

add this class

public class Sha1 {

private static String convertToHex(byte[] data) {
    StringBuffer buf = new StringBuffer();
    for (int i = 0; i < data.length; i++) {
        int halfbyte = (data[i] >>> 4) & 0x0F;
        int two_halfs = 0;
        do {
            if ((0 <= halfbyte) && (halfbyte <= 9))
                buf.append((char) ('0' + halfbyte));
            else
                buf.append((char) ('a' + (halfbyte - 10)));
            halfbyte = data[i] & 0x0F;
        } while (two_halfs++ < 1);
    }
    return buf.toString();
}

public static String SHA1(String text) {
    SHA1Digest sha1Digest = new SHA1Digest();
    sha1Digest.update(text.getBytes(), 0, text.length());
    byte[] hashValBytes = new byte[sha1Digest.getDigestLength()];
    hashValBytes = sha1Digest.getDigest();
    return convertToHex(hashValBytes);
}
}

then on your code , Write

 sha1 = Sha1.SHA1(email);
Rince Thomas
  • 4,158
  • 5
  • 25
  • 44