Hi,
After a long time, during which I was very busy by my personal project (building my house), I am come back with a simple article concerning the encrypting of message via the standard Cipher class. This class provides the functionality of a cryptographic cipher for encryption and decryption. It forms the core of the Java Cryptographic Extension (JCE) framework.
In the following example, I will encrypt and decrypt a message via the symmetric algorithm “AES/ECB/PKCS5Padding” (via a secret key). A transformation is of the form “algorithm/mode/padding” or “algorithm”.
01 | package com.ho.crypto.test1; |
03 | import java.security.InvalidKeyException; |
04 | import java.security.NoSuchAlgorithmException; |
05 | import java.util.Random; |
07 | import javax.crypto.BadPaddingException; |
08 | import javax.crypto.Cipher; |
09 | import javax.crypto.IllegalBlockSizeException; |
10 | import javax.crypto.NoSuchPaddingException; |
11 | import javax.crypto.spec.SecretKeySpec; |
15 | * Encrypt / Decrypt your message with Cipher Class. |
19 | public class MyProtectorSingleton { |
23 | private static MyProtectorSingleton instance = null ; |
25 | private SecretKeySpec certificate = null ; |
26 | private Cipher aesEncrypt = null ; |
27 | private Cipher aesDecrypt = null ; |
30 | private MyProtectorSingleton() throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException{ |
31 | Random myRandom = new Random(); |
32 | byte [] myBytesArray = new byte [ 16 ]; |
33 | myRandom.nextBytes(myBytesArray); |
34 | certificate = new SecretKeySpec(myBytesArray, 0 , 16 , "AES" ); |
36 | aesEncrypt = Cipher.getInstance( "AES/ECB/PKCS5Padding" ); |
37 | aesEncrypt.init(Cipher.ENCRYPT_MODE, certificate); |
39 | aesDecrypt = Cipher.getInstance( "AES/ECB/PKCS5Padding" ); |
40 | aesDecrypt.init(Cipher.DECRYPT_MODE,certificate); |
43 | public static synchronized MyProtectorSingleton getInstance() throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException{ |
45 | instance = new MyProtectorSingleton(); |
51 | public byte [] protect(String toProtect) throws IllegalBlockSizeException, BadPaddingException{ |
52 | byte [] cipherText = aesEncrypt.doFinal(toProtect.getBytes()); |
56 | public String unprotect( byte [] toUnprotect) throws IllegalBlockSizeException, BadPaddingException{ |
57 | String cleartext = new String(aesDecrypt.doFinal(toUnprotect)); |
61 | public static void main(String[] args) { |
63 | String toProtect = "this is my message" ; |
64 | MyProtectorSingleton myProtector = MyProtectorSingleton.getInstance(); |
67 | byte [] msgProtected = myProtector.protect(toProtect); |
68 | System.out.println( "msgProtected=" +msgProtected); |
71 | String str = myProtector.unprotect(msgProtected); |
72 | System.out.println(str); |
That’s all!!!!
Kind regards,
Huseyin OZVEREN
Related