url 請求參數加密

 

import java.security.SecureRandom;import javax.crypto.Cipherjava

import javax.crypto.KeyGenerator;apache

import javax.crypto.SecretKey;數組

import org.apache.commons.codec.binary.Base64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;dom

public class UrlUtil {

private static final String KEY = "myMw6qPt&3AD";
private static final Logger LOGGER = LoggerFactory.getLogger(UrlUtil.class);函數

public static void main(String[] args) throws Exception {
String source = "pwd=pwd";
System.out.println("Excepted:" + source);加密

String result = enCryptAndEncode(source);
System.out.println("加密後:" + result);
String source_2 = deCryptAndDecode(result);
System.out.println("Actual:" + source_2);code

String isSuccess = source.equals(source_2) ? "Success" : "fail";
System.out.println("Result:" + isSuccess);
}ip


public static String enCryptAndEncode(String content) {
try {
byte[] sourceBytes = enCryptAndEncode(content, KEY);
return Base64.encodeBase64URLSafeString(sourceBytes);
} catch (Exception e) {
LOGGER.error(e.getMessage(), e);
return content;
}
}ci

/**
* 加密函數
*
* @param content 加密的內容
* @param strKey 密鑰
* @return 返回二進制字符數組
* @throws Exception
*/
public static byte[] enCryptAndEncode(String content, String strKey) throws Exception {get

KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
keyGenerator.init(128, new SecureRandom(strKey.getBytes()));

SecretKey desKey = keyGenerator.generateKey();
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.ENCRYPT_MODE, desKey);
return cipher.doFinal(content.getBytes("UTF-8"));
}

public static String deCryptAndDecode(String content) throws Exception {
byte[] targetBytes = Base64.decodeBase64(content);
return deCryptAndDecode(targetBytes, KEY);
}


/**
* 解密函數
*
* @param src 加密過的二進制字符數組
* @param strKey 密鑰
* @return
* @throws Exception
*/
public static String deCryptAndDecode(byte[] src, String strKey) throws Exception {
KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
keyGenerator.init(128, new SecureRandom(strKey.getBytes()));

SecretKey desKey = keyGenerator.generateKey();
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.DECRYPT_MODE, desKey);
byte[] cByte = cipher.doFinal(src);
return new String(cByte, "UTF-8");
}

}

相關文章
相關標籤/搜索