Symmetric encryption uses the same key for both encryption
and decryption. This is different from asymmetric encryption where different
keys are used. A common algorithm for symmetric encryption is AES (Advanced
Encryption Standard).
Example of Symmetric Encryption and Decryption in Java
Using AES
Here’s an example that demonstrates how to perform symmetric
encryption and decryption using AES in Java:
Maven Dependency
Ensure you have the following dependency in your pom.xml if
you're using Maven:
xml
<dependency>
<groupId>org.bouncycastle</groupId>
<artifactId>bcprov-jdk15on</artifactId> <version>1.68</version> </dependency> |
Java Code Example
java
import
javax.crypto.Cipher; import
javax.crypto.KeyGenerator; import
javax.crypto.SecretKey; import
javax.crypto.spec.IvParameterSpec; import
java.security.SecureRandom; import
java.util.Base64; public class
AESEncryption { // Generate a new AES key public static SecretKey generateKey(int
n) throws Exception { KeyGenerator keyGen =
KeyGenerator.getInstance("AES"); keyGen.init(n); return keyGen.generateKey(); } // Generate a new initialization vector
(IV) public static IvParameterSpec
generateIv() { byte[] iv = new byte[16]; new SecureRandom().nextBytes(iv); return new IvParameterSpec(iv); } // Encrypt the input string using the
provided key and IV public static String encrypt(String
input, SecretKey key, IvParameterSpec iv) throws Exception { Cipher cipher =
Cipher.getInstance("AES/CBC/PKCS5Padding"); cipher.init(Cipher.ENCRYPT_MODE, key,
iv); byte[] cipherText =
cipher.doFinal(input.getBytes()); return
Base64.getEncoder().encodeToString(cipherText); } // Decrypt the input string using the
provided key and IV public static String decrypt(String
cipherText, SecretKey key, IvParameterSpec iv) throws Exception { Cipher cipher =
Cipher.getInstance("AES/CBC/PKCS5Padding"); cipher.init(Cipher.DECRYPT_MODE, key,
iv); byte[] plainText =
cipher.doFinal(Base64.getDecoder().decode(cipherText)); return new String(plainText); } public static void main(String[] args) { try { // Generate AES key SecretKey key = generateKey(256); // Generate IV IvParameterSpec iv =
generateIv(); // Data to be encrypted String input = "Hello,
World!"; // Encrypt the data String cipherText =
encrypt(input, key, iv);
System.out.println("Encrypted Text: " + cipherText); // Decrypt the data String plainText =
decrypt(cipherText, key, iv);
System.out.println("Decrypted Text: " + plainText); } catch (Exception e) { e.printStackTrace(); } } } |
Explanation
- Key
Generation:
- The generateKey
method generates a new AES key. The parameter n specifies the key size,
typically 128, 192, or 256 bits. In this example, 256-bit AES is used.
- IV
Generation:
- The generateIv
method generates a new initialization vector (IV) which is required for
AES in CBC mode. The IV ensures that the same plaintext encrypted
multiple times will yield different ciphertexts.
- Encryption:
- The encrypt
method initializes the cipher in encryption mode using the AES key and
IV. It then encrypts the input string and returns the ciphertext encoded
in Base64.
- Decryption:
- The decrypt
method initializes the cipher in decryption mode using the same AES key
and IV. It then decrypts the Base64 encoded ciphertext back into
plaintext.
- Main
Method:
- The main
method demonstrates the full encryption and decryption process. It
generates an AES key and IV, encrypts a sample string, and then decrypts
the ciphertext back to the original plaintext.
Notes
- Key
Management: The security of symmetric encryption depends on keeping
the key secret. Ensure that the key is stored securely and not exposed.
- IV
Usage: The IV should be unique for each encryption operation. For CBC
mode, the IV does not need to be secret but must be unique and can be sent
along with the ciphertext.
- Algorithm
Variants: The example uses AES/CBC/PKCS5Padding. Depending on the use
case, other modes and padding schemes might be required, such as GCM mode
for authenticated encryption.
This example provides a straightforward way to implement
AES-based symmetric encryption and decryption in Java, ensuring that data can
be securely encrypted and decrypted using the same key.
Example of Symmetric Encryption and Decryption in Java
Using DES
DES (Data Encryption Standard) is a symmetric-key algorithm
used for the encryption and decryption of data. DES operates on 64-bit blocks
of data and uses a 56-bit key.
Although DES is considered outdated and insecure for many
applications today due to its short key length and susceptibility to
brute-force attacks, it's still valuable for understanding the basics of
symmetric encryption.
Here’s an example in Java that demonstrates how to perform
symmetric encryption and decryption using DES:
Maven Dependency
Make sure you have the following dependency in your pom.xml
if you're using Maven:
xml
<dependency>
<groupId>org.bouncycastle</groupId>
<artifactId>bcprov-jdk15on</artifactId> <version>1.68</version> </dependency> |
Java Code Example
Key Generation
java
import
javax.crypto.KeyGenerator; import
javax.crypto.SecretKey; public class
DESKeyGenerator { public static SecretKey generateKey()
throws Exception { KeyGenerator keyGen =
KeyGenerator.getInstance("DES"); keyGen.init(56); // DES uses a 56-bit
key size return keyGen.generateKey(); } } |
Encryption and Decryption
java
import
javax.crypto.Cipher; import
javax.crypto.SecretKey; import
javax.crypto.spec.IvParameterSpec; import
java.security.SecureRandom; import
java.util.Base64; import
java.nio.file.Files; import
java.nio.file.Paths; public class
DESEncryption { // Generate a new initialization vector
(IV) public static IvParameterSpec
generateIv() { byte[] iv = new byte[8]; // DES uses
an 8-byte block size new SecureRandom().nextBytes(iv); return new IvParameterSpec(iv); } // Encrypt the input string using the
provided key and IV public static String encrypt(String
input, SecretKey key, IvParameterSpec iv) throws Exception { Cipher cipher =
Cipher.getInstance("DES/CBC/PKCS5Padding"); cipher.init(Cipher.ENCRYPT_MODE, key,
iv); byte[] cipherText =
cipher.doFinal(input.getBytes()); return
Base64.getEncoder().encodeToString(cipherText); } // Decrypt the input string using the
provided key and IV public static String decrypt(String
cipherText, SecretKey key, IvParameterSpec iv) throws Exception { Cipher cipher =
Cipher.getInstance("DES/CBC/PKCS5Padding"); cipher.init(Cipher.DECRYPT_MODE, key,
iv); byte[] plainText =
cipher.doFinal(Base64.getDecoder().decode(cipherText)); return new String(plainText); } public static void main(String[] args) { try { // Generate DES key SecretKey key =
DESKeyGenerator.generateKey(); // Generate IV IvParameterSpec iv =
generateIv(); // Data to be encrypted String input = "Hello,
World!"; // Encrypt the data String cipherText =
encrypt(input, key, iv);
System.out.println("Encrypted Text: " + cipherText); // Decrypt the data String plainText =
decrypt(cipherText, key, iv);
System.out.println("Decrypted Text: " + plainText); } catch (Exception e) { e.printStackTrace(); } } } |
Explanation
- Key
Generation:
- The generateKey
method generates a DES key. DES uses a 56-bit key size.
- KeyGenerator.getInstance("DES")
initializes the key generator with the DES algorithm.
- keyGen.init(56)
sets the key size to 56 bits.
- IV
Generation:
- The generateIv
method generates an initialization vector (IV), which is required for DES
in CBC mode. The IV ensures that the same plaintext encrypted multiple
times will yield different ciphertexts.
- Encryption:
- The encrypt
method initializes the cipher in encryption mode using the DES key and
IV.
- Cipher.getInstance("DES/CBC/PKCS5Padding")
initializes the cipher with DES algorithm, CBC mode, and PKCS5 padding.
- cipher.init(Cipher.ENCRYPT_MODE,
key, iv) initializes the cipher for encryption mode.
- cipher.doFinal(input.getBytes())
performs the encryption and returns the encrypted byte array, which is
then encoded to a Base64 string.
- Decryption:
- The decrypt
method initializes the cipher in decryption mode using the same DES key
and IV.
- Cipher.getInstance("DES/CBC/PKCS5Padding")
initializes the cipher with DES algorithm, CBC mode, and PKCS5 padding.
- cipher.init(Cipher.DECRYPT_MODE,
key, iv) initializes the cipher for decryption mode.
- cipher.doFinal(Base64.getDecoder().decode(cipherText))
performs the decryption and returns the original byte array, which is
then converted to a string.
- Main
Method:
- The main
method demonstrates the full encryption and decryption process. It
generates a DES key and IV, encrypts a sample string, and then decrypts
the ciphertext back to the original plaintext.
Notes
- Key
Management: The security of symmetric encryption depends on keeping
the key secret. Ensure that the key is stored securely and not exposed.
- IV
Usage: The IV should be unique for each encryption operation. For CBC
mode, the IV does not need to be secret but must be unique and can be sent
along with the ciphertext.
- Algorithm
and Padding: The example uses DES/CBC/PKCS5Padding. Depending on your
security requirements, other modes and padding schemes might be required.
This example provides a straightforward way to implement
DES-based symmetric encryption and decryption in Java, ensuring that data can
be securely encrypted and decrypted using the same key.
1 Comments