Question

In: Computer Science

how to write program in java for encrypt and decrypt input text using DH algorithm

how to write program in java for encrypt and decrypt input text using DH algorithm

Solutions

Expert Solution

import java.io.UnsupportedEncodingException;

import java.security.InvalidAlgorithmParameterException;

import java.security.InvalidKeyException;

import java.security.Key;

import java.security.KeyPair;

import java.security.KeyPairGenerator;

import java.security.NoSuchAlgorithmException;

import java.security.NoSuchProviderException;

import java.security.PrivateKey;

import java.security.PublicKey;

import java.security.SecureRandom;

import java.util.Enumeration;

import javax.crypto.BadPaddingException;

import javax.crypto.Cipher;

import javax.crypto.IllegalBlockSizeException;

import javax.crypto.KeyAgreement;

import javax.crypto.NoSuchPaddingException;

import javax.crypto.SecretKey;

import javax.crypto.ShortBufferException;

import javax.crypto.spec.IvParameterSpec;

import javax.crypto.spec.SecretKeySpec;

import org.bouncycastle.jce.ECNamedCurveTable;

import org.bouncycastle.jce.spec.ECNamedCurveParameterSpec;

public class Test {

    public static byte[] iv = new SecureRandom().generateSeed(16);

    public static void main(String[] args) {

        String plainText = "Look mah, I'm a message!";

        System.out.println("Original plaintext message: " + plainText);

        // Initialize two key pairs

        KeyPair keyPairA = generateECKeys();

        KeyPair keyPairB = generateECKeys();

        // Create two AES secret keys to encrypt/decrypt the message

        SecretKey secretKeyA = generateSharedSecret(keyPairA.getPrivate(),

                keyPairB.getPublic());

        SecretKey secretKeyB = generateSharedSecret(keyPairB.getPrivate(),

                keyPairA.getPublic());

        // Encrypt the message using 'secretKeyA'

        String cipherText = encryptString(secretKeyA, plainText);

        System.out.println("Encrypted cipher text: " + cipherText);

        // Decrypt the message using 'secretKeyB'

        String decryptedPlainText = decryptString(secretKeyB, cipherText);

        System.out.println("Decrypted cipher text: " + decryptedPlainText);

    }

    public static KeyPair generateECKeys() {

        try {

            ECNamedCurveParameterSpec parameterSpec = ECNamedCurveTable.getParameterSpec("brainpoolp256r1");

            KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(

                    "ECDH", "BC");

            keyPairGenerator.initialize(parameterSpec);

            KeyPair keyPair = keyPairGenerator.generateKeyPair();

          

            return keyPair;

        } catch (NoSuchAlgorithmException | InvalidAlgorithmParameterException

              | NoSuchProviderException e) {

            e.printStackTrace();

            return null;

        }

    }

    public static SecretKey generateSharedSecret(PrivateKey privateKey,

            PublicKey publicKey) {

        try {

            KeyAgreement keyAgreement = KeyAgreement.getInstance("ECDH", "BC");

            keyAgreement.init(privateKey);

            keyAgreement.doPhase(publicKey, true);

            SecretKey key = keyAgreement.generateSecret("AES");

            return key;

        } catch (InvalidKeyException | NoSuchAlgorithmException

                | NoSuchProviderException e) {

            // TODO Auto-generated catch block

            e.printStackTrace();

            return null;

        }

    }

    public static String encryptString(SecretKey key, String plainText) {

        try {

            IvParameterSpec ivSpec = new IvParameterSpec(iv);

            Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding", "BC");

            byte[] plainTextBytes = plainText.getBytes("UTF-8");

            byte[] cipherText;

            cipher.init(Cipher.ENCRYPT_MODE, key, ivSpec);

            cipherText = new byte[cipher.getOutputSize(plainTextBytes.length)];

            int encryptLength = cipher.update(plainTextBytes, 0,

                    plainTextBytes.length, cipherText, 0);

            encryptLength += cipher.doFinal(cipherText, encryptLength);

            return bytesToHex(cipherText);

        } catch (NoSuchAlgorithmException | NoSuchProviderException

                | NoSuchPaddingException | InvalidKeyException

                | InvalidAlgorithmParameterException

                | UnsupportedEncodingException | ShortBufferException

                | IllegalBlockSizeException | BadPaddingException e) {

            e.printStackTrace();

            return null;

        }

    }

    public static String decryptString(SecretKey key, String cipherText) {

        try {

            Key decryptionKey = new SecretKeySpec(key.getEncoded(),

                    key.getAlgorithm());

            IvParameterSpec ivSpec = new IvParameterSpec(iv);

            Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding", "BC");

            byte[] cipherTextBytes = hexToBytes(cipherText);

            byte[] plainText;

            cipher.init(Cipher.DECRYPT_MODE, decryptionKey, ivSpec);

            plainText = new byte[cipher.getOutputSize(cipherTextBytes.length)];

            int decryptLength = cipher.update(cipherTextBytes, 0,

                    cipherTextBytes.length, plainText, 0);

            decryptLength += cipher.doFinal(plainText, decryptLength);

            return new String(plainText, "UTF-8");

        } catch (NoSuchAlgorithmException | NoSuchProviderException

                | NoSuchPaddingException | InvalidKeyException

                | InvalidAlgorithmParameterException

                | IllegalBlockSizeException | BadPaddingException

                | ShortBufferException | UnsupportedEncodingException e) {

            e.printStackTrace();

            return null;

        }

    }

    public static String bytesToHex(byte[] data, int length) {

        String digits = "0123456789ABCDEF";

        StringBuffer buffer = new StringBuffer();

        for (int i = 0; i != length; i++) {

            int v = data[i] & 0xff;

            buffer.append(digits.charAt(v >> 4));

            buffer.append(digits.charAt(v & 0xf));

        }

        return buffer.toString();

    }

    public static String bytesToHex(byte[] data) {

        return bytesToHex(data, data.length);

    }

    public static byte[] hexToBytes(String string) {

        int length = string.length();

        byte[] data = new byte[length / 2];

        for (int i = 0; i < length; i += 2) {

            data[i / 2] = (byte) ((Character.digit(string.charAt(i), 16) << 4) + Character

                    .digit(string.charAt(i + 1), 16));

        }

        return data;

    }

}

Output:

Original plaintext message : Look mah, I'm a message!

Encrypted cipher text: 7AFCF3F9A6213FA6900D3DFC12553379580FC7AD362E2C2E28F548FC2AF42F07CF2B057537376F36

Decrypted cipher text: Look mah, I'm a message!

  


Related Solutions

Write a program in javascript to encrypt and decrypt the user input using the caesar algorithm...
Write a program in javascript to encrypt and decrypt the user input using the caesar algorithm with the substitution algorithm. Specify the min and max of the message user can enter to encrypt. Specify the length of the key user can enter to encrypt and decrypt the message. document your design by words or diagrams.
Write a Java program to encrypt and decrypt a phrase using two similar approaches, each insecure...
Write a Java program to encrypt and decrypt a phrase using two similar approaches, each insecure by modern standards. The first approach is called the Caesar Cipher, and is a simple “substitution cipher” where characters in a message are replaced by a substitute character. The second approach, due to Giovan Battista Bellaso (b 1505, d 1581), uses a key word, where each character in the word specifies the offset for the corresponding character in the message, with the key word...
Write a small program to encrypt and decrypt a message using Python library.
Write a small program to encrypt and decrypt a message using Python library.
Write a Java program that uses the RC4 cipher algorithm to encrypt the following message using...
Write a Java program that uses the RC4 cipher algorithm to encrypt the following message using the word CODES as the key:   Cryptography is a method of protecting information and communications through the use of codes so that only those for whom the information is intended can read and process it. Instead of using stream length 256, we will use length 26. When encrypting, let A = 0 to Z = 25. Ignore spaces and punctuations and put the message...
write a java program to Translate or Encrypt the given string : (input char is all...
write a java program to Translate or Encrypt the given string : (input char is all in capital letters) { 15 } *) Each character replaced by new character based on its position value in english alphabet. As A is position is 1, and Z is position 26. *) New characters will be formed after skipping the N (position value MOD 10) char forward. A->A+1= B , B->B+2=D ,C->C+3=F, .... Y->Y+(25%10)->Y+5=D A B C D E F G H I...
A, B:    Design and Implement a C# windows form application to encrypt and decrypt text....
A, B:    Design and Implement a C# windows form application to encrypt and decrypt text. The application use to receive a string and display another encrypted string. The application also decrypt the encrypted string. The approach for encryption/decryption is simple one i.e. to encrypt we will add 1 to each character, so that "hello" would become "ifmmp", and to decrypt we would subtract 1 from each character.    C:   Test and evaluate application by applying different strings.      ...
Write a Java program to encrypt the following message using the RC4 cipher using key CODES:...
Write a Java program to encrypt the following message using the RC4 cipher using key CODES: Cryptography is a method of protecting information and communications through the use of codes so that only those for whom the information is intended can read and process it. Instead of using stream length 256, we will use length 26. When encrypting, let A = 0 to Z = 25 (hence CODES = [2 14 3 4 18]). Ignore spaces and punctuations and put...
Write a Java program that implements the Depth-First Search (DFS) algorithm. Input format: This is a...
Write a Java program that implements the Depth-First Search (DFS) algorithm. Input format: This is a sample input from a user. 3 2 0 1 1 2 The first line (= 3 in the example) indicates that there are three vertices in the graph. You can assume that the first vertex starts from the number 0. The second line (= 2 in the example) represents the number of edges, and following two lines are the edge information. This is the...
Using a Java. 2. Write a Java program calculate_fare.java to take the input for number of...
Using a Java. 2. Write a Java program calculate_fare.java to take the input for number of miles, and the class of journey (1,2, or 3, for first, second, and third class respectively), for a train journey. The program should then calculate and display the fare of journey based on the following criteria: Note: Use Switch...case and if...else construct First (1) Class Second (1) Class Third (3) Class First 100 mile $ 3 per mile $ 2 per mile $ 1.50...
Write a program in Java that reads an input text file (named: input.txt) that has several...
Write a program in Java that reads an input text file (named: input.txt) that has several lines of text and put those line in a data structure, make all lowercase letters to uppercase and all uppercase letters to lowercase and writes the new lines to a file (named: output.txt).
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT