security
Symmetric encryption example
With this example we are going to demonstrate how to make a symmetric encryption and decryption. In symmetric encryption the same key is used for both encryption of plaintext and decryption of ciphertext. In short, to make a symmetric encryption you should:
- Create a byte array from the initial password and a byte array from the initial key.
- Create a new SecretKeySpec from the key byte array, using the AES algorithm.
- Create a new Cipher for the AES/ECB/NoPadding transformation and initialize it in
encryption mode, with the specified key, using thegetInstance(String transformation)
andinit(int opmode, Key key)
API methods. - Make the encryption, with the
update(byte[] input, int inputOffset, int inputLen, byte[] output, int outputOffset)
anddoFinal(byte[] output, int outputOffset)
API methods. The result is a new byte array with the encrypted password. - Initialize the cipher in decryption mode, using the same key.
- Make the decryption of the encrypted byte array. The result will be a decrypted byte array,
as shown in the code snippet below.
package com.javacodegeeks.snippets.core; import java.security.Security; import javax.crypto.Cipher; import javax.crypto.spec.SecretKeySpec; public class Main { public static void main(String[] args) throws Exception { Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider()); byte[] password = "JavaJavaJavaJava".getBytes("UTF-8"); byte[] pkey = "keykeykekeykeykekeykeykekeykeyke".getBytes("UTF-8"); SecretKeySpec secretKey = new SecretKeySpec(pkey, "AES"); Cipher c = Cipher.getInstance("AES/ECB/NoPadding"); System.out.println("User password(plaintext) : " + new String(password)); // encrypt password byte[] cText = new byte[password.length]; c.init(Cipher.ENCRYPT_MODE, secretKey); int ctLen = c.update(password, 0, password.length, cText, 0); ctLen += c.doFinal(cText, ctLen); System.out.println("Password encrypted: " + cText.toString().getBytes("UTF-8").toString() + " bytes: " + ctLen); // decrypt password byte[] plainText = new byte[ctLen]; c.init(Cipher.DECRYPT_MODE, secretKey); int plen = c.update(cText, 0, ctLen, plainText, 0); plen += c.doFinal(plainText, plen); System.out.println("User password(plaintext) : " + new String(plainText) + " bytes: " + plen); } }
Output:
User password(plaintext) : JavaJavaJavaJava
Password encrypted: [B@64b045f4 bytes: 16
User password(plaintext) : JavaJavaJavaJava bytes: 16
This was an example of how to make symmetric encryption in Java.