DES是一種對稱加密算法java
英文名:Data Encrption Standard(數據加密標準)算法
DES算法的加密與解密都是使用同一個密鑰,密鑰的長度爲8個字節apache
以下爲加密算法:app
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import javax.crypto.spec.IvParameterSpec;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import java.net.URLDecoder;
import java.net.URLEncoder;
/** * 加密 * * @param inputContent 要加密的內容 * @param inputKey 加密用的KEY * @return * @throws Exception */ private static String encryptProcess(String inputContent, String inputKey) throws Exception { DESKeySpec desKeySpec = new DESKeySpec(inputKey.getBytes("UTF-8")); SecretKey secretKey = SecretKeyFactory.getInstance("DES").generateSecret(desKeySpec); IvParameterSpec iv = new IvParameterSpec(inputKey.getBytes("UTF-8")); Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding"); cipher.init(Cipher.ENCRYPT_MODE, secretKey, iv); byte[] encodedBytes = cipher.doFinal(URLEncoder.encode(inputContent, "UTF-8").getBytes("UTF-8")); StringBuffer buffer = new StringBuffer(); for (byte b : encodedBytes) { String plainText = Integer.toHexString(0xff & b); if (plainText.length() < 2) plainText = "0" + plainText; buffer.append(plainText); } return buffer.toString(); }
擴展:3DES (Triple DES: 三重數據加密算法),對每一個數據塊應用3次DES加密算法(使用3條56位的密鑰對數據進行三次加密)加密
3DES是DES向AES過渡時期的一種算法,在Java代碼中,算法的String是"DESede",如:spa
Cipher.getInstance("DESede");.net