BCS3752 Network Security Lab

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 30

PROGRAM NO 1.

Write program for Mono alphabetic cipher in C.

#include <stdio.h>
#include <string.h>
#include <ctype.h>

void monoalphabetic_encrypt(char *text, char key) {


int shift = tolower(key) - 'a';
for (int i = 0; i < strlen(text); i++) {
if (isalpha(text[i])) {
char base = isupper(text[i]) ? 'A' : 'a';
text[i] = base + (text[i] - base + shift) % 26;
}
}
}

void monoalphabetic_decrypt(char *text, char key) {


int shift = tolower(key) - 'a';
for (int i = 0; i < strlen(text); i++) {
if (isalpha(text[i])) {
char base = isupper(text[i]) ? 'A' : 'a';
text[i] = base + (text[i] - base - shift + 26) % 26;
}
}
}

int main() {
char text[100], key;
printf("Enter the text: ");
fgets(text, sizeof(text), stdin);
text[strlen(text) - 1] = '\0'; // remove newline character
printf("Enter the key (a single character): ");
scanf("%c", &key);
getchar(); // consume newline character

monoalphabetic_encrypt(text, key);
printf("Encrypted text: %s\n", text);

monoalphabetic_decrypt(text, key);
printf("Decrypted text: %s\n", text);

return 0;
}
Output :
Enter the text: 23
Enter the key (a single character): 2
Encrypted text: 23
Decrypted text: 23
PROGRAM 2
Implementation of Play Fair cipher in Java.
import java.util.Scanner;

public class PlayfairCipher {

private static char[][] matrix = new char[5][5];

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);
System.out.print("Enter the key: ");
String key = scanner.nextLine();
System.out.print("Enter the plaintext: ");
String plaintext = scanner.nextLine();

generateMatrix(key);

String encryptedText = encrypt(plaintext);


System.out.println("Encrypted Text: " + encryptedText);

String decryptedText = decrypt(encryptedText);


System.out.println("Decrypted Text: " + decryptedText);
}

private static void generateMatrix(String key) {


key = key.toUpperCase().replaceAll("[^A-Z]", "");
key = key.replace("J", "I");
String alphabet = "ABCDEFGHIKLMNOPQRSTUVWXYZ";

StringBuilder uniqueChars = new StringBuilder(key);


for (char ch : alphabet.toCharArray()) {
if (!uniqueChars.toString().contains(String.valueOf(ch))) {
uniqueChars.append(ch);
}
}

int index = 0;
for (int i = 0; i < 5; i++) {
for (int j = 0; j < 5; j++) {
matrix[i][j] = uniqueChars.charAt(index++);
}
}
}

private static String encrypt(String plaintext) {


plaintext = plaintext.toUpperCase().replaceAll("[^A-Z]", "");
plaintext = plaintext.replace("J", "I");
plaintext = prepareText(plaintext);

StringBuilder ciphertext = new StringBuilder();


for (int i = 0; i < plaintext.length(); i += 2) {
char a = plaintext.charAt(i);
char b = plaintext.charAt(i + 1);
int[] rowColA = findPosition(a);
int[] rowColB = findPosition(b);

if (rowColA[0] == rowColB[0]) { // Same row


ciphertext.append(matrix[rowColA[0]][(rowColA[1] + 1) % 5]);
ciphertext.append(matrix[rowColB[0]][(rowColB[1] + 1) % 5]);
} else if (rowColA[1] == rowColB[1]) { // Same column
ciphertext.append(matrix[(rowColA[0] + 1) % 5][rowColA[1]]);
ciphertext.append(matrix[(rowColB[0] + 1) % 5][rowColB[1]]);
} else { // Rectangle
ciphertext.append(matrix[rowColA[0]][rowColB[1]]);
ciphertext.append(matrix[rowColB[0]][rowColA[1]]);
}
}
return ciphertext.toString();
}

private static String decrypt(String ciphertext) {


return encrypt(ciphertext); // Playfair is symmetric
}

private static String prepareText(String text) {


StringBuilder preparedText = new StringBuilder();
for (int i = 0; i < text.length(); i += 2) {
if (i + 1 < text.length() && text.charAt(i) == text.charAt(i + 1)) {
preparedText.append(text.charAt(i)).append('X');
} else {
preparedText.append(text.charAt(i));
if (i + 1 < text.length()) {
preparedText.append(text.charAt(i + 1));
}
}
}
if (preparedText.length() % 2 != 0) {
preparedText.append('X');
}
return preparedText.toString();
}

private static int[] findPosition(char ch) {


for (int i = 0; i < 5; i++) {
for (int j = 0; j < 5; j++) {
if (matrix[i][j] == ch) {
return new int[]{i, j};
}
}
}
return null;
}
}

Output :-
Enter the key: 23
Enter the plaintext: text
Encrypted Text: UDYS
Decrypted Text: TEXT
PROGRAM 3
Implementation of Vigenere cipher (Polyalphabetic substitution)
in C.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>

void upper_case(char *src) {


while (*src != '\0') {
if (islower(*src))
*src &= ~0x20;
src++;
}
}

char* encipher(const char *src, char *key, int is_encode) {


int i, klen, slen;
char *dest;

dest = strdup(src);
upper_case(dest);
upper_case(key);

/* strip out non-letters */


for (i = 0, slen = 0; dest[slen] != '\0'; slen++)
if (isupper(dest[slen]))
dest[i++] = dest[slen];

dest[slen = i] = '\0'; /* null pad it, make it safe to use */

klen = strlen(key);
for (i = 0; i < slen; i++) {
if (!isupper(dest[i]))
continue;
dest[i] = 'A' + (is_encode ? dest[i] - 'A' + key[i % klen] - 'A'
: dest[i] - key[i % klen] + 26) % 26;
}

return dest;
}

int main() {
const char *str = "Beware the Jabberwock, my son! The jaws that bite, "
"the claws that catch!";
const char *cod, *dec;
char key[] = "VIGENERECIPHER";

printf("Text: %s\n", str);


printf("key: %s\n", key);

cod = encipher(str, key, 1);


printf("Code: %s\n", cod);
dec = encipher(cod, key, 0);
printf("Back: %s\n", dec);

/* free(dec); free(cod); *//* nah */


return 0;
}

OUTPUT:-

Text: Beware the Jabberwock, my son! The jaws that bite, the claws that catch!
key: VIGENERECIPHER
Code:
WMCEEIKLGRPIFVMEUGXQPWQVIOIAVEYXUEKFKBTALVXTGAFXYEV
KPAGY
Back:
BEWARETHEJABBERWOCKMYSONTHEJAWSTHATBITETHECLAWSTHAT
CATCH

PROGRAM 4
Implementation of Hill cipher in Java.

class hillCipher {
/* 3x3 key matrix for 3 characters at once */
public static int[][] keymat = new int[][] { { 1, 2, 1 }, { 2, 3, 2 },
{ 2, 2, 1 } }; /* key inverse matrix */
public static int[][] invkeymat = new int[][] { { -1, 0, 1 }, { 2, -1, 0 }, { -2, 2, -1
} };
public static String key = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
private static String encode(char a, char b, char c) {
String ret = "";
int x, y, z;
int posa = (int) a - 65;
int posb = (int) b - 65;
int posc = (int) c - 65;
x = posa * keymat[0][0] + posb * keymat[1][0] + posc * keymat[2][0];
y = posa * keymat[0][1] + posb * keymat[1][1] + posc * keymat[2][1];
z = posa * keymat[0][2] + posb * keymat[1][2] + posc * keymat[2][2];
a = key.charAt(x % 26);
b = key.charAt(y % 26);
c = key.charAt(z % 26);
ret = "" + a + b + c;
return ret;
}
private static String decode(char a, char b, char c) {
String ret = "";
int x, y, z;
int posa = (int) a - 65;
int posb = (int) b - 65;
int posc = (int) c - 65;
x = posa * invkeymat[0][0] + posb * invkeymat[1][0] + posc *
invkeymat[2][0];
y = posa * invkeymat[0][1] + posb * invkeymat[1][1] + posc *
invkeymat[2][1];
z = posa * invkeymat[0][2] + posb * invkeymat[1][2] + posc *
invkeymat[2][2];
a = key.charAt((x % 26 < 0) ? (26 + x % 26) : (x % 26));
b = key.charAt((y % 26 < 0) ? (26 + y % 26) : (y % 26));
c = key.charAt((z % 26 < 0) ? (26 + z % 26) : (z % 26));
ret = "" + a + b + c;
return ret;
}
public static void main(String[] args) throws java.lang.Exception {
String msg;
String enc = "";
String dec = "";
int n;
msg = ("SecurityLaboratory");
System.out.println("simulation of Hill Cipher\n-------------------------");
System.out.println("Input message : " + msg);
msg = msg.toUpperCase();
msg = msg.replaceAll("\\s", "");
/* remove spaces */ n = msg.length() % 3;
/* append padding text X */ if (n != 0) {
for (int i = 1; i <= (3 - n); i++) {
msg += 'X';
}
}
System.out.println("padded message : " + msg);
char[] pdchars = msg.toCharArray();
for (int i = 0; i < msg.length(); i += 3) {
enc += encode(pdchars[i], pdchars[i + 1], pdchars[i + 2]);
}
System.out.println("encoded message : " + enc);
char[] dechars = enc.toCharArray();
for (int i = 0; i < enc.length(); i += 3) {
dec += decode(dechars[i], dechars[i + 1], dechars[i + 2]);
}
System.out.println("decoded message : " + dec);
}
}

Output:
simulation of Hill Cipher
-------------------------
Input message : SecurityLaboratory
padded message : SECURITYLABORATORY
encoded message : EACSDKLCAEFQDUKSXU
decoded message : SECURITYLABORATORY

PROGRAM 5
Implementation of Gauss cipher.

public class GaussCipher {

public static void main(String[] args) {


int a = 3; // Coefficient 'a' for the Gauss cipher equation
int b = 5; // Coefficient 'b' for the Gauss cipher equation
String plaintext = "hello"; // Plaintext to encrypt
String ciphertext = gaussEncrypt(plaintext, a, b); // Encrypt plaintext
System.out.println("Ciphertext: " + ciphertext); // Print ciphertext
String decrypted = gaussDecrypt(ciphertext, a, b); // Decrypt ciphertext
System.out.println("Decrypted text: " + decrypted); // Print decrypted text
}

// Function to encrypt using Gauss cipher


public static String gaussEncrypt(String plaintext, int a, int b) {
StringBuilder ciphertext = new StringBuilder();
for (char c : plaintext.toCharArray()) {
int x = c - 'a'; // Convert character to numerical value
int encrypted = (a * x + b) % 26; // Apply Gauss cipher equation
ciphertext.append((char) (encrypted + 'a')); // Convert back to character
}
return ciphertext.toString();
}

// Function to decrypt using Gauss cipher


public static String gaussDecrypt(String ciphertext, int a, int b) {
int modularInverse = findModularInverse(a, 26); // Find modular inverse of 'a'
StringBuilder decrypted = new StringBuilder();
for (char c : ciphertext.toCharArray()) {
int x = c - 'a'; // Convert character to numerical value
int decryptedValue = (x - b) * modularInverse % 26; // Apply decryption formula
decryptedValue = (decryptedValue % 26 + 26) % 26; // Ensure positive result
decrypted.append((char) (decryptedValue + 'a')); // Convert back to character
}
return decrypted.toString();
}

// Function to find the modular inverse of a number


public static int findModularInverse(int a, int m) {
for (int i = 0; i < m; i++) {
if ((a * i) % m == 1) {
return i;
}
}
return -1; // Modular inverse not found
}
}

OUTPUT :-
Ciphertext: armmv
Decrypted text: hello

PROGRAM 6
Implementation of Rail Fence cipher In C.
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
main()
{
int i,j,len,rails,count,code[100][1000];
char str[1000];
printf("Enter a Secret Message\n");
gets(str);
len=strlen(str);
printf("Enter number of rails\n");
scanf("%d",&rails);
for(i=0;i<rails;i++)
{
for(j=0;j<len;j++)
{
code[i][j]=0;
}
}
count=0;
j=0;
while(j<len)
{
if(count%2==0)
{
for(i=0;i<rails;i++)
{
//strcpy(code[i][j],str[j]);
code[i][j]=(int)str[j];
j++;
}

}
else
{

for(i=rails-2;i>0;i--)
{
code[i][j]=(int)str[j];
j++;
}
}

count++;
}
for(i=0;i<rails;i++)
{
for(j=0;j<len;j++)
{
if(code[i][j]!=0)
printf("%c",code[i][j]);
}

}
printf("\n");
}

OUTPUT:
Enter a Secret Message
34
Enter number of rails
25
34
PROGRAM 7
Implementation of S-DES algorithm for data encryption in
JAVA

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.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import java.io.*;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.spec.InvalidKeySpecException;

class DES{
public static void main(String[] args) throws IOException, NoSuchAlgorithmException,
InvalidKeyException, InvalidKeySpecException, NoSuchPaddingException,
IllegalBlockSizeException, BadPaddingException {

//String we want to encrypt


String message="This is a confidential message.";
byte[] myMessage =message.getBytes(); //string to byte array as DES works on bytes

//If you want to use your own key


// SecretKeyFactory MyKeyFactory = SecretKeyFactory.getInstance("DES");
// String Password = "My Password";
// byte[] mybyte =Password.getBytes();
// DESKeySpec myMaterial = new DESKeySpec(mybyte);
// SecretKey myDESKey = MyKeyFactory.generateSecret(myMaterial);

//Generating Key
KeyGenerator Mygenerator = KeyGenerator.getInstance("DES");
SecretKey myDesKey = Mygenerator.generateKey();

//initializing crypto algorithm


Cipher myCipher = Cipher.getInstance("DES");
//setting encryption mode
myCipher.init(Cipher.ENCRYPT_MODE, myDesKey);
byte[] myEncryptedBytes=myCipher.doFinal(myMessage);

//setting decryption mode


myCipher.init(Cipher.DECRYPT_MODE, myDesKey);
byte[] myDecryptedBytes=myCipher.doFinal(myEncryptedBytes);

//print message in byte format


//System.out.println(Arrays.toString(myEncryptedBytes));
//System.out.println(Arrays.toString(myDecryptedBytes));

String encrypteddata=new String(myEncryptedBytes);


String decrypteddata=new String(myDecryptedBytes);

System.out.println("Message : "+ message);


System.out.println("Encrypted - "+ encrypteddata);
System.out.println("Decrypted Message - "+ decrypteddata);
}
}

OUTPUT:-
Message : This is a confidential message.
Encrypted - P????!????P?sWE??'~?
ecrypted Message - This is a confidential message.
PROGRAM 8
Implement RSA asymmetric (public key and private key)-
Encryption. Encryption key (e, n) & (d,n)
#include<stdio.h>
#include<stdlib.h>
#include<math.h>
#include<string.h>

long int p, q, n, t, flag, e[100], d[100], temp[100], j, m[100], en[100], i;


char msg[100];

int prime(long int);


void ce();
long int cd(long int);
void encrypt();
void decrypt();

int main()
{
printf("ENTER FIRST PRIME NUMBER: ");
scanf("%ld", &p);
flag = prime(p);
if (flag == 0 || p == 1)
{
printf("WRONG INPUT\n");
exit(1);
}

printf("ENTER ANOTHER PRIME NUMBER: ");


scanf("%ld", &q);
flag = prime(q);
if (flag == 0 || q == 1 || p == q)
{
printf("WRONG INPUT\n");
exit(1);
}
printf("ENTER MESSAGE: ");
scanf(" %[^\n]s", msg);
for (i = 0; i < strlen(msg); i++)
m[i] = msg[i];

n = p * q;
t = (p - 1) * (q - 1);

ce();

printf("\nPOSSIBLE VALUES OF e AND d ARE:\n");


for (i = 0; i < j - 1; i++)
printf("%ld\t%ld\n", e[i], d[i]);

encrypt();
decrypt();

return 0;
}

int prime(long int pr)


{
int i;
if (pr == 1)
return 0;

for (i = 2; i <= sqrt(pr); i++)


{
if (pr % i == 0)
return 0;
}
return 1;
}

void ce()
{
int k;
k = 0;
for (i = 2; i < t; i++)
{
if (t % i == 0)
continue;
flag = prime(i);
if (flag == 1 && i != p && i != q)
{
e[k] = i;
flag = cd(e[k]);
if (flag > 0)
{
d[k] = flag;
k++;
}
if (k == 99)
break;
}
}
}

long int cd(long int x)


{
long int k = 1;
while (1)
{
k = k + t;
if (k % x == 0)
return (k / x);
}
}

void encrypt()
{
long int pt, ct, key = e[0], k, len;
i = 0;
len = strlen(msg);
while (i < len)
{
pt = m[i];
pt = pt - 96;
k = 1;
for (j = 0; j < key; j++)
{
k = k * pt;
k = k % n;
}
temp[i] = k;
ct = k + 96;
en[i] = ct;
i++;
}
en[i] = -1;
printf("\nTHE ENCRYPTED MESSAGE IS:\n");
for (i = 0; en[i] != -1; i++)
printf("%c", (char)en[i]);
}

void decrypt()
{
long int pt, ct, key = d[0], k;
i = 0;
while (en[i] != -1)
{
ct = temp[i];
k = 1;
for (j = 0; j < key; j++)
{
k = k * ct;
k = k % n;
}
pt = k + 96;
m[i] = pt;
i++;
}
m[i] = -1;
printf("\nTHE DECRYPTED MESSAGE IS:\n");
for (i = 0; m[i] != -1; i++)
printf("%c", (char)m[i]);
}

OUTPUT:

ENTER FIRST PRIME NUMBER: 5


ENTER ANOTHER PRIME NUMBER: 17
ENTER MESSAGE: Jitendra
POSSIBLE VALUES OF e AND d ARE:
5 65
11 59
13 25
17 89
23 47
29 41
31 7
37 73
41 29
THE ENCRYPTED MESSAGE IS:
I?j?x??a
THE DECRYPTED MESSAGE IS:
Jitendra

RSA algorithm implementation in C


*/

#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int isPrime(int n)
{
int i;
for (i = 2; i <= sqrt(n); i++)
{
if (n % i == 0)
{
return 0;
}
}
return 1;
}

int gcd(int a, int b)


{
if (a == 0)
{
return b;
}
return gcd(b % a, a);
}

int totient(int p, int q)


{
return (p - 1) * (q - 1);
}

int randome(int lambda_n)


{
printf("\nThe number e should be less than %d\n and greater than 1.",
lambda_n);
for (int i = 2; i < lambda_n; i++)
{
if (gcd(i, lambda_n) == 1)
{
return i;
}
}
return -1;
}

int private_key(int e, int lambda_n)


{
for (int i = 1; i < lambda_n; i++)
{
if ((i * e) % lambda_n == 1)
{
printf("\nThus, (i * e) %% lambda_n = 1, (%d * %d) %% %d = 1", i, e,
lambda_n);
return i;
}
}

return -1;
}

long pomod(long a, long b, long m)


{
long x = 1, y = a;
while (b > 0)
{
if (b % 2 == 1)
{
x = (x * y) % m;
}
y = (y * y) % m;
b /= 2;
}
return x % m;
}

/* Encryption
* a procedure that requires the message, the public key, and an integer n w
hich is the sum of p and q. Using the public key, the function encrypts the me
ssage and then returns the result.
*/

char *encrypt(char *message, long e, long n)


{
long i;
long len = strlen(message);
char *cipher = (char *)malloc(len * sizeof(char));
for (i = 0; i < len; i++)
{
cipher[i] = pomod(message[i], e, n);
printf("\n%c -> %c", message[i], cipher[i]);
}
return cipher;
}

/* Decryption
* a procedure that requires the cypher text, the private key, and an integer
n, which is the sum of the values of p and q. The function uses the private ke
y to decode the cypher text and then returns the message that has been dec
rypted.
*/

char *decrypt(char *cipher, long d, long n)


{
long i;
long len = strlen(cipher);
char *message = (char *)malloc(len * sizeof(char));
for (i = 0; i < len; i++)
{
// message[i] = (long) pow(cipher[i], d) % n;
message[i] = pomod(cipher[i], d, n);
printf("\n%c -> %c", cipher[i], message[i]);
}
return message;
}

int main()
{
int p, q, lambda_n;
long n, e, d;
char *message;
char *cipher;
printf("\nEnter the value of p: ");
scanf("%d", &p);
printf("\nEnter the value of q: ");
scanf("%d", &q);
if (isPrime(p) && isPrime(q))
{
n = p * q;
lambda_n = totient(p, q);
e = randome(lambda_n);
d = private_key(e, lambda_n);
printf("\nThe value of n is %ld", n);
printf("\nThe value of lambda_n is %d", lambda_n);
printf("\nThe value of e is %ld", e);
printf("\nThe value of d is %ld", d);
printf("\nEnter the message: ");
message = (char *)malloc(sizeof(char) * 100);
scanf("%s", message);
cipher = encrypt(message, e, n);
puts("\nThe encrypted message is: ");
printf("%s", cipher);
message = decrypt(cipher, d, n);
puts("\nThe original message was: ");
printf("%s", message);
}
else

{
printf("\nThe value of p and q should be prime.");
}
return 0;
}

Output:

Cases of Runtime Testing


In this instance, we enter the two prime numbers "5" and "13", and
then encrypt and decrypt a message using the RSA technique.

Enter the value of p: 5


Enter the value of q: 13
The number e should be less than 48
and greater than 1.
Thus, (i * e) % lambda_n = 1, (29 * 5) % 48 = 1
The value of n is 65
The value of lambda_n is 48
The value of e is 5
The value of d is 29
Enter the message: mango
m -> ,
a ->
n ->
g ->&
o ->

The encrypted message is:


,&

, -> ,
, -> ,
->
-> -
& ->&

-> .
The original message was:
, -&.
PROGRAM 9
Generate digital signature using Hash code in C.

/ DSA
#include<stdio.h>
#include<conio.h>
#include<math.h>

long int ext_eucledian(long int m,long int b)


{
int a1=1,a2=0,a3=m,b1=0,b2=1,b3=b,q,t1,t2,t3;
while(1)
{
if(b3==0)
{
return 0;
}
if(b3==1)
{
if(b2<0)
b2+=m;
return b2;
}
q=a3/b3;
t1=a1-(q*b1);
t2=a2-(q*b2);
t3=a3-(q*b3);
a1=b1;
a2=b2;
a3=b3;
b1=t1;
b2=t2;
b3=t3;
}
}

long int power(long int a, long int j, long int c)


{
int f,i;
f=1;
for(i=1;i<=j;i++)
{
f=(f*a)%c;
}
f=f%c;
return f;
}

void main()
{
long int p,q,g,x,hm,k,y,r,s,s1,w,u1,u2,v,v1,v2,v3;
clrscr();
printf("enter the value of p:");
scanf("%ld",&p);
printf("enter the value of q:");
scanf("%ld",&q);
printf("enter the value of g:");
scanf("%ld",&g);
printf("enter the value of x:");
scanf("%ld",&x);
printf("enter the value of hm:");
scanf("%ld",&hm);
printf("enter the value of k:");
scanf("%ld",&k);
y=power(g,x,p);
printf("\nvalue of y:%ld",y);
r=power(g,k,p);
r=r%q;
printf("\nvalue of r:%ld",r);
s=ext_eucledian(q,k);
s1=(hm+(x*r));
s=(s*s1)%q;
printf("\nvalue of s:%ld",s);
w=ext_eucledian(q,s);
printf("\nsignature (r,s):%ld %ld",r,s);
printf("\nvalue of w:%ld",w);
u1=(hm*w)%q;
printf("\nvalue of u1:%ld",u1);
u2=(r*w)%q;
printf("\nvalue of u2:%ld",u2);
v=power(g,u1,p);
v1=power(y,u2,p);
v2=(v*v1)%p;
v3=v2%q;
printf("\nvalue of v:%ld",v3);
getch();
}

OUTPUT:
Enter the value of p:283
Enter the value of q : 47
Enter the value of g : 60
Enter the value of x : 24
Enter the value of hm : 41
Enter the value of k : 15
Value of y : 158
Value of r :19
Value of s : 30
Signature (r, s): 19 30
Value of w : 11
Value of u1 :28
Value of u2 : 21
Value of v : 19
PROGRAM 10
Generate digital signature using MAC code.

/ Java implementation for Generating


// and verifying the digital signature

package java_cryptography;

// Imports
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.SecureRandom;
import java.security.Signature;
import java.util.Scanner;

import javax.xml.bind.DatatypeConverter;

public class Digital_Signature_GeeksforGeeks {

// Signing Algorithm
private static final String
SIGNING_ALGORITHM
= "SHA256withRSA";
private static final String RSA = "RSA";
private static Scanner sc;

// Function to implement Digital signature


// using SHA256 and RSA algorithm
// by passing private key.
public static byte[] Create_Digital_Signature(
byte[] input,
PrivateKey Key)
throws Exception
{
Signature signature
= Signature.getInstance(
SIGNING_ALGORITHM);
signature.initSign(Key);
signature.update(input);
return signature.sign();
}

// Generating the asymmetric key pair


// using SecureRandom class
// functions and RSA algorithm.
public static KeyPair Generate_RSA_KeyPair()
throws Exception
{
SecureRandom secureRandom
= new SecureRandom();
KeyPairGenerator keyPairGenerator
= KeyPairGenerator
.getInstance(RSA);
keyPairGenerator
.initialize(
2048, secureRandom);
return keyPairGenerator
.generateKeyPair();
}

// Function for Verification of the


// digital signature by using the public key
public static boolean
Verify_Digital_Signature(
byte[] input,
byte[] signatureToVerify,
PublicKey key)
throws Exception
{
Signature signature
= Signature.getInstance(
SIGNING_ALGORITHM);
signature.initVerify(key);
signature.update(input);
return signature
.verify(signatureToVerify);
}

// Driver Code
public static void main(String args[])
throws Exception
{

String input
= "GEEKSFORGEEKS IS A"
+ " COMPUTER SCIENCE PORTAL";
KeyPair keyPair
= Generate_RSA_KeyPair();

// Function Call
byte[] signature
= Create_Digital_Signature(
input.getBytes(),
keyPair.getPrivate());

System.out.println(
"Signature Value:\n "
+ DatatypeConverter
.printHexBinary(signature));

System.out.println(
"Verification: "
+ Verify_Digital_Signature(
input.getBytes(),
signature, keyPair.getPublic()));
}
}

OUTPUT:

You might also like