Blockchain & Solidity Program Lab Manual
ISBN 9788119221646

Highlights

Notes

  

Prog. 5: Blockchain Public Key Cryptography

import java.security.*; 
import javax.crypto.*; 
import java.util.*;

// Public Key Example

public class PublicKeyDemo

{

static KeyPair keyPair;

static String algorithm = “RSA”;

public static void main(String args[]) throws Exception

{

KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(algorithm);

keyPairGenerator.initialize(512);

keyPair = keyPairGenerator.generateKeyPair();

Cipher cipher = Cipher.getInstance(algorithm); 
String text = “ University of Mumbai”;

System.out.println(“Public Keys is: “+keyPair.getPublic().toString());

System.out.println(“Private Key is: “+keyPair.getPrivate().toString());

System.out.println(“ “+text);

// Encrypt the text

cipher.init(Cipher.ENCRYPT_MODE, keyPair.getPublic()); 
byte[] encryptedText = cipher.doFinal(text.getBytes());

String ciphertext = new String(Base64.getEncoder().encode(encryptedText)); 
System.out.println(“Encrypted Text is: “+ciphertext);

// Decryption using Private key

cipher.init(Cipher.DECRYPT_MODE, keyPair.getPrivate());

byte[] ciphertextByte = Base64.getDecoder().decode(ciphertext.getBytes()); byte[] decryptedByte = cipher.doFinal(ciphertextByte);

String decryptedString = new String(decryptedByte);

System.out.println(“After decryption text is:”+decryptedString);

}

}

Output: