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 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...
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...
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 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...
In C++ Write a program that contains a function, encrypt(Cypher) that encrypts the below text and...
In C++ Write a program that contains a function, encrypt(Cypher) that encrypts the below text and a second function, decrypt(Cypher),  that decrypts the encrypted message back to normal.  Cypher is the string which contain the plain or cypher texts.  Demonstrate that the encrypted message that you created is correctly decrypted.  For this problem you need to input “All Gaul is …” into a string Cypher.   Julius Caesar was one of the earliest persons to employ cryptology in history.  All his correspondence from his campaigns to...
Write a MIPS program using the Bubble Sort algorithm, that sorts an input list of integers...
Write a MIPS program using the Bubble Sort algorithm, that sorts an input list of integers by repeatedly calling a “swap” subroutine. The original unsorted list of integers should be received from the keyboard input. Your program should first prompt the user “Please input an integer for the number of elements:”. After the user enters a number and return, your program outputs message “Now input each element and then a return:”. For example, if the user enters 5 as the...
Answer in python! 5.16 LAB: Cryptographic Hashing Algorithms Encrypting text allows us to encrypt and decrypt...
Answer in python! 5.16 LAB: Cryptographic Hashing Algorithms Encrypting text allows us to encrypt and decrypt the text using a special key. Another method of encrypting text / passwords is called hashing. Hashing uses special algorithms to 'scramble' text so that it is tougher to hack. The hash function can take numbers, letters, and symbols then uses one of the special algorithms to output scrambled text. The longer the output string, the harder to hack the data. The difference between...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT