作为一种编程语言,Java在技术领域引入了一种全新的方法。它在编程技术领域占据着榜首位置。一家Java应用设计公司可以处理从综合业务软件到手机及无线设备应用的所有开发工作。这种软件支持的普遍性总是通过运行方法存在,并且已经被嵌入到常见的互联网浏览器中。这意味着使用相同的密钥进行加密和解码。(AES) 是一种广泛使用的密钥加密算法。
保护数据传输有多种方式。但大多数专家认为数据加密是最佳方法,目前,Java AES 是一种用于加密的高级解决方案。新算法正在取代 DES 的旧标准,转向 AES。它在机密性、数据认证和高级完整性方面拥有更好的特性。
让我们开始使用单一密钥进行解密和加密的实践吧。这是保护敏感信息相较于其他方法的巨大优势。对于需要保护敏感信息的政府机构和金融机构来说,这是最佳解决方案。
对称加密标准的普及
随着网络安全问题的出现,AES作为一种拥有3种分组密码的高级方法,成为了最佳的选择。它们可以使用加密密钥对128位的数据块进行打乱。发送方和接收方必须拥有相同的密钥,以保持信息的机密性和隐秘性。这使得它成为一种灵活且安全的工具。它工作在固定的分组模式或使用数据位的流模式中。目前,该技术广泛应用于电子邮件通信、TLS以及即时通讯中。
为AES选择正确的填充方案
在分组密码模式下,明文被转换为分组大小以进行加密。这里需要填充,Java 提供了3种替代方案。对于编码,AES 算法本质上具有重复性,并支持 128、192 和 256 位。
它的工作模式如下所示。
!Creating-Encryption-and-Decryption-with-Java-AES
- Electronic codebook (电码本模式)
- Cipher blocking chain (密码分组链接模式)
- Cipher feedback (密码反馈模式)
- Output feedback (输出反馈模式)
- Counter (计数器模式)
- Galois/Counter Mode (Galois/计数器模式)
我们需要选择合适的密钥以确保应用程序具有前瞻性。
Java
“
// Java program to demonstrate the creation
// of Encryption and Decryption with Java AES
import java.nio.charset.StandardCharsets;
import java.security.spec.KeySpec;
import java.util.Base64;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.SecretKeySpec;
class AES {
// Class private variables
private static final String SECRET_KEY
= "mysupersecretkeyhohoho";
private static final String SALT = "ssshhhhhhhhhhh!!!!";
// This method use to encrypt to string
public static String encrypt(String strToEncrypt)
{
try {
// Create default byte array
byte[] iv = { 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0 };
IvParameterSpec ivspec
= new IvParameterSpec(iv);
// Create SecretKeyFactory object
SecretKeyFactory factory
= SecretKeyFactory.getInstance(
"PBKDF2WithHmacSHA256");
// Create KeySpec object and assign with
// constructor
KeySpec spec = new PBEKeySpec(
SECRET_KEY.toCharArray(), SALT.getBytes(),
65536, 256);
SecretKey tmp = factory.generateSecret(spec);
SecretKeySpec secretKey = new SecretKeySpec(
tmp.getEncoded(), "AES");
Cipher cipher = Cipher.getInstance(
"AES/CBC/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, secretKey,
ivspec);
// Return encrypted string
return Base64.getEncoder().encodeToString(
cipher.doFinal(strToEncrypt.getBytes(
StandardCharsets.UTF_8)));
}
catch (Exception e) {
System.out.println("Error while encrypting: "
+ e.toString());
}
return null;
}
// This method use to decrypt to string
public static String decrypt(String strToDecrypt)
{
try {
// Default byte array
byte[] iv = { 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0 };
// Create IvParameterSpec object and assign with
// constructor
IvParameterSpec ivspec
= new IvParameterSpec(iv);
// Create SecretK