Home | 簡體中文 | 繁體中文 | 雜文 | 知乎專欄 | Github | OSChina 博客 | 雲社區 | 雲棲社區 | Facebook | Linkedin | 視頻教程 | 打賞(Donations) | About

3.2. SHA 專題

3.2.1. sha1sum

		
$ sha1sum /etc/passwd
c144c5cc8d5d3b90ad74a1dcf6af9e6c935e2a2a  /etc/passwd

$ sha1sum about/*
905a26de0f2fd6fcb53bf8db75d76c538d094237  about/index.html
d0aeb4409808b6afded0522964bed6b795d30fc0  about/index.tpl

$ sha1sum about/* > about.sha1
$ cat about.sha1
905a26de0f2fd6fcb53bf8db75d76c538d094237  about/index.html
d0aeb4409808b6afded0522964bed6b795d30fc0  about/index.tpl

$ sha1sum -c about.sha1
about/index.html: OK
about/index.tpl: OK

		
		

3.2.2. PHP sha1()

string sha1 ( string str [, bool raw_output] )


<?php
	$str = 'netkiller';
	echo sha1($str);
?>

		

運行輸出字元串:eb673aa189c814d2db9fb71f162da1c81b4eba1c

3.2.3. Java SHA

3.2.3.1. SHA

			
import java.security.*;

public class shaTest {

	private static String dumpBytes(byte[] bytes) {
	    int i;
	    StringBuffer sb = new StringBuffer();
	    for (i = 0; i < bytes.length; i++) {
	      if (i % 32 == 0 && i != 0) {
	        sb.append("\n");
	      }
	      String s = Integer.toHexString(bytes[i]);
	      if (s.length() < 2) {
	        s = "0" + s;
	      }
	      if (s.length() > 2) {
	        s = s.substring(s.length() - 2);
	      }
	      sb.append(s);
	    }
	    return sb.toString();
	}
	public static void main(String[] args) {

		String passwd = "netkiller";
	    MessageDigest md = null;
		try {
			md = MessageDigest.getInstance("SHA");
			md.update("chen".getBytes());
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}

	    System.out.println(dumpBytes(md.digest()));
	}

}
			
			

編譯運行,輸入字元串:8a89798cf0878e37bb6589ae1c36b9d8a036275b

3.2.3.2. SHA-256

			
package cn.netkiller.security;

import java.math.BigInteger;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class SHA256 {

	public SHA256() {
		// TODO Auto-generated constructor stub
	}

	public static void main(String[] args) throws NoSuchAlgorithmException {
		// TODO Auto-generated method stub
		MessageDigest md = MessageDigest.getInstance("SHA-256");
		String text = "Text to hash, cryptographically.";

		// Change this to UTF-16 if needed
		md.update(text.getBytes(StandardCharsets.UTF_8));
		byte[] digest = md.digest();

		String hex = String.format("%064x", new BigInteger(1, digest));
		System.out.println(hex);

	}

}
			
			
			

3.2.4. Perl

		
 # Functional style
 use Digest::SHA1  qw(sha1 sha1_hex sha1_base64);

 $digest = sha1($data);
 $digest = sha1_hex($data);
 $digest = sha1_base64($data);

 # OO style
 use Digest::SHA1;

 $ctx = Digest::SHA1->new;

 $ctx->add($data);
 $ctx->addfile(*FILE);

 $digest = $ctx->digest;
 $digest = $ctx->hexdigest;
 $digest = $ctx->b64digest;