java 常見的加密算法
加密算法分類:
v 只能加密:SHA SHA1 MD5 CRC-32
v 既能加密也能解密:
對稱:DES 3DES AES Blowfish
非對稱:RSA(加密、簽名) DSA(只能簽名)
非對稱加密技術開銷比較大,不適合大文本的加密。
Java代碼實現SHA算法
/*
SHA(Secure Hash Algorithm,安全散列算法),數字簽名等密碼學應用中重要的工具,
被廣泛地應用於電子商務等信息安全領域。雖然,SHA與MD5通過碰撞法都被破解了,
但是SHA仍然是公認的安全加密算法,較之MD5更爲安全*/
public class SHAEncode {
public static final String KEY_SHA = "SHA1";
public static String shaDigest(byte[] source) throws NoSuchAlgorithmException {
String encrpt = null;
MessageDigest md = MessageDigest.getInstance(KEY_SHA);
md.update(source);
//得到數據摘要
byte[] digest = md.digest();
//把二進制數組轉換成十六進制字符串
encrpt = Byte2HexStrUtil.byte2HexStr(digest);
return encrpt;
}
}
Java代碼實現MD5算法
/**
* 獲取加密後的字符串
* @param input
* @return
*/
public static String md5Digest(String data) {
try {
// 拿到一個MD5轉換器(如果想要SHA1參數換成”SHA1”)
MessageDigest messageDigest =MessageDigest.getInstance("MD5");
// 輸入的字符串轉換成字節數組
byte[] inputByteArray = data.getBytes();
// inputByteArray是輸入字符串轉換得到的字節數組
messageDigest.update(inputByteArray);
// 轉換並返回結果,也是字節數組,包含16個元素
byte[] resultByteArray = messageDigest.digest();
// 字符數組轉換成字符串返回
return byteArrayToHex(resultByteArray);
} catch (NoSuchAlgorithmException e) {
return null;
}
}
public static String byteArrayToHex(byte[] byteArray) {
// 首先初始化一個字符數組,用來存放每個16進制字符
char[] hexDigits = {'0','1','2','3','4','5','6','7','8','9', 'A','B','C','D','E','F' };
// new一個字符數組,這個就是用來組成結果字符串的(解釋一下:一個byte是八位二進制,也就是2位十六進制字符(2的8次方等於16的2次方))
char[] resultCharArray =new char[byteArray.length * 2];
// 遍歷字節數組,通過位運算(位運算效率高),轉換成字符放到字符數組中去
int index = 0;
for (byte b : byteArray) {
resultCharArray[index++] = hexDigits[b>>> 4 & 0xf];
resultCharArray[index++] = hexDigits[b& 0xf];
}
// 字符數組組合成字符串返回
return new String(resultCharArray);
}
java實現DES加密算法
/**
* DES加密
* @param source
* @return
*/
public static String desEncrypt(String source){
if(source == null || source.length() ==0){
return null;
}
try {
//DES算法要求有一個可信任的隨機數源
SecureRandom sr = new SecureRandom();
//從原始密鑰數據創建一個DESKeySpec對象
DESKeySpec dks = new DESKeySpec(DES_KEY.getBytes());
SecretKeyFactory keyFactory =
SecretKeyFactory.getInstance("DES");
//生產密鑰
SecretKey key = keyFactory.generateSecret(dks);
//Cipher對象實際完成加密操作
Cipher cipher = Cipher.getInstance("DES");
//使用密鑰初始化Cipher對象
cipher.init(Cipher.ENCRYPT_MODE,key,sr);
byte [] data =source.getBytes();
//加密
byte [] encryptedData = cipher.doFinal(data);
//轉成16進制串
String hexString = HexUtil.byte2HexStr(encryptedData);
return hexString;
} catch (InvalidKeyException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (InvalidKeySpecException e) {
e.printStackTrace();
} catch (NoSuchPaddingException e) {
e.printStackTrace();
} catch (IllegalBlockSizeException e) {
e.printStackTrace();
} catch (BadPaddingException e) {
e.printStackTrace();
}
return null;
}
/**
* DES解密
* @param source
* @return
*/
public static String desDecrypt(String source){
if(source == null || source.length() ==0){
return null;
}
try {
//DES算法要求有一個可信任的隨機數源
SecureRandom sr = new SecureRandom();
//從原始密鑰數據創建一個DESKeySpec對象
DESKeySpec dks = new DESKeySpec(DES_KEY.getBytes());
SecretKeyFactory keyFactory =
SecretKeyFactory.getInstance("DES");
SecretKey key = keyFactory.generateSecret(dks);
//Cipher對象實際完成解密操作
Cipher cipher = Cipher.getInstance("DES");
//使用密鑰初始化Cipher對象
cipher.init(Cipher.DECRYPT_MODE,key,sr);
//將十六進制串轉成字節數組
byte [] data =HexUtil.hex2Byte(source);
//解密
byte [] decryptedData = cipher.doFinal(data);
return new String(decryptedData);
} catch (InvalidKeyException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (InvalidKeySpecException e) {
e.printStackTrace();
} catch (NoSuchPaddingException e) {
e.printStackTrace();
} catch (IllegalBlockSizeException e) {
e.printStackTrace();
} catch (BadPaddingException e) {
e.printStackTrace();
}
return null;
}
3DES加密算法
Java實現3DES加密算法
1、加入bcprov-jdk16-145.jar包支持
public class ThreeDESUtil {
// 算法名稱
public static final String KEY_ALGORITHM = "desede";
// 算法名稱/加密模式/填充方式
public static final String CIPHER_ALGORITHM = "desede/CBC/NoPadding";
/** *//**
* CBC加密
* @param key 密鑰
* @param keyiv IV
* @param data 明文
* @return Base64編碼的密文
* @throws Exception
*/
public static byte[] des3EncodeCBC(byte[] key, byte[] keyiv, byte[] data) throws Exception {
Security.addProvider(new BouncyCastleProvider());
Key deskey = keyGenerator(new String(key));
Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
IvParameterSpec ips = new IvParameterSpec(keyiv);
cipher.init(Cipher.ENCRYPT_MODE, deskey, ips);
byte[] bOut = cipher.doFinal(data);
for (int k = 0; k < bOut.length; k++) {
System.out.print(bOut[k] + " ");
}
System.out.println("");
return bOut;
}
/** *//**
*
* 生成密鑰key對象
* @param KeyStr 密鑰字符串
* @return 密鑰對象
* @throws InvalidKeyException
* @throws NoSuchAlgorithmException
* @throws InvalidKeySpecException
* @throws Exception
*/
private static Key keyGenerator(String keyStr) throws Exception {
byte input[] = HexString2Bytes(keyStr);
DESedeKeySpec KeySpec = new DESedeKeySpec(input);
SecretKeyFactory KeyFactory = SecretKeyFactory.getInstance(KEY_ALGORITHM);
return ((Key) (KeyFactory.generateSecret(((java.security.spec.KeySpec) (KeySpec)))));
}
private static int parse(char c) {
if (c >= 'a') return (c - 'a' + 10) & 0x0f;
if (c >= 'A') return (c - 'A' + 10) & 0x0f;
return (c - '0') & 0x0f;
}
// 從十六進制字符串到字節數組轉換
public static byte[] HexString2Bytes(String hexstr) {
byte[] b = new byte[hexstr.length() / 2];
int j = 0;
for (int i = 0; i < b.length; i++) {
char c0 = hexstr.charAt(j++);
char c1 = hexstr.charAt(j++);
b[i] = (byte) ((parse(c0) << 4) | parse(c1));
}
return b;
}
/** *//**
* CBC解密
* @param key 密鑰
* @param keyiv IV
* @param data Base64編碼的密文
* @return 明文
* @throws Exception
*/
public static byte[] des3DecodeCBC(byte[] key, byte[] keyiv, byte[] data) throws Exception {
Key deskey = keyGenerator(new String(key));
Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
IvParameterSpec ips = new IvParameterSpec(keyiv);
cipher.init(Cipher.DECRYPT_MODE, deskey, ips);
byte[] bOut = cipher.doFinal(data);
return bOut;
}
public static void main(String[] args) throws Exception {
byte[] key = "6C4E60E55552386C759569836DC0F83869836DC0F838C0F7".getBytes();
byte[] keyiv = { 1, 2, 3, 4, 5, 6, 7, 8 };
byte[] data = "amigoxie".getBytes("UTF-8");
System.out.println("data.length=" + data.length);
System.out.println("CBC加密解密");
byte[] str5 = des3EncodeCBC(key, keyiv, data);
System.out.println(new sun.misc.BASE64Encoder().encode(str5));
byte[] str6 = des3DecodeCBC(key, keyiv, str5);
System.out.println(new String(str6, "UTF-8"));
}
}