1 #define BEECRYPT_DLL_EXPORT
2 
3 #include "beecrypt/pkcs1.h"
4 
5 const byte EMSA_MD2_DIGESTINFO[18] = {
6 	0x30,0x20,0x30,0x0c,0x06,0x08,0x2a,0x86,0x48,0x86,0xf7,0x0d,0x02,0x02,0x05,0x00,
7 	0x04,0x10
8 };
9 
10 const byte EMSA_MD5_DIGESTINFO[18] = {
11 	0x30,0x20,0x30,0x0c,0x06,0x08,0x2a,0x86,0x48,0x86,0xf7,0x0d,0x02,0x05,0x05,0x00,
12 	0x04,0x10
13 };
14 
15 const byte EMSA_SHA1_DIGESTINFO[15] = {
16 	0x30,0x21,0x30,0x09,0x06,0x05,0x2b,0x0e,0x03,0x02,0x1a,0x05,0x00,0x04,0x14
17 };
18 
19 const byte EMSA_SHA256_DIGESTINFO[19] = {
20 	0x30,0x31,0x30,0x0d,0x06,0x09,0x60,0x86,0x48,0x01,0x65,0x03,0x04,0x02,0x01,0x05,
21 	0x00,0x04,0x20
22 };
23 
24 const byte EMSA_SHA384_DIGESTINFO[19] = {
25 	0x30,0x41,0x30,0x0d,0x06,0x09,0x60,0x86,0x48,0x01,0x65,0x03,0x04,0x02,0x03,0x05,
26 	0x00,0x04,0x30
27 };
28 
29 const byte EMSA_SHA512_DIGESTINFO[19] = {
30 	0x30,0x51,0x30,0x0d,0x06,0x09,0x60,0x86,0x48,0x01,0x65,0x03,0x04,0x02,0x03,0x05,
31 	0x00,0x04,0x40
32 };
33 
pkcs1_emsa_encode_digest(hashFunctionContext * ctxt,byte * emdata,size_t emlen)34 int pkcs1_emsa_encode_digest(hashFunctionContext* ctxt, byte* emdata, size_t emlen)
35 {
36 	int rc = -1;
37 	const byte* tinfo;
38 	size_t tlen, digestsize = ctxt->algo->digestsize;
39 
40 	if (strcmp(ctxt->algo->name, "MD5") == 0)
41 	{
42 		/* tlen is 18 bytes for EMSA_MD5_DIGESTINFO plus digestsize */
43 		tinfo = EMSA_MD5_DIGESTINFO;
44 		tlen = 18;
45 	}
46 	else if (strcmp(ctxt->algo->name, "SHA-1") == 0)
47 	{
48 		/* tlen is 15 bytes for EMSA_SHA1_DIGESTINFO plus digestsize */
49 		tinfo = EMSA_SHA1_DIGESTINFO;
50 		tlen = 15;
51 	}
52 	else if (strcmp(ctxt->algo->name, "SHA-256") == 0)
53 	{
54 		/* tlen is 19 bytes for EMSA_SHA256_DIGESTINFO plus digestsize */
55 		tinfo = EMSA_SHA256_DIGESTINFO;
56 		tlen = 19;
57 	}
58 	else if (strcmp(ctxt->algo->name, "SHA-384") == 0)
59 	{
60 		/* tlen is 19 bytes for EMSA_SHA384_DIGESTINFO plus digestsize */
61 		tinfo = EMSA_SHA384_DIGESTINFO;
62 		tlen = 19;
63 	}
64 	else if (strcmp(ctxt->algo->name, "SHA-512") == 0)
65 	{
66 		/* tlen is 19 bytes for EMSA_SHA512_DIGESTINFO plus digestsize */
67 		tinfo = EMSA_SHA512_DIGESTINFO;
68 		tlen = 19;
69 	}
70 	else
71 		goto cleanup;
72 
73 	tlen += digestsize;
74 
75 	/* fill emdata with 0x00 0x01 0xff .... 0xff 0x00 EMSA_x_DIGESTINFO DIGEST */
76 	emdata[0] = 0x00;
77 	emdata[1] = 0x01;
78 	memset(emdata+2, 0xff, emlen-tlen-3);
79 	emdata[emlen-tlen-1] = 0x00;
80 	memcpy(emdata+emlen-tlen, tinfo, tlen-digestsize);
81 
82 	hashFunctionContextDigest(ctxt, emdata+emlen-digestsize);
83 
84 	rc = 0;
85 
86 cleanup:
87 
88 	return rc;
89 }
90