Java加密程序

/**
 * @about JavaEncrypt Class
 */
package open.source.java;

import java.security.Key;
import java.security.MessageDigest;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;

/**
 * @author zwm
 * 
 */
public class JavaEncrypt {
 public static void main(String args[]) throws Exception {
  JavaEncrypt je = new JavaEncrypt();
  String s="zhaowenming21";
  System.out.println(je.encrypt(s));
 
  
 }

 /**
  * 
  * @param s
  * @return
  * @throws Exception
  */
 public String encrypt(String s) throws Exception {
  MessageDigest messageDigest = MessageDigest.getInstance("SHA-256");
  messageDigest.update(s.getBytes("UTF-8"));
  byte by[] = messageDigest.digest();
  // 调用byte2hex(by)方法
  return byte2hex(by);

 }

 /**
  * byte 转为 hex
  * @param by
  * @return
  * @throws Exception
  */
 private String byte2hex(byte by[]) throws Exception {
  String s = "";
  for (int i = 0; i < by.length; i++) {
   String st = Integer.toHexString(by[i] & 0xff);
   if (st.length() == 1)
    s = (new StringBuilder()).append(s).append("0").append(st)
      .toString();
   else
    s = (new StringBuilder()).append(s).append(st).toString();
   if (i < by.length - 1)
    s = (new StringBuilder()).append(s).append("").toString();
  }

  return s.toUpperCase();
 }

 /**
  * 取得密钥
  * @return
  * @throws Exception
  */
 public Key getKey() throws Exception {
  KeyGenerator keygenerator = KeyGenerator.getInstance("AES");
  keygenerator.init(128);
  javax.crypto.SecretKey secretkey = keygenerator.generateKey();
  return secretkey;
 }

 /**
  * 
  * @param key
  * @param abyte0
  * @return
  * @throws Exception
  */
 public byte[] Sig_EnCrypt(Key key, byte abyte0[]) throws Exception {
  Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
  cipher.init(1, key);
  byte abyte1[] = cipher.doFinal(abyte0);
  return abyte1;
 }

 /**
  * 
  * @param key
  * @param abyte0
  * @return
  * @throws Exception
  */
 public byte[] Sig_DeCrypt(Key key, byte abyte0[]) throws Exception {
  Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
  cipher.init(2, key);
  byte abyte1[] = cipher.doFinal(abyte0);
  return abyte1;
 }

}
 

 

你可能感兴趣的:(java,Security)