Java中常用加密/解密方法詳解
安全問(wèn)題已經(jīng)成為一個(gè)越來(lái)越重要的問(wèn)題,在Java中如何對(duì)重要數(shù)據(jù)進(jìn)行加密解密是本文的主要內(nèi)容。
一、常用的加密/解密算法
1.Base64
嚴(yán)格來(lái)說(shuō)Base64并不是一種加密/解密算法,而是一種編碼方式。Base64不生成密鑰,通過(guò)Base64編碼后的密文就可以直接“翻譯”為明文,但是可以通過(guò)向明文中添加混淆字符來(lái)達(dá)到加密的效果。
2.DES
DES是一種基于56位密鑰的對(duì)稱算法,1976年被美國(guó)聯(lián)邦政府的國(guó)家標(biāo)準(zhǔn)局確定為聯(lián)邦資料處理標(biāo)準(zhǔn)(FIPS),隨后在國(guó)際上廣泛流傳開(kāi)來(lái)。現(xiàn)在DES已經(jīng)不是一種安全的加密算法,已被公開(kāi)破解,現(xiàn)在DES已經(jīng)被高級(jí)加密標(biāo)準(zhǔn)(AES)所代替。
3.3DES
3DES是DES的一種派生算法,主要提升了DES的一些實(shí)用所需的安全性。
4.AES
AES是現(xiàn)在對(duì)稱加密算法中最流行的算法之一。
二、實(shí)現(xiàn)所需的一些庫(kù)
為了實(shí)現(xiàn)上述的算法,我們可以實(shí)用JDK自帶的實(shí)現(xiàn),也可以使用一些開(kāi)源的第三方庫(kù),例如Bouncy Castle(https://www.bouncycastle.org/)和comnons codec(https://commons.apache.org/proper/commons-codec/)。
三、具體實(shí)現(xiàn)
1.Base64
package com.tancky.security;
import java.io.IOException;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
public class Base64Demo {
private static String src = "TestBase64";
public static void main(String[] args) {
Base64Demo.jdkBase64();
Base64Demo.commonsCodecBase64 ();
Base64Demo.bouncyCastleBase64 ();
}
//使用JDK的base64實(shí)現(xiàn),
public static void jdkBase64 (){
BASE64Encoder encoder = new BASE64Encoder();
String encode = encoder.encode(Base64Demo.src.getBytes());
System.out.println("encode: " + encode);
BASE64Decoder decoder = new BASE64Decoder();
try {
String decode = new String ( decoder.decodeBuffer(encode));
System.out.println("decode: " + decode);
} catch (IOException e) {
e.printStackTrace();
}
}
//使用apache的commonsCodec實(shí)現(xiàn)
public static void commonsCodecBase64 (){
byte[] encodeBytes = org.apache.commons.codec.binary.Base64.encodeBase64(Base64Demo.src.getBytes());
String encode = new String (encodeBytes);
System.out.println("encode: " + encode);
byte[] decodeBytes = org.apache.commons.codec.binary.Base64.decodeBase64(encode);
String decode = new String(decodeBytes);
System.out.println("decode: " + decode);
}
//使用bouncyCastlede實(shí)現(xiàn)
public static void bouncyCastleBase64 () {
byte[] encodeBytes = org.bouncycastle.util.encoders.Base64.encode(Base64Demo.src.getBytes()) ;
String encode = new String (encodeBytes);
System.out.println("encode: " + encode);
byte[] decodeBytes = org.bouncycastle.util.encoders.Base64.decode(encode);
String decode = new String(decodeBytes);
System.out.println("decode: " + decode);
}
}
2.DES
package com.tancky.security;
import java.security.InvalidKeyException;
import java.security.Key;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.Security;
import java.security.spec.InvalidKeySpecException;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.KeyGenerator;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.util.encoders.Hex;
public class DESDemo {
private static String src = "TestDES";
public static void jdkDES () {
try {
//生成密鑰Key
KeyGenerator keyGenerator = KeyGenerator.getInstance("DES");
keyGenerator.init(56);
SecretKey secretKey = keyGenerator.generateKey();
byte[] bytesKey = secretKey.getEncoded();
//KEY轉(zhuǎn)換
DESKeySpec deSedeKeySpec = new DESKeySpec(bytesKey);
SecretKeyFactory factory = SecretKeyFactory.getInstance("DES");
Key convertSecretKey = factory.generateSecret(deSedeKeySpec);
//加密
Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, convertSecretKey);
byte[] encodeResult = cipher.doFinal(DESDemo.src.getBytes());
System.out.println("DESEncode :" + Hex.toHexString(encodeResult));
//解密
cipher.init(Cipher.DECRYPT_MODE,convertSecretKey);
byte[] DecodeResult = cipher.doFinal(encodeResult);
System.out.println("DESDncode :" + new String (DecodeResult));
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (InvalidKeyException e) {
// TODO 自動(dòng)生成的 catch 塊
e.printStackTrace();
} catch (InvalidKeySpecException e) {
// TODO 自動(dòng)生成的 catch 塊
e.printStackTrace();
} catch (NoSuchPaddingException e) {
// TODO 自動(dòng)生成的 catch 塊
e.printStackTrace();
} catch (IllegalBlockSizeException e) {
// TODO 自動(dòng)生成的 catch 塊
e.printStackTrace();
} catch (BadPaddingException e) {
// TODO 自動(dòng)生成的 catch 塊
e.printStackTrace();
}
}
public static void bcDES (){
try {
//使用BouncyCastle 的DES加密
Security.addProvider(new BouncyCastleProvider());
//生成密鑰Key
KeyGenerator keyGenerator = KeyGenerator.getInstance("DES","BC");
keyGenerator.init(56);
SecretKey secretKey = keyGenerator.generateKey();
byte[] bytesKey = secretKey.getEncoded();
//KEY轉(zhuǎn)換
DESKeySpec deSedeKeySpec = new DESKeySpec(bytesKey);
SecretKeyFactory factory = SecretKeyFactory.getInstance("DES");
Key convertSecretKey = factory.generateSecret(deSedeKeySpec);
//加密
Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, convertSecretKey);
byte[] encodeResult = cipher.doFinal(DESDemo.src.getBytes());
System.out.println("DESEncode :" + Hex.toHexString(encodeResult));
//解密
cipher.init(Cipher.DECRYPT_MODE,convertSecretKey);
byte[] DecodeResult = cipher.doFinal(encodeResult);
System.out.println("DESDncode :" + new String (DecodeResult));
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (InvalidKeyException e) {
// TODO 自動(dòng)生成的 catch 塊
e.printStackTrace();
} catch (InvalidKeySpecException e) {
// TODO 自動(dòng)生成的 catch 塊
e.printStackTrace();
} catch (NoSuchPaddingException e) {
// TODO 自動(dòng)生成的 catch 塊
e.printStackTrace();
} catch (IllegalBlockSizeException e) {
// TODO 自動(dòng)生成的 catch 塊
e.printStackTrace();
} catch (BadPaddingException e) {
// TODO 自動(dòng)生成的 catch 塊
e.printStackTrace();
} catch (NoSuchProviderException e) {
// TODO 自動(dòng)生成的 catch 塊
e.printStackTrace();
}
}
public static void main(String[] args) {
DESDemo.jdkDES ();
DESDemo.bcDES();
}
}
3.3DES
package com.tancky.security;
import java.security.InvalidKeyException;
import java.security.Key;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.Security;
import java.security.spec.InvalidKeySpecException;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.KeyGenerator;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESedeKeySpec;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.util.encoders.Hex;
public class TripleDESDemo {
private static String src = "TestTripleDES";
public static void jdkTripleDES () {
try {
//生成密鑰Key
KeyGenerator keyGenerator = KeyGenerator.getInstance("DESede");
keyGenerator.init(168);
SecretKey secretKey = keyGenerator.generateKey();
byte[] bytesKey = secretKey.getEncoded();
//KEY轉(zhuǎn)換
DESedeKeySpec deSedeKeySpec = new DESedeKeySpec(bytesKey);
SecretKeyFactory factory = SecretKeyFactory.getInstance("DESede");
Key convertSecretKey = factory.generateSecret(deSedeKeySpec);
//加密
Cipher cipher = Cipher.getInstance("DESede/ECB/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, convertSecretKey);
byte[] encodeResult = cipher.doFinal(TripleDESDemo.src.getBytes());
System.out.println("TripleDESEncode :" + Hex.toHexString(encodeResult));
//解密
cipher.init(Cipher.DECRYPT_MODE,convertSecretKey);
byte[] DecodeResult = cipher.doFinal(encodeResult);
System.out.println("TripleDESDncode :" + new String (DecodeResult));
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (InvalidKeyException e) {
// TODO 自動(dòng)生成的 catch 塊
e.printStackTrace();
} catch (InvalidKeySpecException e) {
// TODO 自動(dòng)生成的 catch 塊
e.printStackTrace();
} catch (NoSuchPaddingException e) {
// TODO 自動(dòng)生成的 catch 塊
e.printStackTrace();
} catch (IllegalBlockSizeException e) {
// TODO 自動(dòng)生成的 catch 塊
e.printStackTrace();
} catch (BadPaddingException e) {
// TODO 自動(dòng)生成的 catch 塊
e.printStackTrace();
}
}
public static void bcTripleDES () {
try {
Security.addProvider(new BouncyCastleProvider());
//生成密鑰Key
KeyGenerator keyGenerator = KeyGenerator.getInstance("DESede","BC");
keyGenerator.getProvider();
keyGenerator.init(168);
SecretKey secretKey = keyGenerator.generateKey();
byte[] bytesKey = secretKey.getEncoded();
//KEY轉(zhuǎn)換
DESedeKeySpec deSedeKeySpec = new DESedeKeySpec(bytesKey);
SecretKeyFactory factory = SecretKeyFactory.getInstance("DESede");
Key convertSecretKey = factory.generateSecret(deSedeKeySpec);
//加密
Cipher cipher = Cipher.getInstance("DESede/ECB/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, convertSecretKey);
byte[] encodeResult = cipher.doFinal(TripleDESDemo.src.getBytes());
System.out.println("TripleDESEncode :" + Hex.toHexString(encodeResult));
//解密
cipher.init(Cipher.DECRYPT_MODE,convertSecretKey);
byte[] DecodeResult = cipher.doFinal(encodeResult);
System.out.println("TripleDESDncode :" + new String (DecodeResult));
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (InvalidKeyException e) {
// TODO 自動(dòng)生成的 catch 塊
e.printStackTrace();
} catch (InvalidKeySpecException e) {
// TODO 自動(dòng)生成的 catch 塊
e.printStackTrace();
} catch (NoSuchPaddingException e) {
// TODO 自動(dòng)生成的 catch 塊
e.printStackTrace();
} catch (IllegalBlockSizeException e) {
// TODO 自動(dòng)生成的 catch 塊
e.printStackTrace();
} catch (BadPaddingException e) {
// TODO 自動(dòng)生成的 catch 塊
e.printStackTrace();
} catch (NoSuchProviderException e) {
// TODO 自動(dòng)生成的 catch 塊
e.printStackTrace();
}
}
public static void main(String[] args) {
jdkTripleDES ();
bcTripleDES ();
}
}
4.AES
package com.tancky.security;
import java.security.InvalidKeyException;
import java.security.Key;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.SecureRandom;
import java.security.Security;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.KeyGenerator;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.util.encoders.Hex;
public class AESDemo {
private static String src = "TestAES";
public static void jdkAES (){
try {
//生成Key
KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
keyGenerator.init(128);
//keyGenerator.init(128, new SecureRandom("seedseedseed".getBytes()));
//使用上面這種初始化方法可以特定種子來(lái)生成密鑰,這樣加密后的密文是唯一固定的。
SecretKey secretKey = keyGenerator.generateKey();
byte[] keyBytes = secretKey.getEncoded();
//Key轉(zhuǎn)換
Key key = new SecretKeySpec(keyBytes, "AES");
//加密
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, key);
byte[] encodeResult = cipher.doFinal(AESDemo.src.getBytes());
System.out.println("AESencode : " + Hex.toHexString(encodeResult) );
//解密
cipher.init(Cipher.DECRYPT_MODE, key);
byte[] decodeResult = cipher.doFinal(encodeResult);
System.out.println("AESdecode : " + new String (decodeResult));
} catch (NoSuchAlgorithmException e) {
// TODO 自動(dòng)生成的 catch 塊
e.printStackTrace();
} catch (NoSuchPaddingException e) {
// TODO 自動(dòng)生成的 catch 塊
e.printStackTrace();
} catch (InvalidKeyException e) {
// TODO 自動(dòng)生成的 catch 塊
e.printStackTrace();
} catch (IllegalBlockSizeException e) {
// TODO 自動(dòng)生成的 catch 塊
e.printStackTrace();
} catch (BadPaddingException e) {
// TODO 自動(dòng)生成的 catch 塊
e.printStackTrace();
}
}
public static void bcAES (){
try {
//使用BouncyCastle 的DES加密
Security.addProvider(new BouncyCastleProvider());
//生成Key
KeyGenerator keyGenerator = KeyGenerator.getInstance("AES","BC");
keyGenerator.getProvider();
keyGenerator.init(128);
SecretKey secretKey = keyGenerator.generateKey();
byte[] keyBytes = secretKey.getEncoded();
//Key轉(zhuǎn)換
Key key = new SecretKeySpec(keyBytes, "AES");
//加密
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, key);
byte[] encodeResult = cipher.doFinal(AESDemo.src.getBytes());
System.out.println("AESencode : " + Hex.toHexString(encodeResult) );
//解密
cipher.init(Cipher.DECRYPT_MODE, key);
byte[] decodeResult = cipher.doFinal(encodeResult);
System.out.println("AESdecode : " + new String (decodeResult));
} catch (NoSuchAlgorithmException e) {
// TODO 自動(dòng)生成的 catch 塊
e.printStackTrace();
} catch (NoSuchPaddingException e) {
// TODO 自動(dòng)生成的 catch 塊
e.printStackTrace();
} catch (InvalidKeyException e) {
// TODO 自動(dòng)生成的 catch 塊
e.printStackTrace();
} catch (IllegalBlockSizeException e) {
// TODO 自動(dòng)生成的 catch 塊
e.printStackTrace();
} catch (BadPaddingException e) {
// TODO 自動(dòng)生成的 catch 塊
e.printStackTrace();
} catch (NoSuchProviderException e) {
// TODO 自動(dòng)生成的 catch 塊
e.printStackTrace();
}
}
public static void main(String[] args) {
jdkAES();
bcAES();
}
}
以上就是本文的全部?jī)?nèi)容,希望本文的內(nèi)容對(duì)大家的學(xué)習(xí)或者工作能帶來(lái)一定的幫助,同時(shí)也希望多多支持腳本之家!
相關(guān)文章
mybatis-config.xml文件中的mappers標(biāo)簽使用
在MyBatis配置中,<mapper>標(biāo)簽關(guān)鍵用于指定SQL?Mapper的XML文件路徑,主要有三種指定方式:resource、url和class,Resource方式從類的根路徑開(kāi)始,適合放在項(xiàng)目?jī)?nèi)部保障移植性,URL方式指定絕對(duì)路徑,移植性差,適用于外部路徑2024-10-10
Spring?Boot?實(shí)現(xiàn)字段唯一校驗(yàn)功能(實(shí)例代碼)
這篇文章主要介紹了Spring?Boot?實(shí)現(xiàn)字段唯一校驗(yàn),實(shí)現(xiàn)代碼很簡(jiǎn)單,代碼簡(jiǎn)單易懂,對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2022-08-08
Java中new關(guān)鍵字和newInstance方法的區(qū)別分享
在初始化一個(gè)類,生成一個(gè)實(shí)例的時(shí)候,newInstance()方法和new關(guān)鍵字除了一個(gè)是方法一個(gè)是關(guān)鍵字外,最主要的區(qū)別是創(chuàng)建對(duì)象的方式不同2013-07-07
Java終止循環(huán)體的具體實(shí)現(xiàn)
這篇文章主要介紹了Java終止循環(huán)體的具體實(shí)現(xiàn),需要的朋友可以參考下2014-02-02

