熱點推薦:
您现在的位置: 電腦知識網 >> 編程 >> Java編程 >> Java核心技術 >> 正文

java密碼加密與解密

2022-06-13   來源: Java核心技術 

  以下兩個類可以很方便的完成字符串的加密和解密

  加密CryptHelperencrypt(password)

  解密CrypHelperdecrypt(password)

  代碼如下

  CryptUtilsjava

  [java]

  package comgdielabcrypt;

  import javaioIOException;

  import javaxcryptoCipher;

  import javaxcryptoKeyGenerator;

  import javaxcryptoSecretKey;

  import apachexercesinternalimpldvutilBase;

  public class CryptUtils {

  private static String Algorithm = DES;

  private static byte[] DEFAULT_KEY=new byte[] { };

  private static String VALUE_ENCODING=UTF;

  /**

  * 生成密鑰

  *

  * @return byte[] 返回生成的密鑰

  * @throws exception

  *             扔出異常

  */

  public static byte[] getSecretKey() throws Exception {

  KeyGenerator keygen = KeyGeneratorgetInstance(Algorithm)

  SecretKey deskey = keygengenerateKey()

  // if (debug ) Systemoutprintln (生成密鑰+bytehex (deskeygetEncoded

  // ()))

  return deskeygetEncoded()

  }

  /**

  * 將指定的數據根據提供的密鑰進行加密

  *

  * @param input

  *            需要加密的數據

  * @param key

  *            密鑰

  * @return byte[] 加密後的數據

  * @throws Exception

  */

  public static byte[] encryptData(byte[] input byte[] key) throws Exception {

  SecretKey deskey = new javaxcryptospecSecretKeySpec(key Algorithm)

  // if (debug )

  // {

  // Systemoutprintln (加密前的二進串+bytehex (input ))

  // Systemoutprintln (加密前的字符串+new String (input ))

  //

  // }

  Cipher c = CiphergetInstance(Algorithm)

  cinit(CipherENCRYPT_MODE deskey)

  byte[] cipherByte = cdoFinal(input)

  // if (debug ) Systemoutprintln (加密後的二進串+bytehex (cipherByte ))

  return cipherByte;

  }

  public static byte[] encryptData(byte[] input) throws Exception {

  return encryptData(input DEFAULT_KEY)

  }

  /**

  * 將給定的已加密的數據通過指定的密鑰進行解密

  *

  * @param input

  *            待解密的數據

  * @param key

  *            密鑰

  * @return byte[] 解密後的數據

  * @throws Exception

  */

  public static byte[] decryptData(byte[] input byte[] key) throws Exception {

  SecretKey deskey = new javaxcryptospecSecretKeySpec(key Algorithm)

  // if (debug ) Systemoutprintln (解密前的信息+bytehex (input ))

  Cipher c = CiphergetInstance(Algorithm)

  cinit(CipherDECRYPT_MODE deskey)

  byte[] clearByte = cdoFinal(input)

  // if (debug )

  // {

  // Systemoutprintln (解密後的二進串+bytehex (clearByte ))

  // Systemoutprintln (解密後的字符串+(new String (clearByte )))

  //

  // }

  return clearByte;

  }

  public static byte[] decryptData(byte[] input) throws Exception {

  return decryptData(input DEFAULT_KEY)

  }

  /**

  * 字節碼轉換成進制字符串

  *

  * @param byte[] b 輸入要轉換的字節碼

  * @return String 返回轉換後的進制字符串

  */

  public static String bytehex(byte[] bytes) {

  StringBuilder hs = new StringBuilder()

  for(byte b : bytes)

  hsappend(Stringformat(%$X b))

  return hstoString()

  }

  public static byte[] hexbyte(String content) {

  int l=contentlength()》;

  byte[] result=new byte[l];

  for(int i=;i<l;i++) {

  int j=i《;

  String s=contentsubstring(j j+

  result[i]=IntegervalueOf(s byteValue()

  }

  return result;

  }

  /**

  * 將字節數組轉換為base編碼字符串

  * @param buffer

  * @return

  */

  public static String bytesToBase(byte[] buffer) {

  //BASEEncoder en=new BASEEncoder()

  return Baseencode(buffer)

  //      return encoderencode(buffer)

  }

  /**

  * 將base編碼的字符串解碼為字節數組

  * @param value

  * @return

  * @throws IOException

  */

  public static byte[] baseToBytes(String value) throws IOException {

  //return BasedecodeToByteArray(value)

  //      Systemoutprintln(decoderdecodeBuffer(value))

  //      return decoderdecodeBuffer(value)

  return Basedecode(value)

  }

  /**

  * 加密給定的字符串

  * @param value

  * @return 加密後的base字符串

  */

  public static String encryptString(String value) {

  return encryptString(value DEFAULT_KEY)

  }

  /**

  * 根據給定的密鑰加密字符串

  * @param value 待加密的字符串

  * @param key 以BASE形式存在的密鑰

  * @return 加密後的base字符串

  * @throws IOException

  */

  public static String encryptString(String value String key) throws IOException {

  return encryptString(value baseToBytes(key))

  }

  /**

  * 根據給定的密鑰加密字符串

  * @param value 待加密的字符串

  * @param key 字節數組形式的密鑰

  * @return 加密後的base字符串

  */

  public static String encryptString(String value byte[] key) {

  try {

  byte[] data=valuegetBytes(VALUE_ENCODING)

  data=CryptUtilsencryptData(data key)

  return bytesToBase(data)

  } catch (Exception e) {

  // TODO Autogenerated catch block

  eprintStackTrace()

  return null;

  }

  }

  /**

  * 解密字符串

  * @param value base形式存在的密文

  * @return 明文

  */

  public static String decryptString(String value) {

  return decryptString(value DEFAULT_KEY)

  }

  /**

  * 解密字符串

  * @param value base形式存在的密文

  * @param key base形式存在的密鑰

  * @return 明文

  * @throws IOException

  */

  public static String decryptString(String value String key) throws IOException {

  String s=decryptString(value baseToBytes(key))

  return s;

  }

  /**

  * 解密字符串

  * @param value base形式存在的密文

  * @param key 字節數據形式存在的密鑰

  * @return 明文

  */

  public static String decryptString(String value byte[] key) {

  try {

  byte[] data=baseToBytes(value)

  data=CryptUtilsdecryptData(data key)

  return new String(data VALUE_ENCODING)

  }catch(Exception e) {

  eprintStackTrace()

  return null;

  }

  }

  }

  package comgdielabcrypt;

  import javaioIOException;

  import javaxcryptoCipher;

  import javaxcryptoKeyGenerator;

  import javaxcryptoSecretKey;

  import apachexercesinternalimpldvutilBase;

  public class CryptUtils {

  private static String Algorithm = DES;

  private static byte[] DEFAULT_KEY=new byte[] { };

  private static String VALUE_ENCODING=UTF;

  /**

  * 生成密鑰

  *

  * @return byte[] 返回生成的密鑰

  * @throws exception

  *             扔出異常

  */

  public static byte[] getSecretKey() throws Exception {

  KeyGenerator keygen = KeyGeneratorgetInstance(Algorithm)

  SecretKey deskey = keygengenerateKey()

  // if (debug ) Systemoutprintln (生成密鑰+bytehex (deskeygetEncoded

  // ()))

  return deskeygetEncoded()

  }

  /**

  * 將指定的數據根據提供的密鑰進行加密

  *

  * @param input

  *            需要加密的數據

  * @param key

  *            密鑰

  * @return byte[] 加密後的數據

  * @throws Exception

  */

  public static byte[] encryptData(byte[] input byte[] key) throws Exception {

  SecretKey deskey = new javaxcryptospecSecretKeySpec(key Algorithm)

  // if (debug )

  // {

  // Systemoutprintln (加密前的二進串+bytehex (input ))

  // Systemoutprintln (加密前的字符串+new String (input ))

  //

  // }

  Cipher c = CiphergetInstance(Algorithm)

  cinit(CipherENCRYPT_MODE deskey)

  byte[] cipherByte = cdoFinal(input)

  // if (debug ) Systemoutprintln (加密後的二進串+bytehex (cipherByte ))

  return cipherByte;

  }

  public static byte[] encryptData(byte[] input) throws Exception {

  return encryptData(input DEFAULT_KEY)

  }

  /**

  * 將給定的已加密的數據通過指定的密鑰進行解密

  *

  * @param input

  *            待解密的數據

  * @param key

  *            密鑰

  * @return byte[] 解密後的數據

  * @throws Exception

  */

  public static byte[] decryptData(byte[] input byte[] key) throws Exception {

  SecretKey deskey = new javaxcryptospecSecretKeySpec(key Algorithm)

  // if (debug ) Systemoutprintln (解密前的信息+bytehex (input ))

  Cipher c = CiphergetInstance(Algorithm)

  cinit(CipherDECRYPT_MODE deskey)

  byte[] clearByte = cdoFinal(input)

  // if (debug )

  // {

  // Systemoutprintln (解密後的二進串+bytehex (clearByte ))

  // Systemoutprintln (解密後的字符串+(new String (clearByte )))

  //

  // }

  return clearByte;

  }

  public static byte[] decryptData(byte[] input) throws Exception {

  return decryptData(input DEFAULT_KEY)

  }

  /**

  * 字節碼轉換成進制字符串

  *

  * @param byte[] b 輸入要轉換的字節碼

  * @return String 返回轉換後的進制字符串

  */

  public static String bytehex(byte[] bytes) {

  StringBuilder hs = new StringBuilder()

  for(byte b : bytes)

  hsappend(Stringformat(%$X b))

  return hstoString()

  }

  public static byte[] hexbyte(String content) {

  int l=contentlength()》;

  byte[] result=new byte[l];

  for(int i=;i<l;i++) {

  int j=i《;

  String s=contentsubstring(j j+

  result[i]=IntegervalueOf(s byteValue()

  }

  return result;

  }

  /**

  * 將字節數組轉換為base編碼字符串

  * @param buffer

  * @return

  */

  public static String bytesToBase(byte[] buffer) {

  //BASEEncoder en=new BASEEncoder()

  return Baseencode(buffer)

  //  return encoderencode(buffer)

  }

  /**

  * 將base編碼的字符串解碼為字節數組

  * @param value

  * @return

  * @throws IOException

  */

  public static byte[] baseToBytes(String value) throws IOException {

  //return BasedecodeToByteArray(value)

  //  Systemoutprintln(decoderdecodeBuffer(value))

  //  return decoderdecodeBuffer(value)

  return Basedecode(value)

  }

  /**

  * 加密給定的字符串

  * @param value

  * @return 加密後的base字符串

  */

  public static String encryptString(String value) {

  return encryptString(value DEFAULT_KEY)

  }

  /**

  * 根據給定的密鑰加密字符串

  * @param value 待加密的字符串

  * @param key 以BASE形式存在的密鑰

  * @return 加密後的base字符串

  * @throws IOException

  */

  public static String encryptString(String value String key) throws IOException {

  return encryptString(value baseToBytes(key))

  }

  /**

  * 根據給定的密鑰加密字符串

  * @param value 待加密的字符串

  * @param key 字節數組形式的密鑰

  * @return 加密後的base字符串

  */

  public static String encryptString(String value byte[] key) {

  try {

  byte[] data=valuegetBytes(VALUE_ENCODING)

  data=CryptUtilsencryptData(data key)

  return bytesToBase(data)

  } catch (Exception e) {

  // TODO Autogenerated catch block

  eprintStackTrace()

  return null;

  }

  }

  /**

  * 解密字符串

  * @param value base形式存在的密文

  * @return 明文

  */

  public static String decryptString(String value) {

  return decryptString(value DEFAULT_KEY)

  }

  /**

  * 解密字符串

  * @param value base形式存在的密文

  * @param key base形式存在的密鑰

  * @return 明文

  * @throws IOException

  */

  public static String decryptString(String value String key) throws IOException {

  String s=decryptString(value baseToBytes(key))

  return s;

  }

  /**

  * 解密字符串

  * @param value base形式存在的密文

  * @param key 字節數據形式存在的密鑰

  * @return 明文

  */

  public static String decryptString(String value byte[] key) {

  try {

  byte[] data=baseToBytes(value)

  data=CryptUtilsdecryptData(data key)

  return new String(data VALUE_ENCODING)

  }catch(Exception e) {

  eprintStackTrace()

  return null;

  }

  }

  }

  CryptHelperjava

  [java]

  package comgdielabcrypt;

  import javaxcryptoCipher;

  import javaxcryptoSecretKey;

  import javaxcryptoSecretKeyFactory;

  import javaxcryptospecDESKeySpec;

  import javaxcryptospecIvParameterSpec;

  import orgspringframeworkutilDigestUtils;

  public class CryptHelper{

  private static String CRYPT_KEY = zhongqian;

  //加密

  private static Cipher ecip;

  //解密

  private static Cipher dcip;

  static {

  try {

  String KEY = DigestUtilsmdDigestAsHex(CRYPT_KEYgetBytes())toUpperCase()

  KEY = KEYsubstring(

  byte[] bytes = KEYgetBytes()

  DESKeySpec ks = new DESKeySpec(bytes)

  SecretKeyFactory skf = SecretKeyFactorygetInstance(DES

  SecretKey sk = skfgenerateSecret(ks)

  IvParameterSpec iv = new IvParameterSpec(bytes)

  ecip = CiphergetInstance(DES/CBC/PKCSPadding

  ecipinit(CipherENCRYPT_MODE sk iv

  dcip = CiphergetInstance(DES/CBC/PKCSPadding

  dcipinit(CipherDECRYPT_MODE sk iv

  }catch(Exception ex) {

  exprintStackTrace()

  }

  }

  public static String encrypt(String content) throws Exception {

  byte[] bytes = ecipdoFinal(contentgetBytes(ascii))

  return CryptUtilsbytehex(bytes)

  }

  public static String decrypt(String content) throws Exception {

  byte[] bytes  = CryptUtilshexbyte(content)

  bytes = dcipdoFinal(bytes)

  return new String(bytes ascii

  }

  //test

  public static void main(String[] args) throws Exception {

  String password = gly;

  String en = encrypt(password)

  Systemoutprintln(en)

  Systemoutprintln(decrypt(en))

  }

  }

  package comgdielabcrypt;

  import javaxcryptoCipher;

  import javaxcryptoSecretKey;

  import javaxcryptoSecretKeyFactory;

  import javaxcryptospecDESKeySpec;

  import javaxcryptospecIvParameterSpec;

  import orgspringframeworkutilDigestUtils;

  public class CryptHelper{

  private static String CRYPT_KEY = zhongqian;

  //加密

  private static Cipher ecip;

  //解密

  private static Cipher dcip;

  static {

  try {

  String KEY = DigestUtilsmdDigestAsHex(CRYPT_KEYgetBytes())toUpperCase()

  KEY = KEYsubstring(

  byte[] bytes = KEYgetBytes()

  DESKeySpec ks = new DESKeySpec(bytes)

  SecretKeyFactory skf = SecretKeyFactorygetInstance(DES

  SecretKey sk = skfgenerateSecret(ks)

  IvParameterSpec iv = new IvParameterSpec(bytes)

  ecip = CiphergetInstance(DES/CBC/PKCSPadding

  ecipinit(CipherENCRYPT_MODE sk iv

  dcip = CiphergetInstance(DES/CBC/PKCSPadding

  dcipinit(CipherDECRYPT_MODE sk iv

  }catch(Exception ex) {

  exprintStackTrace()

  }

  }

  public static String encrypt(String content) throws Exception {

  byte[] bytes = ecipdoFinal(contentgetBytes(ascii))

  return CryptUtilsbytehex(bytes)

  }

  public static String decrypt(String content) throws Exception {

  byte[] bytes  = CryptUtilshexbyte(content)

  bytes = dcipdoFinal(bytes)

  return new String(bytes ascii

  }

  //test

  public static void main(String[] args) throws Exception {

  String password = gly;

  String en = encrypt(password)

  Systemoutprintln(en)

  Systemoutprintln(decrypt(en))

  }

  }


From:http://tw.wingwit.com/Article/program/Java/hx/201311/26449.html
    推薦文章
    Copyright © 2005-2022 電腦知識網 Computer Knowledge   All rights reserved.