當前位置:編程學習大全網 - 源碼下載 - 如何用JAVA實現字符串簡單加密解密

如何用JAVA實現字符串簡單加密解密

import?org.apache.commons.codec.binary.Base64;

import?org.apache.commons.lang3.StringUtils;

import?org.slf4j.Logger;

import?org.slf4j.LoggerFactory;

import?javax.crypto.Cipher;

import?javax.crypto.spec.SecretKeySpec;

public?class?AESUtil?{

public?static?final?Logger?LOGGER?=?LoggerFactory.getLogger(AESUtil.class);

public?static?final?String?ENCRYPTED_KEY?=?"<TEST>KEY,123";

/**

*?

*?@param?sSrc

*?@param?sKey

*?@return

*?@throws?Exception

*/

public?static?String?encrypt(String?sSrc,?String?sKey)?throws?Exception?{

//判斷加密串是否為空,長度是否為16

if?(StringUtils.isBlank(sKey)?||?sKey.length()?!=?16)?{

LOGGER.error("sKey為空null或長度不是16");

return?null;

}

byte[]?raw?=?sKey.getBytes("utf-8");

SecretKeySpec?skeySpec?=?new?SecretKeySpec(raw,?"AES");

Cipher?cipher?=?Cipher.getInstance("AES/ECB/PKCS5Padding");

cipher.init(Cipher.ENCRYPT_MODE,?skeySpec);

byte[]?encrypted?=?cipher.doFinal(sSrc.getBytes("utf-8"));

return?new?String(new?Base64().encode(encrypted),"UTF-8");

}

/**

*?

*?@param?enString

*?@param?sKey

*?@return

*?@throws?Exception

*/

public?static?String?decrypt(String?enString,?String?sKey)?throws?Exception?{

try?{

if?(StringUtils.isBlank(sKey)?||?sKey.length()?!=?16)?{

LOGGER.error("sKey為空null或長度不是16");

return?null;

}

byte[]?raw?=?sKey.getBytes("utf-8");

SecretKeySpec?skeySpec?=?new?SecretKeySpec(raw,?"AES");

Cipher?cipher?=?Cipher.getInstance("AES/ECB/PKCS5Padding");

cipher.init(Cipher.DECRYPT_MODE,?skeySpec);

byte[]?encrypted1?=?(byte[])?new?Base64().decode(enString.getBytes());

try?{

byte[]?original?=?cipher.doFinal(encrypted1);

String?originalString?=?new?String(original,"utf-8");

return?originalString;

}?catch?(Exception?e)?{

LOGGER.error(e.toString());

return?null;

}

}?catch?(Exception?ex)?{

LOGGER.error(ex.toString());

return?null;

}

}

}

  • 上一篇:有很多韓飯說NC什麽什麽的。請問NC是什麽意思?
  • 下一篇:C語言,C++,VC++,VB,易語言,有什麽區別?
  • copyright 2024編程學習大全網