1. 程式人生 > >java 3des加解密

java 3des加解密

加解密的擴充套件類:

    import javax.crypto.Cipher;
    import javax.crypto.SecretKey;
    import javax.crypto.spec.SecretKeySpec;

加密 金鑰:

   private static final String keyStr = "safetyprod";//加密金鑰
   private static final String algorithm = "DESede"; ///定義加密演算法,有DES、DESede(即3DES)、Blowfish

 

將加密金鑰轉為3des加解密所必須的24位元組碼:

/**
	 * 將加密金鑰轉為為位元組陣列
	 * 3des加密的金鑰必須要24位元組
	 * @param keyStr 加密金鑰字串
	 * @return
	 */
	public static byte[] build3DesKeyByte(String keyStr){
		byte []keyByte = new byte[24];//預設資料為0
		try {
			byte []temp = keyStr.getBytes("UTF-8");
			/*
			 * 執行陣列拷貝
			 * System.arraycopy(源陣列,從源陣列哪裡開始拷貝,目標陣列,拷貝多少位)
			*/
			if(keyByte.length > temp.length){
				//如果temp不夠24位,則拷貝temp陣列整個長度的內容到key陣列中
				System.arraycopy(temp, 0, keyByte, 0, temp.length);
			}else{
				//如果temp大於24位,則拷貝temp陣列24個長度的內容到key陣列中
				System.arraycopy(temp, 0, keyByte, 0, keyByte.length);
			}
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return keyByte;
	} 

3des加密

/**
     * 3DES加密
     * @param srcStr 將加密的字串
     * @return
     *
     */
	public static byte[] encrypt3Des(byte[] srcStrByte) {
		byte[] keyByte = build3DesKeyByte(keyStr);
		try {
			// 生成金鑰
			SecretKey deskey = new SecretKeySpec(keyByte, algorithm);
			// 加密
			Cipher c1 = Cipher.getInstance(algorithm);
			c1.init(Cipher.ENCRYPT_MODE, deskey);
			return c1.doFinal(srcStrByte);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
    }

3des解密

/**
	 * 3des解密
	 * @param srcStr
	 * @return
	 */
	public static byte[] decrypt3Des(byte[] srcStrByte) {
		byte[] keyByte = build3DesKeyByte(keyStr);
		try {
			// 生成金鑰
			SecretKey deskey = new SecretKeySpec(keyByte, algorithm);
			// 加密
			Cipher c1 = Cipher.getInstance(algorithm);
			c1.init(Cipher.DECRYPT_MODE, deskey);
			return c1.doFinal(srcStrByte);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
    }