구조 사의 sha 암호 화 복호화

19126 단어 암호 화 복호화
1.머리말.
제목 과 같다.
2.코드.

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * reference apache commons <a
 * href="http://commons.apache.org/codec/">http://commons.apache.org/codec/</a>
 *
 * support MD2/MD5/SHA/SHA256/SHA384/SHA512
 * @author Aub
 *
 */
public class DigestUtils {

 /**
  *                   
  *
  * @param algorithm
  *                 
  * @return       
  * @see MessageDigest#getInstance(String)
  * @throws RuntimeException
  *               {@link java.security.NoSuchAlgorithmException}    
  */
 static MessageDigest getDigest(String algorithm) {
  try {
   return MessageDigest.getInstance(algorithm);
  } catch (NoSuchAlgorithmException e) {
   throw new RuntimeException(e.getMessage());
  }
 }

 /**
  *    MD5       
  *
  * @return MD5       
  * @throws RuntimeException
  *               {@link java.security.NoSuchAlgorithmException}    
  */
 private static MessageDigest getMd5Digest() {
  return getDigest("MD5");
 }

 /**
  *    SHA-1       
  *
  * @return SHA-1       
  * @throws RuntimeException
  *               {@link java.security.NoSuchAlgorithmException}    
  */
 private static MessageDigest getShaDigest() {
  return getDigest("SHA");
 }

 /**
  *    SHA-256       
  *
  * @return SHA-256       
  * @throws RuntimeException
  *               {@link java.security.NoSuchAlgorithmException}    
  */
 private static MessageDigest getSha256Digest() {
  return getDigest("SHA-256");
 }

 /**
  *    SHA-384       
  *
  * @return SHA-384       
  * @throws RuntimeException
  *               {@link java.security.NoSuchAlgorithmException}    
  */
 private static MessageDigest getSha384Digest() {
  return getDigest("SHA-384");
 }

 /**
  *    SHA-512       
  *
  * @return SHA-512       
  * @throws RuntimeException
  *               {@link java.security.NoSuchAlgorithmException}    
  */
 private static MessageDigest getSha512Digest() {
  return getDigest("SHA-512");
 }

 /**
  *   MD5            
  *
  * @param data
  *                    
  * @return     (   16     )
  */
 public static byte[] encodeMD5(byte[] data) {
  return getMd5Digest().digest(data);
 }

 /**
  *   MD5            
  *
  * @param data
  *                    
  * @return     (   32        )
  */
 public static String encodeMD5Hex(byte[] data) {
  return Hex.encodeHexStr(encodeMD5(data));
 }

 /**
  *   SHA-1            
  *
  * @param data
  *                    
  * @return SHA-1    (   20     )
  */
 public static byte[] encodeSHA(byte[] data) {
  return getShaDigest().digest(data);
 }

 /**
  *   SHA-1            
  *
  * @param data
  *                    
  * @return SHA-1    (   40        )
  */
 public static String encodeSHAHex(byte[] data) {
  return Hex.encodeHexStr(getShaDigest().digest(data));
 }

 /**
  *   SHA-256            
  *
  * @param data
  *                    
  * @return SHA-256    (   32     )
  */
 public static byte[] encodeSHA256(byte[] data) {
  return getSha256Digest().digest(data);
 }

 /**
  *   SHA-256            
  *
  * @param data
  *                    
  * @return SHA-256    (   64        )
  */
 public static String encodeSHA256Hex(byte[] data) {
  return Hex.encodeHexStr(encodeSHA256(data));
 }

 /**
  *   SHA-384            
  *
  * @param data
  *                    
  * @return SHA-384    (   43     )
  */
 public static byte[] encodeSHA384(byte[] data) {
  return getSha384Digest().digest(data);
 }

 /**
  *   SHA-384            
  *
  * @param data
  *                    
  * @return SHA-384    (   86        )
  */
 public static String encodeSHA384Hex(byte[] data) {
  return Hex.encodeHexStr(encodeSHA384(data));
 }

 /**
  *   SHA-512            
  *
  * @param data
  *                    
  * @return SHA-512    (   64     )
  */
 public static byte[] encodeSHA512(byte[] data) {
  return getSha512Digest().digest(data);
 }

 /**
  *   SHA-512            
  *
  * @param data
  *                    
  * @return SHA-512    (   128        )
  */
 public static String encodeSHA512Hex(byte[] data) {
  return Hex.encodeHexStr(encodeSHA512(data));
 }

}

 

import java.security.InvalidKeyException;
import java.security.Key;
import java.security.NoSuchAlgorithmException;

import javax.crypto.KeyGenerator;
import javax.crypto.Mac;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

/**
 * Hmac<br/>
 * algorithm HmacMD5/HmacSHA/HmacSHA256/HmacSHA384/HmacSHA512
 * @author Aub
 */
public class Hmac {
 
 /**
  *               
  *
  * @param algorithm
  *                
  * @return   
  * @throws RuntimeException
  *               {@link java.security.NoSuchAlgorithmException}    
  */
 private static byte[] getHmacKey(String algorithm){
  //   KeyGenerator
  KeyGenerator keyGenerator = null;
  try {
   keyGenerator = KeyGenerator.getInstance(algorithm);
  } catch (NoSuchAlgorithmException e) {
   throw new RuntimeException(e.getMessage());
  }
  //    
  SecretKey secretKey = keyGenerator.generateKey();
  //    
  return secretKey.getEncoded();
 }
 
 /**
  *    HmaMD5   
  *
  * @return  HmaMD5   
  * @throws RuntimeException
  *               {@link java.security.NoSuchAlgorithmException}    
  */
 public static byte[] getHmaMD5key(){
  return getHmacKey("HmacMD5");
 }
 
 /**
  *    HmaSHA   
  *
  * @return  HmaSHA   
  * @throws RuntimeException
  *               {@link java.security.NoSuchAlgorithmException}    
  */
 public static byte[] getHmaSHAkey(){
  return getHmacKey("HmacSHA1");
 }
 
 /**
  *    HmaSHA256   
  *
  * @return  HmaSHA256   
  * @throws RuntimeException
  *               {@link java.security.NoSuchAlgorithmException}    
  */
 public static byte[] getHmaSHA256key(){
  return getHmacKey("HmacSHA256");
 }
 
 /**
  *    HmaSHA384   
  *
  * @return  HmaSHA384   
  * @throws RuntimeException
  *               {@link java.security.NoSuchAlgorithmException}    
  */
 public static byte[] getHmaSHA384key(){
  return getHmacKey("HmacSHA384");
 }
 
 /**
  *    HmaSHA512   
  *
  * @return  HmaSHA384   
  * @throws RuntimeException
  *               {@link java.security.NoSuchAlgorithmException}    
  */
 public static byte[] getHmaSHA512key(){
  return getHmacKey("HmacSHA512");
 }
 
 /**
  *     
  *
  * @param key      
  * @param algorithm     
  * @return   
  */
 private static Key toKey(byte[] key,String algorithm){
  //    
  return new SecretKeySpec(key, algorithm);
 }
 
 /**
  *   HmacMD5            
  *
  * @param data         
  * @param key   
  * @return     (   16     )
  */
 public static byte[] encodeHmacMD5(byte[] data, Key key){
  Mac mac = null;
  try {
   mac = Mac.getInstance("HmacMD5");
   mac.init(key);
  } catch (NoSuchAlgorithmException e) {
   e.printStackTrace();
   return new byte[0];
  }catch (InvalidKeyException e) {
   e.printStackTrace();
   return new byte[0];
  }
  return mac.doFinal(data);
 }
 
 /**
  *   HmacMD5            
  *
  * @param data         
  * @param key   
  * @return     (   16     )
  */
 public static byte[] encodeHmacMD5(byte[] data, byte[] key){
  Key k = toKey(key, "HmacMD5");
  return encodeHmacMD5(data, k);
 }
 
 /**
  *   HmacSHA            
  *
  * @param data         
  * @param key   
  * @return     (   16     )
  */
 public static byte[] encodeHmacSHA(byte[] data, Key key){
  Mac mac = null;
  try {
   mac = Mac.getInstance("HmacSHA1");
   mac.init(key);
  } catch (NoSuchAlgorithmException e) {
   e.printStackTrace();
   return new byte[0];
  }catch (InvalidKeyException e) {
   e.printStackTrace();
   return new byte[0];
  }
  return mac.doFinal(data);
 }
 
 /**
  *   HmacSHA            
  *
  * @param data         
  * @param key   
  * @return     (   16     )
  */
 public static byte[] encodeHmacSHA(byte[] data, byte[] key){
  Key k = toKey(key, "HmacSHA1");
  return encodeHmacSHA(data, k);
 }
 
 /**
  *   HmacSHA256            
  *
  * @param data         
  * @param key   
  * @return     (   16     )
  */
 public static byte[] encodeHmacSHA256(byte[] data, Key key){
  Mac mac = null;
  try {
   mac = Mac.getInstance("HmacSHA256");
   mac.init(key);
  } catch (NoSuchAlgorithmException e) {
   e.printStackTrace();
   return new byte[0];
  }catch (InvalidKeyException e) {
   e.printStackTrace();
   return new byte[0];
  }
  return mac.doFinal(data);
 }
 
 /**
  *   HmacSHA256            
  *
  * @param data         
  * @param key   
  * @return     (   16     )
  */
 public static byte[] encodeHmacSHA256(byte[] data, byte[] key){
  Key k = toKey(key, "HmacSHA256");
  return encodeHmacSHA256(data, k);
 }
 
 
 /**
  *   HmacSHA384            
  *
  * @param data         
  * @param key   
  * @return     (   16     )
  */
 public static byte[] encodeHmacSHA384(byte[] data, Key key){
  Mac mac = null;
  try {
   mac = Mac.getInstance("HmacSHA384");
   mac.init(key);
  } catch (NoSuchAlgorithmException e) {
   e.printStackTrace();
   return new byte[0];
  }catch (InvalidKeyException e) {
   e.printStackTrace();
   return new byte[0];
  }
  return mac.doFinal(data);
 }
 
 /**
  *   HmacSHA384            
  *
  * @param data         
  * @param key   
  * @return     (   16     )
  */
 public static byte[] encodeHmacSHA384(byte[] data, byte[] key){
  Key k = toKey(key, "HmacSHA384");
  return encodeHmacSHA384(data, k);
 }
 
 
 
 /**
  *   HmacSHA512            
  *
  * @param data         
  * @param key   
  * @return     (   16     )
  */
 public static byte[] encodeHmacSHA512(byte[] data, Key key){
  Mac mac = null;
  try {
   mac = Mac.getInstance("HmacSHA512");
   mac.init(key);
  } catch (NoSuchAlgorithmException e) {
   e.printStackTrace();
   return new byte[0];
  }catch (InvalidKeyException e) {
   e.printStackTrace();
   return new byte[0];
  }
  return mac.doFinal(data);
 }
 
 /**
  *   HmacSHA512            
  *
  * @param data         
  * @param key   
  * @return     (   16     )
  */
 public static byte[] encodeHmacSHA512(byte[] data, byte[] key){
  Key k = toKey(key, "HmacSHA512");
  return encodeHmacSHA512(data, k);
 }
 
 
 private static String  showByteArray(byte[] data){
  if(null == data){
   return null;
  }
  StringBuilder sb = new StringBuilder("{");
  for(byte b:data){
   sb.append(b).append(",");
  }
  sb.deleteCharAt(sb.length()-1);
  sb.append("}");
  return sb.toString();
 }
 
 public static void main(String[] args) {
//  byte[] key = getHmaMD5key();
//  byte[] key = getHmaSHAkey();
//  byte[] key = getHmaSHA256key();
//  byte[] key = getHmaSHA384key();
  byte[] key = getHmaSHA512key();
  
  
  System.out.println("    : byte[]:"+showByteArray(key).length());
  
  String data = "Mac  ";
  System.out.println("     : string:"+data);
  System.out.println("     : byte[]:"+showByteArray(data.getBytes()));
  System.out.println();
//  byte[] encodeData = encodeHmacMD5(data.getBytes(), key);
//  byte[] encodeData = encodeHmacSHA(data.getBytes(), key);
//  byte[] encodeData = encodeHmacSHA256(data.getBytes(), key);
//  byte[] encodeData = encodeHmacSHA384(data.getBytes(), key);
  byte[] encodeData = encodeHmacSHA512(data.getBytes(), key);
  System.out.println("     : byte[]:"+showByteArray(encodeData).length());
  System.out.println("     : byte[]:"+encodeData.length);
  System.out.println("     : hexStr:"+Hex.encodeHexStr(encodeData));
  System.out.println();
 }
}

 

 

/**
 * reference apache commons <a
 * href="http://commons.apache.org/codec/">http://commons.apache.org/codec/</a>
 *
 * @author Aub
 *
 */
public class Hex {

 /**
  *                     
  */
 private static final char[] DIGITS_LOWER = { '0', '1', '2', '3', '4', '5',
   '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };

 /**
  *                     
  */
 private static final char[] DIGITS_UPPER = { '0', '1', '2', '3', '4', '5',
   '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };

 /**
  *                 
  *
  * @param data
  *            byte[]
  * @return     char[]
  */
 public static char[] encodeHex(byte[] data) {
  return encodeHex(data, true);
 }

 /**
  *                 
  *
  * @param data
  *            byte[]
  * @param toLowerCase
  *            <code>true</code>         , <code>false</code>        
  * @return     char[]
  */
 public static char[] encodeHex(byte[] data, boolean toLowerCase) {
  return encodeHex(data, toLowerCase ? DIGITS_LOWER : DIGITS_UPPER);
 }

 /**
  *                 
  *
  * @param data
  *            byte[]
  * @param toDigits
  *                   char[]
  * @return     char[]
  */
 protected static char[] encodeHex(byte[] data, char[] toDigits) {
  int l = data.length;
  char[] out = new char[l << 1];
  // two characters form the hex value.
  for (int i = 0, j = 0; i < l; i++) {
   out[j++] = toDigits[(0xF0 & data[i]) >>> 4];
   out[j++] = toDigits[0x0F & data[i]];
  }
  return out;
 }

 /**
  *                
  *
  * @param data
  *            byte[]
  * @return     String
  */
 public static String encodeHexStr(byte[] data) {
  return encodeHexStr(data, true);
 }

 /**
  *                
  *
  * @param data
  *            byte[]
  * @param toLowerCase
  *            <code>true</code>         , <code>false</code>        
  * @return     String
  */
 public static String encodeHexStr(byte[] data, boolean toLowerCase) {
  return encodeHexStr(data, toLowerCase ? DIGITS_LOWER : DIGITS_UPPER);
 }

 /**
  *                
  *
  * @param data
  *            byte[]
  * @param toDigits
  *                   char[]
  * @return     String
  */
 protected static String encodeHexStr(byte[] data, char[] toDigits) {
  return new String(encodeHex(data, toDigits));
 }

 /**
  *                 
  *
  * @param data
  *                char[]
  * @return byte[]
  * @throws RuntimeException
  *                                ,        
  */
 public static byte[] decodeHex(char[] data) {

  int len = data.length;

  if ((len & 0x01) != 0) {
   throw new RuntimeException("Odd number of characters.");
  }

  byte[] out = new byte[len >> 1];

  // two characters form the hex value.
  for (int i = 0, j = 0; j < len; i++) {
   int f = toDigit(data[j], j) << 4;
   j++;
   f = f | toDigit(data[j], j);
   j++;
   out[i] = (byte) (f & 0xFF);
  }

  return out;
 }

 /**
  *               
  *
  * @param ch
  *                char
  * @param index
  *                           
  * @return     
  * @throws RuntimeException
  *              ch              ,       
  */
 protected static int toDigit(char ch, int index) {
  int digit = Character.digit(ch, 16);
  if (digit == -1) {
   throw new RuntimeException("Illegal hexadecimal character " + ch
     + " at index " + index);
  }
  return digit;
 }

 public static void main(String[] args) {
  String srcStr = "      ";
  String encodeStr = encodeHexStr(srcStr.getBytes());
  String decodeStr = new String(decodeHex(encodeStr.toCharArray()));
  System.out.println("   :" + srcStr);
  System.out.println("   :" + encodeStr);
  System.out.println("   :" + decodeStr);
 }

}


다음으로 이동:http://blog.163.com/yxhui_cool/blog/static/770197702012291433339/

좋은 웹페이지 즐겨찾기