Using the Java Cryptographic Extensions

Patient Tools

Read, save, and share this guide

Use these quick tools to make this medical article easier to read, print, save, or share with a family member.

On this page8 sections

Article Summary

The code included in this article has not been reviewed and should not be used without proper analysis. If you have reviewed the included code or portions of it, please post your findings back to the issue tracker for this web content. Java Cryptographic Extensions (JCE) is a set of Java API's which provides cryptographic services such as encryption, secret Key Generation, Message Authentication code and Key...

Key Takeaways

  • This article explains Examples in simple medical language.
Before reading

RX Patient Tools

Use these quick guides before reading the article, or return to them when you need help preparing questions for a doctor.

Start here Choose the right pathway for symptoms, reports, medicines, or urgent warning signs. Disease article roadmap Read this topic step by step: meaning, symptoms, warning signs, diagnosis, treatment, prevention, and follow-up. Treatment planner Prepare questions about treatment choices, benefits, risks, side effects, and follow-up. Family & caregiver guide Organize symptoms, reports, medicines, questions, and follow-up safely. Nutrition & diet guide Prepare food, hydration, supplement, and medicine-timing questions safely. Prevention guide Organize risk factors, protective habits, screening, and warning signs. Recovery guide Prepare a safe plan for activity, rehabilitation, warning signs, and follow-up.
Educational health guideWritten for patient understanding and clinical awareness.
Reviewed content workflowUse writer and reviewer profiles for stronger trust.
Emergency safety firstUrgent warning signs are highlighted below.
Definition

The code included in this article has not been reviewed and should not be used without proper analysis. If you have reviewed the included code or portions of it, please post your findings back to the issue tracker for this web content.

Java Cryptographic Extensions (JCE) is a set of Java API’s which provides cryptographic services such as encryption, secret Key Generation, Message Authentication code and Key Agreement. The ciphers supported by JCE include symmetric, asymmetric, block and stream ciphers. JCE was an optional package to JDK v 1.2.x and 1.3.x. JCE has been integrated into JDK v1.4. JCE API’s are implemented by Cryptographic Service Providers. Each of these cryptographic service providers implements the Service Provider Interface which specifies the functionalities which needs to be implemented by the service providers. Programmers can plugin any Service Providers for performing cryptographic functionalities provided by JCE. J2SE comes with a default provider named SunJCE.

Symmetric Encryption Algorithms provided by SunJCE

  1. DES – default keylength of 56 bits
  2. AES –
  3. RC2, RC4 and RC5
  4. IDEA
  5. Triple DES – default keylength 112 bits
  6. Blowfish – default keylength 56 bits
  7. PBEWithMD5AndDES
  8. PBEWithHmacSHA1AndDESede
  9. DES ede

Modes of Encryption

  1. ECB
  2. CFB
  3. OFB
  4. PCBC

Asymmetric Encryption Algorithms implemented by SunJCE

  1. RSA
  2. Diffie-Hellman – default keylength 1024 bits

Hashing / Message Digest Algorithms implemented by SunJCE

  1. MD5 – default size 64 bytes
  2. SHA1 – default size 64 bytes

Examples

SecureRandom

SecureRandom class is used to generate a cryptographically strong pseudo random number by using a PRNG Algorithm. The following are the advantages of using SecureRandom over Random. 1. SecureRandom produces a cryptographically strong pseudo random number generator. 2. SecureRandom produces cryptographically strong sequences as described in RFC 1750: Randomness Recommendations for Security

package org.owasp.java.crypto;

import java.security.SecureRandom;
import java.security.NoSuchAlgorithmException;

/**
 * @author Joe Prasanna Kumar
 * This program provides the functionality for Generating a Secure Random Number.
 *
 * There are 2 ways to generate a  Random number through SecureRandom.
 * 1. By calling nextBytes method to generate Random Bytes
 * 2. Using setSeed(byte[]) to reseed a Random object
 *
 */


public class SecureRandomGen {

    /**
     * @param args
     */
    public static void main(String[] args) {
        try {
            // Initialize a secure random number generator
            SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");

            // Method 1 - Calling nextBytes method to generate Random Bytes
            byte[] bytes = new byte[512];
            secureRandom.nextBytes(bytes);

            // Printing the SecureRandom number by calling secureRandom.nextDouble()
            System.out.println(" Secure Random # generated by calling nextBytes() is " + secureRandom.nextDouble());

            // Method 2 - Using setSeed(byte[]) to reseed a Random object
            int seedByteCount = 10;
            byte[] seed = secureRandom.generateSeed(seedByteCount);

            secureRandom.setSeed(seed);

            System.out.println(" Secure Random # generated using setSeed(byte[]) is  " + secureRandom.nextDouble());

        } catch (NoSuchAlgorithmException noSuchAlgo)
        {
            System.out.println(" No Such Algorithm exists " + noSuchAlgo);
        }
    }

}

AES Encryption and Decryption

package org.owasp.java.crypto;

import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.KeyGenerator;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;

import java.util.Base64;

/**
 * @author Joe Prasanna Kumar
 * This program provides the following cryptographic functionalities
 * 1. Encryption using AES
 * 2. Decryption using AES
 *
 * High Level Algorithm :
 * 1. Generate a AES key (specify the Key size during this phase)
 * 2. Create the Cipher
 * 3. To Encrypt : Initialize the Cipher for Encryption
 * 4. To Decrypt : Initialize the Cipher for Decryption
 *
 *
 */

public class AES {
    public static void main(String[] args) {

        String strDataToEncrypt = new String();
        String strCipherText = new String();
        String strDecryptedText = new String();

        try {
            /**
             * Step 1. Generate an AES key using KeyGenerator Initialize the
             * keysize to 128 bits (16 bytes)
             *
             */
            KeyGenerator keyGen = KeyGenerator.getInstance("AES");
            keyGen.init(128);
            SecretKey secretKey = keyGen.generateKey();

            /**
             * Step 2. Generate an Initialization Vector (IV)
             *      a. Use SecureRandom to generate random bits
             *         The size of the IV matches the blocksize of the cipher (128 bits for AES)
             *      b. Construct the appropriate IvParameterSpec object for the data to pass to Cipher's init() method
             */

            final int AES_KEYLENGTH = 128;  // change this as desired for the security level you want
            byte[] iv = new byte[AES_KEYLENGTH / 8];    // Save the IV bytes or send it in plaintext with the encrypted data so you can decrypt the data later
            SecureRandom prng = new SecureRandom();
            prng.nextBytes(iv);

            /**
             * Step 3. Create a Cipher by specifying the following parameters
             *      a. Algorithm name - here it is AES
             *      b. Mode - here it is CBC mode
             *      c. Padding - PKCS5
             */

            Cipher aesCipherForEncryption = Cipher.getInstance("AES/CBC/PKCS5PADDING"); // Must specify the mode explicitly as most JCE providers default to ECB mode!!

            /**
             * Step 4. Initialize the Cipher for Encryption
             */

            aesCipherForEncryption.init(Cipher.ENCRYPT_MODE, secretKey,
                    new IvParameterSpec(iv));

            /**
             * Step 5. Encrypt the Data
             *      a. Declare / Initialize the Data. Here the data is of type String
             *      b. Convert the Input Text to Bytes
             *      c. Encrypt the bytes using doFinal method
             */
            strDataToEncrypt = "Hello World of Encryption using AES ";
            byte[] byteDataToEncrypt = strDataToEncrypt.getBytes();
            byte[] byteCipherText = aesCipherForEncryption
                    .doFinal(byteDataToEncrypt);
            strCipherText = Base64.getEncoder().withoutPadding().encodeToString(byteCipherText);
            System.out.println("Cipher Text generated using AES is "
                    + strCipherText);

            /**
             * Step 6. Decrypt the Data
             *      a. Initialize a new instance of Cipher for Decryption (normally don't reuse the same object)
             *         Be sure to obtain the same IV bytes for CBC mode.
             *      b. Decrypt the cipher bytes using doFinal method
             */

            Cipher aesCipherForDecryption = Cipher.getInstance("AES/CBC/PKCS5PADDING"); // Must specify the mode explicitly as most JCE providers default to ECB mode!!

            aesCipherForDecryption.init(Cipher.DECRYPT_MODE, secretKey,
                    new IvParameterSpec(iv));
            byte[] byteDecryptedText = aesCipherForDecryption
                    .doFinal(byteCipherText);
            strDecryptedText = new String(byteDecryptedText);
            System.out
                    .println(" Decrypted Text message is " + strDecryptedText);
        }

        catch (NoSuchAlgorithmException noSuchAlgo) {
            System.out.println(" No Such Algorithm exists " + noSuchAlgo);
        }

        catch (NoSuchPaddingException noSuchPad) {
            System.out.println(" No Such Padding exists " + noSuchPad);
        }

        catch (InvalidKeyException invalidKey) {
            System.out.println(" Invalid Key " + invalidKey);
        }

        catch (BadPaddingException badPadding) {
            System.out.println(" Bad Padding " + badPadding);
        }

        catch (IllegalBlockSizeException illegalBlockSize) {
            System.out.println(" Illegal Block Size " + illegalBlockSize);
        }

        catch (InvalidAlgorithmParameterException invalidParam) {
            System.out.println(" Invalid Parameter " + invalidParam);
        }
    }
}

Des Encryption and Decryption

package org.owasp.crypto;

import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.Cipher;

import java.security.NoSuchAlgorithmException;
import java.security.InvalidKeyException;
import java.security.InvalidAlgorithmParameterException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.BadPaddingException;
import javax.crypto.IllegalBlockSizeException;

import java.util.Base64;

/**
 * @author Joe Prasanna Kumar
 * This program provides the following cryptographic functionalities
 * 1. Encryption using DES
 * 2. Decryption using DES
 *
 * The following modes of DES encryption are supported by SUNJce provider
 * 1. ECB (Electronic code Book) - Every plaintext block is encrypted separately
 * 2. CBC (Cipher Block Chaining) - Every plaintext block is XORed with the previous ciphertext block
 * 3. PCBC (Propogating Cipher Block Chaining) -
 * 4. CFB (Cipher Feedback Mode) - The previous ciphertext block is encrypted and this enciphered block is XORed with the plaintext block to produce the corresponding ciphertext block
 * 5. OFB (Output Feedback Mode) -
 *
 *  High Level Algorithm :
 * 1. Generate a DES key
 * 2. Create the Cipher (Specify the Mode and Padding)
 * 3. To Encrypt : Initialize the Cipher for Encryption
 * 4. To Decrypt : Initialize the Cipher for Decryption
 *
 * Need for Padding :
 * Block ciphers operates on data blocks on fixed size n.
 * Since the data to be encrypted might not always be a multiple of n, the remainder of the bits are padded.
 * PKCS#5 Padding is what will be used in this program
 *
 */

public class DES {
    public static void main(String[] args) {

        String strDataToEncrypt = new String();
        String strCipherText = new String();
        String strDecryptedText = new String();

        try{
        /**
         *  Step 1. Generate a DES key using KeyGenerator
         *
         */
        KeyGenerator keyGen = KeyGenerator.getInstance("DES");
        SecretKey secretKey = keyGen.generateKey();

        /**
         *  Step2. Create a Cipher by specifying the following parameters
         *          a. Algorithm name - here it is DES
         *          b. Mode - here it is CBC
         *          c. Padding - PKCS5Padding
         */

        Cipher desCipher = Cipher.getInstance("DES/CBC/PKCS5Padding"); /* Must specify the mode explicitly as most JCE providers default to ECB mode!! */

        /**
         *  Step 3. Initialize the Cipher for Encryption
         */

        desCipher.init(Cipher.ENCRYPT_MODE,secretKey);

        /**
         *  Step 4. Encrypt the Data
         *          1. Declare / Initialize the Data. Here the data is of type String
         *          2. Convert the Input Text to Bytes
         *          3. Encrypt the bytes using doFinal method
         */
        strDataToEncrypt = "Hello World of Encryption using DES ";
        byte[] byteDataToEncrypt = strDataToEncrypt.getBytes();
        byte[] byteCipherText = desCipher.doFinal(byteDataToEncrypt);
        strCipherText = Base64.getEncoder().withoutPadding().encodeToString(byteCipherText);
        System.out.println("Cipher Text generated using DES with CBC mode and PKCS5 Padding is " +strCipherText);

        /**
         *  Step 5. Decrypt the Data
         *          1. Initialize the Cipher for Decryption
         *          2. Decrypt the cipher bytes using doFinal method
         */
        desCipher.init(Cipher.DECRYPT_MODE,secretKey,desCipher.getParameters());
         //desCipher.init(Cipher.DECRYPT_MODE,secretKey);
        byte[] byteDecryptedText = desCipher.doFinal(byteCipherText);
        strDecryptedText = new String(byteDecryptedText);
        System.out.println(" Decrypted Text message is " +strDecryptedText);
        }

        catch (NoSuchAlgorithmException noSuchAlgo)
        {
            System.out.println(" No Such Algorithm exists " + noSuchAlgo);
        }

            catch (NoSuchPaddingException noSuchPad)
            {
                System.out.println(" No Such Padding exists " + noSuchPad);
            }

                catch (InvalidKeyException invalidKey)
                {
                    System.out.println(" Invalid Key " + invalidKey);
                }

                catch (BadPaddingException badPadding)
                {
                    System.out.println(" Bad Padding " + badPadding);
                }

                catch (IllegalBlockSizeException illegalBlockSize)
                {
                    System.out.println(" Illegal Block Size " + illegalBlockSize);
                }

                catch (InvalidAlgorithmParameterException invalidParam)
                {
                    System.out.println(" Invalid Parameter " + invalidParam);
                }
    }

}
Doctor visit helper

Prepare before seeing a doctor

A simple rural-patient checklist to help you explain symptoms clearly, ask better questions, and avoid unsafe self-treatment.

Safety note: This is not a prescription or diagnosis. For severe symptoms, pregnancy danger signs, children with serious illness, chest pain, breathing difficulty, stroke-like weakness, or major injury, seek urgent care.

Which doctor may help?

Start with a registered doctor or the nearest qualified health center.

What to tell the doctor

  • Write when the problem started and how it changed.
  • Bring old prescriptions, investigation reports, and current medicines.
  • Write allergies, pregnancy status, diabetes, kidney/liver disease, and major past illnesses.
  • Bring one family member if the patient is weak, elderly, confused, or a child.

Questions to ask

  • What is the most likely cause of my symptoms?
  • Which danger signs mean I should go to hospital quickly?
  • Which tests are necessary now, and which can wait?
  • How should I take medicines safely and what side effects should I watch for?
  • When should I come for follow-up?

Tests to discuss

  • Vital signs: temperature, pulse, blood pressure, oxygen saturation
  • Basic physical examination by a clinician
  • CBC, urine test, blood sugar, or imaging only when clinically needed

Avoid these mistakes

  • Do not use antibiotics, steroid tablets/injections, or strong painkillers without proper medical advice.
  • Do not hide pregnancy, kidney disease, ulcer, allergy, or blood thinner use.
  • Do not delay emergency care when danger signs are present.

Medicine safety and first-aid guide

This section is for patient education only. It does not replace a doctor, pharmacist, or emergency care.

Safe first steps

  • Rest, drink safe water, and observe symptoms carefully.
  • Keep a written note of symptoms, duration, temperature, medicines already taken, and allergy history.
  • Seek medical care quickly if symptoms are severe, worsening, or unusual for the patient.

OTC medicine safety

  • For mild pain or fever, ask a registered pharmacist or doctor before using common over-the-counter pain/fever medicines.
  • Do not combine multiple pain medicines without advice, especially if you have kidney disease, liver disease, stomach ulcer, asthma, pregnancy, or take blood thinners.
  • Do not give adult medicines to children unless a qualified clinician advises it.

Avoid these mistakes

  • Do not start antibiotics without a proper medical decision.
  • Do not use steroid tablets or injections casually for quick relief.
  • Do not delay emergency care because of home remedies.

Get urgent help if

  • Severe symptoms, confusion, fainting, breathing difficulty, chest pain, severe dehydration, or sudden weakness need urgent medical care.
Medicine names, dose, and timing must be decided by a qualified clinician or pharmacist after checking age, pregnancy, allergy, other diseases, and current medicines.

For rural patients and family caregivers

Patient health record and symptom diary

Write your symptoms, medicines already taken, test results, and questions before visiting a doctor. This note stays on your device unless you print or copy it.

Doctor to discuss: Doctor / qualified healthcare provider
Tests to discuss with doctor
  • Basic vital signs: temperature, pulse, blood pressure, oxygen level if needed
  • Relevant blood, urine, imaging, or specialist tests only after clinical assessment
Questions to ask
  • What is the most likely cause of my symptoms?
  • Which warning signs mean I should go to emergency care?
  • Which tests are really needed now?
  • Which medicines are safe for my age, pregnancy status, allergy, kidney/liver/stomach condition, and current medicines?

Emergency warning signs such as chest pain, severe breathing difficulty, sudden weakness, confusion, severe dehydration, major injury, or loss of bladder/bowel control need urgent medical care. Do not wait for online information.

Safe pathway to proper treatment

Care roadmap for: Using the Java Cryptographic Extensions

Use this simple roadmap to understand the next safe steps. It is educational and does not replace examination by a doctor.

Go to emergency care if you notice:
  • Severe or rapidly worsening symptoms
  • Breathing difficulty, chest pain, fainting, confusion, severe weakness, major injury, or severe dehydration
Doctor / service to discuss: Qualified healthcare provider; specialist depends on symptoms and examination.
  1. Step 1

    Check danger signs first

    If danger signs are present, seek emergency care and do not wait for online information.

  2. Step 2

    Record the symptom story

    Write when symptoms started, severity, medicines already taken, allergies, pregnancy status, and test results.

  3. Step 3

    Visit a qualified clinician

    A doctor, nurse, or qualified healthcare provider can examine you and decide which tests or treatment are needed.

  4. Step 4

    Do only useful tests

    Do tests after clinical assessment. Avoid unnecessary tests, random antibiotics, or repeated medicines without diagnosis.

  5. Step 5

    Follow up and return early if worse

    If symptoms worsen, new warning signs appear, or treatment is not helping, return for review quickly.

Rural patient practical tips
  • Take a written symptom diary and all previous prescriptions/test reports.
  • Do not hide medicines already taken, even herbal or over-the-counter medicines.
  • Ask which warning signs mean urgent referral to hospital.

This roadmap is for education. A real diagnosis and treatment plan requires history, examination, and clinical judgment.

Internal learning pathway

Explore related RX articles

Related guides from RX Harun are grouped to help readers move from overview to symptoms, tests, treatment, and safe next steps.

Rx iT World Hacking Tutorial
  1. Transient Blockage of the Internal Iliac Artery DefinitionThe internal iliac artery? is a crucial blood vessel in the pelvis?, responsible for supplying blood…
  2. GraphQL DefinitionGraphQL is an open source query language originally developed by Facebook that can be used to build…
  3. Forgot Password Service DefinitionIn order to implement a proper user management system, systems integrate a Forgot Password service that allows the…
  4. File upload DefinitionFile upload is becoming a more and more essential part of any application, where the user…
  5. Error Handling DefinitionError handling is a part of the overall security of an application. Except in movies, an…
  6. The .NET Framework DefinitionThe .NET Framework is Microsoft’s principal platform for enterprise development. It is the supporting API for…