面试题答案
一键面试- 密钥生成:
- 在Java中,使用
KeyGenerator
生成AES密钥。示例代码如下:
import javax.crypto.KeyGenerator; import javax.crypto.SecretKey; import java.security.NoSuchAlgorithmException; public class AESKeyGenerator { public static SecretKey generateAESKey() throws NoSuchAlgorithmException { KeyGenerator keyGenerator = KeyGenerator.getInstance("AES"); keyGenerator.init(256); // 建议使用256位密钥 return keyGenerator.generateKey(); } }
- 在Java中,使用
- 加密实现:
- 使用
Cipher
类进行加密操作。示例代码如下:
import javax.crypto.Cipher; import javax.crypto.SecretKey; import javax.crypto.spec.IvParameterSpec; import javax.crypto.spec.SecretKeySpec; import java.nio.charset.StandardCharsets; import java.security.SecureRandom; import java.util.Base64; public class AESEncryption { public static String encrypt(String password, SecretKey secretKey) throws Exception { Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); byte[] iv = new byte[16]; SecureRandom secureRandom = new SecureRandom(); secureRandom.nextBytes(iv); IvParameterSpec ivParameterSpec = new IvParameterSpec(iv); cipher.init(Cipher.ENCRYPT_MODE, secretKey, ivParameterSpec); byte[] encrypted = cipher.doFinal(password.getBytes(StandardCharsets.UTF_8)); byte[] encryptedIVAndText = new byte[iv.length + encrypted.length]; System.arraycopy(iv, 0, encryptedIVAndText, 0, iv.length); System.arraycopy(encrypted, 0, encryptedIVAndText, iv.length, encrypted.length); return Base64.getEncoder().encodeToString(encryptedIVAndText); } }
- 使用
- 解密实现:
- 使用
Cipher
类进行解密操作。示例代码如下:
import javax.crypto.Cipher; import javax.crypto.SecretKey; import javax.crypto.spec.IvParameterSpec; import javax.crypto.spec.SecretKeySpec; import java.nio.charset.StandardCharsets; import java.util.Base64; public class AESDecryption { public static String decrypt(String encryptedPassword, SecretKey secretKey) throws Exception { byte[] decoded = Base64.getDecoder().decode(encryptedPassword); int ivSize = 16; byte[] iv = new byte[ivSize]; System.arraycopy(decoded, 0, iv, 0, ivSize); IvParameterSpec ivParameterSpec = new IvParameterSpec(iv); byte[] encrypted = new byte[decoded.length - ivSize]; System.arraycopy(decoded, ivSize, encrypted, 0, encrypted.length); Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); cipher.init(Cipher.DECRYPT_MODE, secretKey, ivParameterSpec); byte[] decrypted = cipher.doFinal(encrypted); return new String(decrypted, StandardCharsets.UTF_8); } }
- 使用
在实际的Java网络编程场景中使用时,要注意密钥的安全存储和传输。可以通过安全通道如SSL/TLS来传输密钥,同时密钥应妥善保管,例如存储在安全的密钥管理系统(KMS)中。