Java version of the SHA-1

Source: Internet
Author: User
Tags abstract date bitwise final hash int size tostring javascript array
/**
* <b>this Java Class consists the server side for the Wondeful JavaScript library ' sha1.js '. I wrote it because I basically needed
* Some cheap client/server login authentication by the usual Key/data system. Besides, I got the creeps watching the password
* Posted unencrypted via HTTP requests. This class makes sure so if your client is using the ' sha1.js ' to encrypt the password
* With a key sent by the server, you can always repeat the encrypting on the server side (using the same key) and compare The
* Encrypted strings. Since Anyone who trapping the HTTP requests can actually send to you same encrypted string, I suggest
* Use the client's IP address as the base for the key generation. Since IP Address Spoofing isn't a problem, this authentication
* Method isn't a very secured solution. If you are need a full proof solution use SSL. However, this one, the sure beats nothing.
* Feel free to does with it whatever for you want</b>
* <p><b>this class is ' An Abstract class ' to ' Make sure ' don't create any new instances of it. It does not throw any exceptions and
* The code is much more ' C ' like than pure object oriented. There are no implemented interfaces and no inheritance in use. In fact, it
* is written as close as possible to the original JavaScript code. I did not test tweaking the instance variables but if your do change
* them, make sure to apply the same change in the ' sha1.js ' library or your won ' t get the same encrypted.
* Can call each one of the 6 work methods by using something LIKE:SHA1.HEX_HMAC_SHA1 ("key", "data");
* They are the only public methods. All are public and static. You have no reason the private ones anyway.</p></b>
* <p>the ' sha1.js ' is a JavaScript implementation of the Secure Hash algorithm, SHA-1, as defined in FIPS PUB 180-1.
* JavaScript Version 2.1 Copyright Paul Johnston 2000-2002. Contributors to JavaScript Version:greg Holt,
* Andrew Kepert, Ydnar, Lostinet distributed under the BSD license</p>
* <p>see <a href= "Http://pajhome.org.uk/crypt/md5" >http://pajhome.org.uk/crypt/md5</a> for Details.</p>
* <p><b>author: </b>t.n.silverman (C.t.xm-sia Riga, LV) <a href= "mailto:tnsilver@ctcm.com" > Mailto:tnsilver@ctxm.com</a>
* <br>creation Date: (3/27/2004 5:57:00 PM) </p>
* <p>don ' t forget to visit me <b>CTXM</b> site at <a href= "http://www.ctxm.com" >http://w Ww.ctxm.com</a> where you'll find reference to all of the games this code being used in.
*/
Public abstract class SHA1 {
Private static Final Boolean hexcase = false;/* hex output format. False-lowercase; True-uppercase *
private static final String B64pad = "="; /* base-64 pad character. "=" for strict RFC compliance * *
private static final int chrsz = 8; /* bits per input character. 8-ascii; 16-unicode *
/**
* This is one of the functions you'll usually want to call
* It take a string arguments and returns either Hex or BASE-64 encoded
* Creation Date: (3/27/2004 6:05:10 PM)
* @author T.n.silverman
* @version 1.0.0
* @return java.lang.String
* @param key java.lang.String
* @param data java.lang.String
*/
public static string B64_hmac_sha1 (string key, string data) {
Return binb2b64 (key, data) (CORE_HMAC_SHA1);
}
/**
* This is one of the functions you'll usually want to call
* It take a string argument and returns either Hex or BASE-64 encoded
* Creation Date: (3/27/2004 6:05:10 PM)
* @author T.n.silverman
* @version 1.0.0
* @return java.lang.String
* @param s Java.lang.String
*/
public static string B64_sha1 (string s) {
s = (s==null)? "": s;
Return binb2b64 (CORE_SHA1 (STR2BINB (s), s.length () * chrsz));
}
/**
* Convert An array of Big-endian words to a base-64 string
* Creation Date: (3/27/2004 6:05:10 PM)
* @author T.n.silverman
* @version 1.0.0
* @return java.lang.String
* @param BinArray int[]
*/
private static String binb2b64 (int[] binarray) {
String tab = "abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz0123456789+/";
String str = "";
BinArray = Strechbinarray (BinArray, Binarray.length * 4);
for (int i = 0; i < binarray.length * 4; i + + 3) {
int triplet =
(((Binarray[i >> 2] >> 8 * (3-i% 4)) & 0xFF) << 16)
| (((binarray[i + 1 >> 2] >> 8 * (3-(i + 1)% 4)) & 0xFF) << 8)
| ((Binarray[i + 2 >> 2] >> 8 * (3-(i + 2)% 4)) & 0xFF);
for (int j = 0; J < 4; J + +) {
if (I * 8 + J * 6 > Binarray.length * 32)
str = B64pad;
Else
str = Tab.charat ((triplet >> 6 * (3-J)) & 0x3F);
}
}
return Cleanb64str (str);
}
/**
* Convert An array of Big-endian words to a hex string.
* Creation Date: (3/27/2004 6:05:10 PM)
* @author T.n.silverman
* @version 1.0.0
* @return java.lang.String
* @param BinArray int[]
*/
private static String Binb2hex (int[] binarray) {
String Hex_tab = hexcase? "0123456789ABCDEF": "0123456789abcdef";
String str = "";
for (int i = 0; i < binarray.length * 4; i++) {
char a = (char) hex_tab.charat ((Binarray[i >> 2] >> ((3-i% 4) * 8 + 4)) & 0xF);
Char B = (char) hex_tab.charat ((Binarray[i >> 2] >> ((3-i% 4) * 8)) & 0xF);
str = (new Character (a). ToString () + new Character (b). ToString ());
}
return str;
}
/**
* Convert An array of Big-endian words to a string
* Creation Date: (3/27/2004 6:05:10 PM)
* @author T.n.silverman
* @version 1.0.0
* @return java.lang.String
* @param bin int[]
*/
private static String Binb2str (int[] bin) {
String str = "";
int mask = (1 << chrsz)-1;
for (int i = 0; i < bin.length * i + + = Chrsz)
STR + + (char) ((Bin[i >> 5] >>> (24-i%)) & mask);
return str;
}
/**
* Bitwise rotate a 32-bit number to the left.
* Creation Date: (3/26/2004 1:05:01 PM)
* @author T.n.silverman
* @version 1.0.0
* @return int
* @param num INT
* @param CNT INT
*/
private static int Bit_rol (int num, int cnt) {
return (num << cnt) | (Num >>> (32-cnt));
}
/**
* Cleans a base64 String from all of the trailing ' a ' or other
* Characters put there by binb2b64 that made the bin array
* 4 times larger than it originally is.
* Creation Date: (3/27/2004 6:05:10 PM)
* @author T.n.silverman
* @version 1.0.0
* @return java.lang.String
* @param str java.lang.String
*/
private static string Cleanb64str (String str) {
str = (str==null)? "": STR;
int len = Str.length ();
if (Len <= 1)
return str;
Char Trailchar = Str.charat (len-1);
String trailstr= "";
for (int i=len-1;i>=0 && Str.charat (i) ==trailchar;i--)
Trailstr + + Str.charat (i);
Return str.substring (0,str.indexof (TRAILSTR));
}
/**
* makes an int array of a length less than an array of length with all previous
* Cells at their previous indexes.
* Creation Date: (3/27/2004 6:05:10 PM)
* @author T.n.silverman
* @version 1.0.0
* @return int[]
* @param str java.lang.String
*/
private static int[] complete216 (int[] oldbin) {
if (oldbin.length >= 16)
return oldbin;
int[] Newbin = new Int[16-oldbin.length];
for (int i = 0; i < newbin.length newbin[i] = 0, i++);
Return concat (Oldbin, Newbin);
}
/**
* Joins two int arrays and return one of that contains the previous values.
* This corresponds to the concat method of the JavaScript Array object.
* Creation Date: (3/27/2004 6:05:10 PM)
* @author T.n.silverman
* @version 1.0.0
* @return int[]
* @param str java.lang.String
*/
private static int[] Concat (int[] oldbin, int[] newbin) {
int[] retval = new Int[oldbin.length + newbin.length];
for (int i = 0; I < (oldbin.length + newbin.length); i++) {
if (I < oldbin.length)
Retval[i] = Oldbin[i];
Else
Retval[i] = Newbin[i-oldbin.length];
}
return retval;
}
/**
* Calculate the HMAC-SHA1 of a key and some data
* Creation Date: (3/26/2004 1:05:01 PM)
* @author T.n.silverman
* @version 1.0.0
* @return int
* @param x java.lang.string[]
* @param len Int
*/
private static int[] CORE_HMAC_SHA1 (string key, string data) {
Key = (key = null)? "": Key;
data = (data = null)? "": Data;
int[] Bkey = complete216 (STR2BINB (key));
if (Bkey.length > 16)
Bkey = CORE_SHA1 (Bkey, Key.length () * Chrsz);
int[] ipad = new INT[16];
int[] Opad = new INT[16];
for (int i = 0; i < ipad[i] = 0, Opad[i] = 0, i++);
for (int i = 0; i < i++) {
Ipad[i] = bkey[i] ^ 0x36363636;
Opad[i] = bkey[i] ^ 0x5c5c5c5c;
}
Int[] Hash =
CORE_SHA1 (ipad, STR2BINB (data)), Concat + data.length () * Chrsz);
Return Core_sha1 (concat (Opad, hash), 512 + 160);
}
/**
* Calculate The SHA-1 of an array of Big-endian words, and a bit length
* Creation Date: (3/26/2004 1:05:01 PM)
* @author T.n.silverman
* @version 1.0.0
* @return int
* @param x java.lang.string[]
* @param len Int
*/
private static int[] CORE_SHA1 (int[] x, int len) {
/* Append padding * *
int size = (len >> 5);
x = Strechbinarray (x, size);
X[len >> 5] |= 0x80 << (24-len% 32);
Size = ((len + >> 9) << 4) + 15;
x = Strechbinarray (x, size);
x[(len + >> 9) << 4) = Len;
int[] W = new int[80];
int a = 1732584193;
int b =-271733879;
int c =-1732584194;
int d = 271733878;
int e =-1009589776;
for (int i = 0; i < x.length i + + 16) {
int Olda = A;
int oldb = b;
int OLDC = c;
int oldd = D;
int olde = e;
for (int j = 0; J <; J + +) {
if (J < 16)
W[J] = X[i + j];
Else
W[J] = Rol (w[j-3] ^ w[j-8] ^ w[j-14] ^ w[j-16], 1);
int t =
Safe_add (
Safe_add (Rol (A, 5), sha1_ft (J, B, C, D)),
Safe_add (Safe_add (E, w[j]), Sha1_kt (j)));
e = D;
D = C;
c = Rol (b, 30);
b = A;
A = t;
}
A = Safe_add (A, Olda);
b = Safe_add (b, oldb);
c = Safe_add (c, OLDC);
D = Safe_add (d, OLDD);
E = Safe_add (e, Olde);
}
int[] retval = new INT[5];
Retval[0] = A;
RETVAL[1] = b;
RETVAL[2] = c;
RETVAL[3] = D;
RETVAL[4] = e;
return retval;
}
/**
* Just a test function to output the results of the "6 working funcions to the" standard out.
* The two Strings used as parameters are null. Feel free to test with different values.
* Creation Date: (3/27/20046:05:10pm)
* @author T.n.silverman
* @version 1.0.0
* @return java.lang.String
*/
private static void Dotest () {
String key= "Key";
String data= "Data";
System.out.println ("HEX_SHA1 (" + data + ") =" + HEX_SHA1 (data));
System.out.println ("B64_SHA1 (" + data + ") =" + B64_SHA1 (data));
System.out.println ("STR_SHA1 (" + data + ") =" + STR_SHA1 (data));
System.out.println ("HEX_HMAC_SHA1 + key +", "+ Data +") = "+ HEX_HMAC_SHA1 (key, data));
System.out.println ("B64_HMAC_SHA1 + key +", "+ Data +") = "+ B64_HMAC_SHA1 (key, data));
System.out.println ("STR_HMAC_SHA1 + key +", "+ Data +") = "+ STR_HMAC_SHA1 (key, data));
}
/**
* This is one of the functions you'll usually want to call
* It take a string arguments and returns either Hex or BASE-64 encoded
* Creation Date: (3/27/2004 6:05:10 PM)
* @author T.n.silverman
* @version 1.0.0
* @return java.lang.String
* @param key java.lang.String
* @param data java.lang.String
*/
public static string Hex_hmac_sha1 (string key, string data) {
Return Binb2hex (key, data) (CORE_HMAC_SHA1);
}
/**
* This is one of the functions you'll usually want to call
* It take a string argument and returns either Hex or BASE-64 encoded
* Creation Date: (3/27/2004 6:05:10 PM)
* @author T.n.silverman
* @version 1.0.0
* @return java.lang.String
* @param s Java.lang.String
*/
public static string Hex_sha1 (string s) {
s = (s = = null)? "": s;
Return Binb2hex (CORE_SHA1 (STR2BINB (s), s.length () * chrsz));
}
/**
* Bitwise rotate a 32-bit number to the left. * Creation Date: (3/26/2004 1:05:01 PM)
* Creation Date: (3/27/2004 6:05:10 PM)
* @author T.n.silverman
* @version 1.0.0
* @return int
* @param num INT
* @param CNT INT
*/
private static int rol (int num, int cnt) {
return (num << cnt) | (Num >>> (32-cnt));
}
/**
* Add ints, wrapping at 2^32. This uses 16-bit operations internally
* To work around bugs in some JS interpreters. The original function
* is part of the Sha1.js library. It ' s here for compatibility.
* Creation Date: (3/26/2004 1:05:01 PM)
* @author T.n.silverman
* @version 1.0.0
* @return int
* @param num INT
* @param CNT INT
*/
private static int Safe_add (int x, int y) {
int LSW = (int) (x & 0xFFFF) + (int) (Y & 0xFFFF);
int MSW = (x >>) + (y >>) + (LSW >> 16);
Return (MSW << 16) | (LSW & 0xFFFF);
}
/**
* Perform the appropriate triplet combination function for the current
* Creation Date: (3/26/2004 1:05:01 PM)
* @author T.n.silverman
* @version 1.0.0
* @return int
* @param t int
* @param b int
* @param c int
* @param d int
*/
private static int sha1_ft (int t, int b, int c, int d) {
if (T < 20)
Return (b & c) | ((~b) & D);
if (T < 40)
Return b ^ C ^ D;
if (T < 60)
Return (b & c) | (b & D) | (C & D);
Return b ^ C ^ D;
}
/**
* Determine the appropriate additive constant for the current iteration
* Creation Date: (3/26/2004 1:05:01 PM)
* @author T.n.silverman
* @version 1.0.0
* @return int
* @param t int
*/
private static int sha1_kt (int t) {
Return (T < 20)
? 1518500249
: (T < 40)
? 1859775393
: (T < 60)
? -1894007588
:-899497514;
}
/**
* This is a Boolean returnig test function that exists in the Sha1.js library.
* If it returns ' false ' something is wrong.
* Creation Date: (3/26/2004 1:05:01 PM)
* @author T.n.silverman
* @version 1.0.0
* @return java.lang.String
* @param s Java.lang.String
*/
private static Boolean sha1_vm_test () {
Return hexcase? HEX_SHA1 ("abc"). Equals ("a9993e364706816aba3e25717850c26c9cd0d89d"): HEX_SHA1 ("abc"). Equals (" a9993e364706816aba3e25717850c26c9cd0d89d ");
}
/**
* This is one of the functions you'll usually want to call
* It take a string arguments and returns either Hex or BASE-64 encoded
* Creation Date: (3/26/2004 1:05:01 PM)
* @author T.n.silverman
* @version 1.0.0
* @return java.lang.String
* @param key java.lang.String
* @param data java.lang.String
*/
public static string Str_hmac_sha1 (string key, string data) {
Return Binb2str (key, data) (CORE_HMAC_SHA1);
}
/**
* This is one of the functions you'll usually want to call
* It take a string argument and returns either Hex or BASE-64 encoded
* Creation Date: (3/26/2004 1:05:01 PM)
* @author T.n.silverman
* @version 1.0.0
* @return java.lang.String
* @param s Java.lang.String
*/
public static string Str_sha1 (string s) {
s = (s = = null)? "": s;
Return Binb2str (CORE_SHA1 (STR2BINB (s), s.length () * chrsz));
}
/**
* Convert an 8-bit or 16-bit string to an array of Big-endian words
* in 8-bit function characters >255 have their hi-byte silently.
* Creation Date: (3/26/2004 1:05:01 PM)
* @author T.n.silverman
* @version 1.0.0
* @return int[]
* @param str java.lang.String
*/
private static int[] Str2binb (String str) {
str = (str==null)? "": STR;
int[] tmp = new Int[str.length () * Chrsz];
int mask = (1 << chrsz)-1;
for (int i = 0; i < str.length () * chrsz i = = Chrsz)
TMP[I&GT;&GT;5] |= ((int) (Str.charat (I/chrsz)) & mask) << (24-i%32);

int len = 0;
for (int i=0;i<tmp.length&&tmp[i]!=0;i++,len++);
int[] bin = new Int[len];
for (int i=0;i<len;i++)
Bin[i] = Tmp[i];
return bin;
}
/**
* Increase an int array to a desired sized + 1 while keeping the old values.
* Creation Date: (3/26/2004 1:05:01 PM)
* @author T.n.silverman
* @version 1.0.0
* @return int[]
* @param str java.lang.String
*/
private static int[] Strechbinarray (int[] oldbin, int size) {
int currlen = Oldbin.length;
if (currlen >= size + 1)
return oldbin;
int[] Newbin = new Int[size + 1];
for (int i = 0; i < size; Newbin[i] = 0, i++);
for (int i = 0; i < Currlen; i++)
Newbin[i] = Oldbin[i];
return newbin;
}
}





Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.