summaryrefslogtreecommitdiff
path: root/set6/task41.c
blob: 6793ecc219bd31c8b17827734c00db4a50809cc4 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
#include "../lib/lib.h"
#include "../lib/lib2.h"
#include "../lib/lib3.h"
#include "../lib/lib4.h"
#include "../lib/lib5.h"
#include "../lib/lib6.h"

int main()
{
	struct rsa_key_bignum public, private;
	unsigned char *mess = "Love of my live you hurt me. You stolen my heart";
	BIGNUM *bn_mess = BN_bin2bn(mess, strlen(mess), NULL);
	BIGNUM *encrypted = BN_new();
	BIGNUM *decrypted = BN_new();
	out = BIO_new(BIO_s_file());
	BIO_set_fp(out, stdout, BIO_NOCLOSE);
	ctx = BN_CTX_new();

	printf("plaintext is: %s\n", mess);
	BN_print(out, bn_mess);

	rsa_generate_key_bignum(&public, &private);

	rsa_encrypt_bignum(bn_mess, encrypted, &public);

	printf("\nencrpyted message is:\n");
	BN_print(out, encrypted);
	BIGNUM *S = BN_new();
	// genrate random value mod N
	BN_pseudo_rand(S, 256, -1, -1);
	BN_nnmod(S, S, public.modulo, ctx);
	
	BIGNUM *C_ = BN_new();
	BIGNUM *tmp = BN_new();

	BN_mod_exp(tmp, S, public.exponent, public.modulo, ctx);
	BN_mod_mul(C_, tmp, encrypted, public.modulo, ctx);

	printf("\nmodified ciphertext for decryption is:\n");
	BN_print(out, C_);

	// ok submit this totally differen ciphertext for decryption
	rsa_decrypt_bignum(C_, decrypted, &private);
	// multiply by modinv of s
	modular_multiplicative_inverse_bignum_my(tmp, S, public.modulo);
	BN_mod_mul(tmp, decrypted, tmp, public.modulo, ctx);
	printf("\nrecovered plaintext is:\n");
	BN_print(out, tmp);
	printf("\n");
	unsigned char *__dec = malloc(strlen(mess));
	memset(__dec, 0, strlen(mess));
	BN_bn2bin(tmp, __dec);
	printf("recovered plaintext: %s\n", __dec);

}