Practical Java Encryption and Decryption Algorithms: Applications of AES, RSA, and ECC in Protecting Sensitive Data – Essential Security Knowledge for Architects
As a Java engineer, I often encounter scenarios that require the protection of sensitive data. With the increasing risks of cybersecurity, personal information protection has become a hot topic. Whether it is passwords, payment information, or user privacy data, we need to master reliable encryption technologies. Today, let’s discuss three commonly used encryption and decryption algorithms in Java: AES, RSA, and ECC, and see their characteristics and how to implement them in code.
AES Algorithm: The Mainstay of Symmetric Encryption
AES (Advanced Encryption Standard) is currently the most popular symmetric encryption algorithm, meaning that the same key is used for both encryption and decryption. It is fast and secure, making it particularly suitable for encrypting large amounts of data.
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;
public class AESDemo {
public static void main(String[] args) throws Exception {
// Generate AES key
KeyGenerator keyGen = KeyGenerator.getInstance("AES");
keyGen.init(256); // Use 256-bit key
SecretKey secretKey = keyGen.generateKey();
// Data to be encrypted
String data = "This is the sensitive information to be encrypted";
// Encrypt
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.ENCRYPT_MODE, secretKey);
byte[] encryptedData = cipher.doFinal(data.getBytes());
String encoded = Base64.getEncoder().encodeToString(encryptedData);
System.out.println("Encrypted: " + encoded);
// Decrypt
cipher.init(Cipher.DECRYPT_MODE, secretKey);
byte[] decryptedData = cipher.doFinal(Base64.getDecoder().decode(encoded));
System.out.println("Decrypted: " + new String(decryptedData));
}
}
Note: In actual projects, key management is very important! Do not hard-code keys in the code, nor store them in plaintext configuration files. Consider using dedicated key management services or environment variables to store them.
RSA Algorithm: The Representative of Asymmetric Encryption
The RSA algorithm is the most widely used asymmetric encryption algorithm, which has two keys: a public key and a private key. Data encrypted with the public key can only be decrypted with the private key, and vice versa. This characteristic makes it particularly suitable for scenarios that require secure key transmission.
import java.security.*;
import javax.crypto.Cipher;
import java.util.Base64;
public class RSADemo {
public static void main(String[] args) throws Exception {
// Generate RSA key pair
KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
keyGen.initialize(2048);
KeyPair pair = keyGen.generateKeyPair();
PublicKey publicKey = pair.getPublic();
PrivateKey privateKey = pair.getPrivate();
// Data to be encrypted
String data = "Data encrypted using RSA";
// Encrypt with public key
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
byte[] encryptedData = cipher.doFinal(data.getBytes());
String encoded = Base64.getEncoder().encodeToString(encryptedData);
System.out.println("RSA Encrypted: " + encoded);
// Decrypt with private key
cipher.init(Cipher.DECRYPT_MODE, privateKey);
byte[] decryptedData = cipher.doFinal(Base64.getDecoder().decode(encoded));
System.out.println("RSA Decrypted: " + new String(decryptedData));
}
}
RSA is relatively slow for computation and is generally not suitable for encrypting large data; it is more often used to encrypt symmetric encryption keys. Many times, we combine AES and RSA: using AES to encrypt data and then using RSA to encrypt the AES key, which is known as hybrid encryption.
ECC Algorithm: More Efficient Asymmetric Encryption
ECC (Elliptic Curve Cryptography) is an encryption algorithm based on elliptic curve mathematics. It achieves the same level of security as RSA with shorter keys and higher computational efficiency, making it particularly suitable for resource-constrained environments.
import java.security.*;
import java.security.spec.*;
import javax.crypto.Cipher;
import java.util.Base64;
public class ECCDemo {
public static void main(String[] args) throws Exception {
// Generate ECC key pair
KeyPairGenerator keyGen = KeyPairGenerator.getInstance("EC");
keyGen.initialize(256);
KeyPair pair = keyGen.generateKeyPair();
PublicKey publicKey = pair.getPublic();
PrivateKey privateKey = pair.getPrivate();
// In Java, directly using ECC for encryption is complex; it is usually used for key exchange or digital signatures.
// Here we demonstrate ECC key generation and storage.
System.out.println("ECC Public Key: " +
Base64.getEncoder().encodeToString(publicKey.getEncoded()));
System.out.println("ECC Private Key: " +
Base64.getEncoder().encodeToString(privateKey.getEncoded()));
}
}
Note: The Java standard library has limited direct support for ECC encryption; ECC is more commonly used in key exchange protocols (like ECDH) and digital signatures (like ECDSA). If ECC encryption is needed, consider using third-party libraries like Bouncy Castle.
Choosing the Right Algorithm for Practical Applications
Choosing which encryption algorithm to use depends on specific requirements:
- • Database Sensitive Field Encryption: Use AES to encrypt sensitive data such as user information and credit card numbers.
- • Secure Communication: Use RSA or ECC to protect key exchange, and then use AES to encrypt communication content.
- • Digital Signatures: Use RSA or ECDSA to verify data integrity and origin.
- • Password Storage: Use one-way hash functions like bcrypt or PBKDF2, rather than these reversible encryption algorithms.
// The correct way to store passwords is to use hashing rather than encryption
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
String hashedPassword = encoder.encode("user password");
// Store hashedPassword in the database
Encryption algorithms are just one part of a security system; complete data protection also requires consideration of key management, secure transmission, access control, and other factors. As architects, we also need to regularly update our security knowledge and pay attention to the latest developments and potential vulnerabilities of various algorithms.
Cryptography is profound, but Java’s encryption API allows us to implement these complex algorithms relatively easily. Mastering these encryption and decryption techniques will enable us to better protect user data and have a stronger voice in technical reviews!