SHA1 加密源码

SHA1加密(Java版)
public class SHA1 {  

    private static final boolean hexcase = false;  
    private static final int chrsz = 8;  
 
    // 得到字符串SHA-1值的方法  
    public static String hex_sha1(String s) {  
        s = (s == null) ? "" : s;  
        return binb2hex(core_sha1(str2binb(s), s.length() * chrsz));  
    }  
 
    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;  
    }  
 
    private static String binb2str(int[] bin) {  
        String str = "";  
        int mask = (1 << chrsz) - 1;  
 
        for (int i = 0; i < bin.length * 32; i += chrsz) {  
            str += (char) ((bin[i >> 5] >>> (24 - i % 32)) & mask);  
        }  
        return str;  
    }  
 
    private static int[] core_sha1(int[] x, int len) {  
        int size = (len >> 5);  
        x = strechbinarray(x, size);  
        x[len >> 5] |= 0x80 << (24 - len % 32);  
        size = ((len + 64 >> 9) << 4) + 15;  
        x = strechbinarray(x, size);  
        x[((len + 64 >> 9) << 4) + 15] = 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 < 80; 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;  
    }  
 
    private static int rol(int num, int cnt) {  
        return (num << cnt) | (num >>> (32 - cnt));  
    }  
 
    private static int safe_add(int x, int y) {  
        int lsw = (int) (x & 0xffff) + (int) (y & 0xffff);  
        int msw = (x >> 16) + (y >> 16) + (lsw >> 16);  
 
        return (msw << 16) | (lsw & 0xffff);  
    }  
 
    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;  
    }  
 
    private static int sha1_kt(int t) {  
        return (t < 20) ? 1518500249 : (t < 40) ? 1859775393 : (t < 60) ? -1894007588 : -899497514;  
    }  
 
    public static String str_sha1(String s) {  
        s = (s == null) ? "" : s;  
 
        return binb2str(core_sha1(str2binb(s), s.length() * chrsz));  
    }  
 
    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 >> 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;  
    }  
 
    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;  
    }  
} 

测试类:
 public static void main(String args[]) {  
        System.out.println(SHA1.hex_sha1("123456"));  
}


SHA1加密(Flex版)
package
{
	import flash.utils.ByteArray;
	import mx.utils.Base64Encoder;
	
	/**
	 *  US Secure Hash Algorithm 1 (SHA1)
	 */
	public class SHA1
	{
		
		private static var hexChars:String = "0123456789abcdef";
		
		public static var digest:ByteArray;
		
		/**
		 *  Performs the SHA1 hash algorithm on a string.
		 *
		 *  @param s		The string to hash
		 *  @return			A string containing the hash value of s
		 *  @langversion	ActionScript 3.0
		 *  @playerversion	9.0
		 *  @tiptext
		 */
		public static function hash( s:String ):String
		{
			var blocks:Array = createBlocksFromString( s );
			var byteArray:ByteArray = hashBlocks( blocks );
			
			return toHex( byteArray.readInt(), true )
				+ toHex( byteArray.readInt(), true )
				+ toHex( byteArray.readInt(), true )
				+ toHex( byteArray.readInt(), true )
				+ toHex( byteArray.readInt(), true );
		}
		
		public static function hashBytes( data:ByteArray ):String
		{
			var blocks:Array = SHA1.createBlocksFromByteArray( data );
			var byteArray:ByteArray = hashBlocks(blocks);
			
			return toHex( byteArray.readInt(), true )
				+ toHex( byteArray.readInt(), true )
				+ toHex( byteArray.readInt(), true )
				+ toHex( byteArray.readInt(), true )
				+ toHex( byteArray.readInt(), true );
		}
		
		public static function hashToBase64( s:String ):String
		{
			var blocks:Array = SHA1.createBlocksFromString( s );
			var byteArray:ByteArray = hashBlocks(blocks);

			var charsInByteArray:String = "";
			byteArray.position = 0;
			for (var j:int = 0; j < byteArray.length; j++)
			{
				var byte:uint = byteArray.readUnsignedByte();
				charsInByteArray += String.fromCharCode(byte);
			}
			
			var encoder:Base64Encoder = new Base64Encoder();
			encoder.encode(charsInByteArray);
			return encoder.flush();
		}
		
		private static function rol ( x:int, n:int ):int {
			return ( x << n ) | ( x >>> ( 32 - n ) );
		}
		private static function ror ( x:int, n:int ):uint {
			var nn:int = 32 - n;
			return ( x << nn ) | ( x >>> ( 32 - nn ) );
		}
		
		private static function toHex( n:int, bigEndian:Boolean = false ):String {
			var s:String = "";
			
			if ( bigEndian ) {
				for ( var i:int = 0; i < 4; i++ ) {
					s += hexChars.charAt( ( n >> ( ( 3 - i ) * 8 + 4 ) ) & 0xF ) 
						+ hexChars.charAt( ( n >> ( ( 3 - i ) * 8 ) ) & 0xF );
				}
			} else {
				for ( var x:int = 0; x < 4; x++ ) {
					s += hexChars.charAt( ( n >> ( x * 8 + 4 ) ) & 0xF )
						+ hexChars.charAt( ( n >> ( x * 8 ) ) & 0xF );
				}
			}
			return s;
		}
		
		private static function hashBlocks( blocks:Array ):ByteArray
		{
			var h0:int = 0x67452301;
			var h1:int = 0xefcdab89;
			var h2:int = 0x98badcfe;
			var h3:int = 0x10325476;
			var h4:int = 0xc3d2e1f0;
			
			var len:int = blocks.length;
			var w:Array = new Array( 80 );
			
			for ( var i:int = 0; i < len; i += 16 ) {
				
				var a:int = h0;
				var b:int = h1;
				var c:int = h2;
				var d:int = h3;
				var e:int = h4;
				
				for ( var t:int = 0; t < 80; t++ ) {
					
					if ( t < 16 ) {
						// 6.1.a
						w[ t ] = blocks[ i + t ];
					} else {
						// 6.1.b
						w[ t ] = rol( w[ t - 3 ] ^ w[ t - 8 ] ^ w[ t - 14 ] ^ w[ t - 16 ], 1 );
					}
					
					// 6.1.d
					var temp:int = rol( a, 5 ) + f( t, b, c, d ) + e + int( w[ t ] ) + k( t );
					
					e = d;
					d = c;
					c = rol( b, 30 );
					b = a;
					a = temp;
				}
				
				// 6.1.e
				h0 += a;
				h1 += b;
				h2 += c;
				h3 += d;
				h4 += e;		
			}
			
			var byteArray:ByteArray = new ByteArray();
			byteArray.writeInt(h0);
			byteArray.writeInt(h1);
			byteArray.writeInt(h2);
			byteArray.writeInt(h3);
			byteArray.writeInt(h4);
			byteArray.position = 0;
			
			digest = new ByteArray();
			digest.writeBytes(byteArray);
			digest.position = 0;
			return byteArray;
		}
		
		private static function f( t:int, b:int, c:int, d:int ):int {
			if ( t < 20 ) {
				return ( b & c ) | ( ~b & d );
			} else if ( t < 40 ) {
				return b ^ c ^ d;
			} else if ( t < 60 ) {
				return ( b & c ) | ( b & d ) | ( c & d );
			}
			return b ^ c ^ d;
		}
		
		private static function k( t:int ):int {
			if ( t < 20 ) {
				return 0x5a827999;
			} else if ( t < 40 ) {
				return 0x6ed9eba1;
			} else if ( t < 60 ) {
				return 0x8f1bbcdc;
			}
			return 0xca62c1d6;
		}
		
		private static function createBlocksFromByteArray( data:ByteArray ):Array
		{
			var oldPosition:int = data.position;
			data.position = 0;
			
			var blocks:Array = new Array();
			var len:int = data.length * 8;
			var mask:int = 0xFF; // ignore hi byte of characters > 0xFF
			for( var i:int = 0; i < len; i += 8 )
			{
				blocks[ i >> 5 ] |= ( data.readByte() & mask ) << ( 24 - i % 32 );
			}
			
			// append padding and length
			blocks[ len >> 5 ] |= 0x80 << ( 24 - len % 32 );
			blocks[ ( ( ( len + 64 ) >> 9 ) << 4 ) + 15 ] = len;
			
			data.position = oldPosition;
			
			return blocks;
		}
		
		private static function createBlocksFromString( s:String ):Array
		{
			var blocks:Array = new Array();
			var len:int = s.length * 8;
			var mask:int = 0xFF; // ignore hi byte of characters > 0xFF
			for( var i:int = 0; i < len; i += 8 ) {
				blocks[ i >> 5 ] |= ( s.charCodeAt( i / 8 ) & mask ) << ( 24 - i % 32 );
			}
			
			// append padding and length
			blocks[ len >> 5 ] |= 0x80 << ( 24 - len % 32 );
			blocks[ ( ( ( len + 64 ) >> 9 ) << 4 ) + 15 ] = len;
			return blocks;
		}
		
	}
}

测试类:
public function init():void{			
    Alert.show(SHA1.hash("123456"));
}


Flex使用mx.utils.SHA256类来实现SHA256加密:
package
{
	import flash.utils.ByteArray;
	import mx.utils.SHA256;
	public class SHA256_Test
	{
		public function SHA256_Test(){}
		
		public static function sha_256(source : String):String{
			var encryption : String;
			
			var ba : ByteArray = new ByteArray();
			ba.writeUTFBytes(source);
			encryption = mx.utils.SHA256.computeDigest(ba);
			
			return encryption;
		}
	}
}

测试类:
public function init():void{			
    Alert.show(SHA256_Test.sha_256("123456"));
}

你可能感兴趣的:(C++,c,C#,Flex,J#)