[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 2656
  • Last Modified:

Simple Example for Java Encryption and Decryption?

I need to do a simple example of java encryption and decryption. Does anyone know of a good simple library and what functions I would use. All I need to do is encrypt and decrypt between two machines. But I can manually move the key.
0
alexmac05
Asked:
alexmac05
1 Solution
 
bluebelldiscoveryCommented:
Try Java Cryptography API

I have attached some code which I have used in my project.
Should be useful.

First you need to generate a key using
generateAESKey()
You can generate a key using this function and save it as binary file in server.

to encrypt use
encryptAES()

to decrypt use
decryptAES
import java.security.*;
import javax.crypto.*;
import javax.crypto.spec.*;
import java.security.spec.*;
import java.io.*;
import java.util.*;
 
public class CipherText
{
        public static byte[] generateAESKey() throws Exception
        {
                KeyGenerator kgen = KeyGenerator.getInstance("AES");
                kgen.init(128);
                // Generate the secret key specs.
                //SecretKey skey = kgen.generateKey();
                return skey.getEncoded();
        }
 
 
        public static byte[] encryptAES(byte key[], byte data[]) throws Exception
        {
               SecretKeySpec skeySpec = new SecretKeySpec(key, "AES");
 
               // Instantiate the cipher
               Cipher cipher = Cipher.getInstance("AES/CTR/NoPadding");
               cipher.init(Cipher.ENCRYPT_MODE, skeySpec, new IvParameterSpec(new byte[16]));
 
               return cipher.doFinal(data);
        }
 
        public static byte[] decryptAES(byte key[], byte msg[]) throws Exception
        {
               SecretKeySpec skeySpec = new SecretKeySpec(key, "AES");
 
               // Instantiate the cipher
               Cipher cipher = Cipher.getInstance("AES/CTR/NoPadding");
               cipher.init(Cipher.DECRYPT_MODE, skeySpec, new IvParameterSpec(new byte[16]));
 
               return cipher.doFinal(msg);
        }
 
}

Open in new window

0
 
alexmac05Author Commented:
Thank you so much! worked perfectly!
0

Featured Post

Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now