在現(xiàn)實(shí)生活中,我們經(jīng)常需要進(jìn)行信息加密來保證信息安全。Java提供了兩種常見的加密方式:對(duì)等加密和非對(duì)等加密。
對(duì)等加密(也稱為對(duì)稱加密)指加密和解密使用相同的密鑰。這種加密方式相對(duì)簡(jiǎn)單,速度較快,適用于對(duì)數(shù)據(jù)量較小的信息進(jìn)行加密。Java提供了多種對(duì)等加密算法,如DES、AES等。下面是Java中使用AES對(duì)等加密的代碼(注:此處為簡(jiǎn)化版代碼):
import javax.crypto.*; import javax.crypto.spec.SecretKeySpec; public class AESUtil { private static final String AES = "AES"; public static byte[] encrypt(String content, String password) throws Exception{ KeyGenerator keyGenerator = KeyGenerator.getInstance(AES); SecureRandom random = SecureRandom.getInstance("SHA1PRNG"); random.setSeed(password.getBytes()); keyGenerator.init(128, random); SecretKey secretKey = keyGenerator.generateKey(); byte[] enCodeFormat = secretKey.getEncoded(); SecretKeySpec key = new SecretKeySpec(enCodeFormat, AES); Cipher cipher = Cipher.getInstance(AES); cipher.init(Cipher.ENCRYPT_MODE, key); byte[] byteContent = content.getBytes("utf-8"); byte[] result = cipher.doFinal(byteContent); return result; } }
非對(duì)等加密(也稱為公鑰加密)指加密和解密使用不同的密鑰。這種加密方式比對(duì)等加密更安全,適用于對(duì)數(shù)據(jù)量較大的信息進(jìn)行加密。Java提供了RSA非對(duì)等加密算法。下面是Java中使用RSA非對(duì)等加密的代碼(注:此處為簡(jiǎn)化版代碼):
import java.security.*; import javax.crypto.*; public class RSAUtil { private static final String RSA = "RSA"; public static byte[] encrypt(String content, PublicKey publicKey) throws Exception { Cipher cipher = Cipher.getInstance(RSA); cipher.init(Cipher.ENCRYPT_MODE, publicKey); byte[] byteContent = content.getBytes("utf-8"); byte[] result = cipher.doFinal(byteContent); return result; } }
綜上所述,對(duì)等加密和非對(duì)等加密都有自己的優(yōu)缺點(diǎn),選擇哪種加密方式要根據(jù)實(shí)際情況來進(jìn)行判斷。