· 8 years ago · Feb 05, 2018, 12:20 PM
1JAVAHASH ====================================================================
2
3public static byte[] hashFunction(String fileName, String alg, String provider) throws IOException, NoSuchAlgorithmException, NoSuchProviderException{
4 byte[] result = null;
5
6 File file = new File(fileName);
7 if(!file.exists())
8 file.createNewFile();
9
10 FileInputStream fis = new FileInputStream(file);
11 MessageDigest md = MessageDigest.getInstance(alg, provider);
12
13 byte[] buffer = new byte[1];
14 int noBytes = fis.read(buffer);
15 while(noBytes != -1){
16 md.update(buffer, 0, noBytes);
17 noBytes = fis.read(buffer);
18 }
19
20 result = md.digest();
21
22 return result;
23 }
24
25
26JAVAHMAC =================================================================
27
28public static byte[] hashMACfunction(String inputFile, String secretKey, String alg, String provider) throws NoSuchAlgorithmException, NoSuchProviderException, InvalidKeyException, IOException{
29
30 byte[] result = null;
31
32 File file = new File(inputFile);
33 if(!file.exists())
34 throw new FileNotFoundException();
35
36 FileInputStream fis = new FileInputStream(file);
37
38 Mac hashMac = Mac.getInstance(alg, provider);
39 Key key = new SecretKeySpec(secretKey.getBytes(), alg);
40 hashMac.init(key);
41
42 byte[] buffer = new byte[150];
43 int noBytes = fis.read(buffer);
44 while(noBytes != -1){
45 hashMac.update(buffer, 0, noBytes);
46 noBytes = fis.read(buffer);
47 }
48
49 result = hashMac.doFinal();
50 fis.close();
51
52 return result;
53 }
54
55
56JAVASYMECB==========================================================================
57
58public static void encrypt(String fileInput, String fileOutput, String secretKey, String alg, String provider)
59 throws IOException, NoSuchAlgorithmException, NoSuchProviderException, NoSuchPaddingException,
60 InvalidKeyException, ShortBufferException, IllegalBlockSizeException, BadPaddingException {
61
62 File file = new File(fileInput);
63 if (!file.exists())
64 throw new FileNotFoundException();
65
66 File out = new File(fileOutput);
67 if (!out.exists())
68 file.createNewFile();
69
70 FileInputStream fis = new FileInputStream(file);
71 FileOutputStream fos = new FileOutputStream(out);
72
73 String setUp = alg + "/ECB/PKCS5Padding";
74 Cipher cipher = Cipher.getInstance(setUp, provider);
75
76 Key key = new SecretKeySpec(secretKey.getBytes(), alg);
77 cipher.init(Cipher.ENCRYPT_MODE, key);
78
79 byte[] cipherBuffer;
80 byte[] buffer = new byte[cipher.getBlockSize()];
81 int noBytes = fis.read(buffer);
82
83 while (noBytes != -1) {
84 int outputSize = cipher.getOutputSize(noBytes);// 1
85 cipherBuffer = new byte[outputSize];// 2 facem asta pentru ca
86 // block-urile nu sunt mereu
87 // pline, trebuie sa citim doar
88 // ce avem, nu toata dimensiunea
89 int no = cipher.update(buffer, 0, noBytes, cipherBuffer, 0);
90 fos.write(cipherBuffer, 0, no);
91 noBytes = fis.read(buffer);
92 }
93
94 cipherBuffer = cipher.doFinal();
95 fos.write(cipherBuffer);
96 fis.close();
97 fos.close();
98 }
99
100 public static void decrypt(String fileInput, String fileOutput, String secretKey, String alg, String provider)
101 throws IOException, NoSuchAlgorithmException, NoSuchProviderException, NoSuchPaddingException,
102 InvalidKeyException, ShortBufferException, IllegalBlockSizeException, BadPaddingException {
103
104 File file = new File(fileInput);
105 if (!file.exists())
106 throw new FileNotFoundException();
107
108 File out = new File(fileOutput);
109 if (!out.exists())
110 file.createNewFile();
111
112 FileInputStream fis = new FileInputStream(file);
113 FileOutputStream fos = new FileOutputStream(out);
114
115 String setUp = alg + "/ECB/PKCS5Padding";
116 Cipher cipher = Cipher.getInstance(setUp, provider);
117
118 Key key = new SecretKeySpec(secretKey.getBytes(), alg);
119 cipher.init(Cipher.DECRYPT_MODE, key);
120
121 byte[] cipherBuffer;
122 byte[] buffer = new byte[cipher.getBlockSize()];
123 int noBytes = fis.read(buffer);
124
125 while (noBytes != -1) {
126 int outputSize = cipher.getOutputSize(noBytes);// 1
127 cipherBuffer = new byte[outputSize];// 2 facem asta pentru ca
128 // block-urile nu sunt mereu
129 // pline, trebuie sa citim doar
130 // ce avem, nu toata dimensiunea
131
132 int no = cipher.update(buffer, 0, noBytes, cipherBuffer, 0);
133 fos.write(cipherBuffer, 0, no);
134
135 noBytes = fis.read(buffer);
136 }
137
138 cipherBuffer = cipher.doFinal();
139 fos.write(cipherBuffer);
140
141
142 fis.close();
143 fos.close();
144
145
146 }
147
148
149JAVASYMCBC =================================================================================
150
151public static void encryptCBC(String inputFile, String outputFile, String secretKey, String alg, String provider)
152 throws IOException, NoSuchAlgorithmException, NoSuchProviderException, NoSuchPaddingException,
153 InvalidKeyException, InvalidAlgorithmParameterException, ShortBufferException, IllegalBlockSizeException,
154 BadPaddingException {
155
156 File input = new File(inputFile);
157 File output = new File(outputFile);
158 if (!input.exists())
159 throw new FileNotFoundException();
160
161 if (!output.exists())
162 output.createNewFile();
163
164 FileInputStream fis = new FileInputStream(input);
165 FileOutputStream fos = new FileOutputStream(output);
166
167 String prop = alg + "/CBC/PKCS5Padding";
168 Cipher cipher = Cipher.getInstance(prop, provider);
169
170 Key key = new SecretKeySpec(secretKey.getBytes(), alg);
171
172 byte[] IV = new byte[secretKey.getBytes().length];
173 for (int i = 0; i < IV.length; i++) {
174 IV[i] = (byte) 0xFF;
175 }
176
177 IvParameterSpec iv = new IvParameterSpec(IV);
178
179 cipher.init(Cipher.ENCRYPT_MODE, key, iv);
180
181 fos.write(IV);
182
183 byte[] buffer = new byte[cipher.getBlockSize()];
184 byte[] cipherBlock;
185 int noBytes = fis.read(buffer);
186 while (noBytes != -1) {
187 cipherBlock = new byte[cipher.getOutputSize(noBytes)];
188 int byteRead = cipher.update(buffer, 0, noBytes, cipherBlock);
189 fos.write(cipherBlock, 0, byteRead);
190 noBytes = fis.read(buffer);
191 }
192
193 cipherBlock = cipher.doFinal();
194 fos.write(cipherBlock);
195
196 fis.close();
197 fos.close();
198 }
199
200 public static void decryptCBC(String inputFile, String outputFile, String secretKey, String alg, String provider)
201 throws IOException, NoSuchAlgorithmException, NoSuchProviderException, NoSuchPaddingException,
202 InvalidKeyException, InvalidAlgorithmParameterException, ShortBufferException, IllegalBlockSizeException,
203 BadPaddingException {
204
205 File input = new File(inputFile);
206 File output = new File(outputFile);
207 if (!input.exists())
208 throw new FileNotFoundException();
209
210 if (!output.exists())
211 output.createNewFile();
212
213 FileInputStream fis = new FileInputStream(input);
214 FileOutputStream fos = new FileOutputStream(output);
215
216 String prop = alg + "/CBC/PKCS5Padding";
217 Cipher cipher = Cipher.getInstance(prop, provider);
218
219 Key key = new SecretKeySpec(secretKey.getBytes(), alg);
220
221 byte[] IV = new byte[secretKey.getBytes().length];
222 fis.read(IV);
223
224 IvParameterSpec iv = new IvParameterSpec(IV);
225
226 cipher.init(Cipher.DECRYPT_MODE, key, iv);
227
228 byte[] buffer = new byte[cipher.getBlockSize()];
229 byte[] cipherBlock;
230 int noBytes = fis.read(buffer);
231 while (noBytes != -1) {
232 cipherBlock = new byte[cipher.getOutputSize(noBytes)];
233 int byteRead = cipher.update(buffer, 0, noBytes, cipherBlock, 0);
234 fos.write(cipherBlock, 0, byteRead);
235 noBytes = fis.read(buffer);
236 }
237
238 cipherBlock = cipher.doFinal();
239 fos.write(cipherBlock);
240
241 fis.close();
242 fos.close();
243 }
244
245
246JAVARSA =================================================================================
247
248public static void checkKeyStore(String fileName, String storePass) throws KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException, NoSuchProviderException{
249 File file = new File(fileName);
250 if(!file.exists())
251 throw new FileNotFoundException();
252
253 KeyStore store = KeyStore.getInstance("jks");
254 store.load(new FileInputStream(file), storePass.toCharArray());
255 Enumeration<String> alias = store.aliases();
256 while(alias.hasMoreElements()){
257 String nickname = alias.nextElement();
258 System.out.println("Entry name: " + nickname);
259 if(store.isKeyEntry(nickname))
260 System.out.println("Key pair");
261 if(store.isCertificateEntry(nickname))
262 System.out.println("Certificate");
263 }
264 }
265
266
267 public static PrivateKey getPrivateKey(String ksName, String ksPass, String alias, String password) throws KeyStoreException, NoSuchAlgorithmException, CertificateException, FileNotFoundException, IOException, UnrecoverableKeyException{
268 File file = new File(ksName);
269 KeyStore store = KeyStore.getInstance("JKS");
270
271 store.load(new FileInputStream(file), ksPass.toCharArray());
272
273 return (PrivateKey) store.getKey(alias, password.toCharArray());
274 }
275
276 public static PublicKey getPublicKey(String certificateName) throws CertificateException, FileNotFoundException{
277 File file = new File(certificateName);
278 CertificateFactory factory = CertificateFactory.getInstance("X509");
279 X509Certificate certificate = (X509Certificate) factory.generateCertificate(new FileInputStream(file));
280 return certificate.getPublicKey();
281 }
282
283
284 public static byte[] genertePseudoRandomKey(int size) throws NoSuchAlgorithmException{
285 byte[] result = null;
286
287 KeyGenerator generator = KeyGenerator.getInstance("AES");
288 generator.init(size);
289 result = generator.generateKey().getEncoded();
290 return result;
291 }
292
293 public static byte[] encryptRSA(byte[] input, Key key) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException{
294 byte[] result = null;
295 Cipher cipher = Cipher.getInstance("RSA");
296 cipher.init(Cipher.ENCRYPT_MODE, key);
297 result = cipher.doFinal(input);
298 return result;
299 }
300
301 public static byte[] decryptRSA(byte[] input, Key key) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException{
302 byte[] result = null;
303 Cipher cipher = Cipher.getInstance("RSA");
304 cipher.init(Cipher.DECRYPT_MODE, key);
305 result = cipher.doFinal(input);
306 return result;
307 }
308
309 public static byte[] generateDigitalSignature(byte[] input, PrivateKey pvKey) throws NoSuchAlgorithmException, InvalidKeyException, SignatureException{
310 byte[] result = null;
311 Signature signature = Signature.getInstance("NONEwithRSA");
312 signature.initSign(pvKey);
313 signature.update(input);
314 result = signature.sign();
315 return result;
316 }
317
318
319 public static boolean verifyDigitalSign(byte[] signature, byte[] input, PublicKey publicKey) throws NoSuchAlgorithmException, InvalidKeyException, SignatureException{
320 Signature sign = Signature.getInstance("NONEwithRSA");
321 sign.initVerify(publicKey);
322 sign.update(input);
323 return sign.verify(signature);
324 }
325
326
327
328CHASH ========================================================================================
329
330#include<stdio.h>
331#include<malloc.h>
332#include<conio.h>
333#include<stdlib.h>
334#include "openssl\sha.h"
335
336#define MESSAGE_CHUNK 128
337
338void main(){
339
340 FILE* f = new FILE;
341 FILE* g = fopen("citit.txt", "w");
342 errno_t error;
343 unsigned char* buffer;
344 SHA_CTX context;
345 unsigned char finalDigest[SHA_DIGEST_LENGTH];
346
347 SHA1_Init(&context);
348
349 error = fopen_s(&f, "textSHA1.txt", "rb");
350 if (error == 0){
351 fseek(f, 0, SEEK_END);
352 int fileLen = ftell(f);
353 fseek(f, 0, SEEK_SET);
354
355 buffer = (unsigned char*)malloc(sizeof(char)*fileLen);
356 fread(buffer, fileLen, 1, f);
357 //fwrite(buffer, fileLen, 1, g);
358 unsigned char* tempbuffer = buffer;
359
360 while (fileLen > 0){
361 if (fileLen > MESSAGE_CHUNK){
362 SHA1_Update(&context, tempbuffer, MESSAGE_CHUNK);
363 //fwrite(tempbuffer, MESSAGE_CHUNK, 1, g);
364 }
365 else{
366 SHA1_Update(&context, tempbuffer, fileLen);
367 //fwrite(tempbuffer, fileLen, 1, g);
368 }
369
370 fileLen -= MESSAGE_CHUNK;
371 tempbuffer += MESSAGE_CHUNK;
372 //fwrite(tempbuffer, fileLen, 1, g);
373 }
374
375 SHA1_Final(finalDigest, &context);
376 }
377
378 /*unsigned char value;
379 value = strtol(finalDigest, NULL, 2);*/
380 printf("Hash: ");
381 for (int i = 0; i < SHA_DIGEST_LENGTH; i++){
382 printf("%2X", finalDigest[i]);
383 //fwrite(&finalDigest[i], SHA_DIGEST_LENGTH, 1, g);
384 fprintf(g, "%2X", finalDigest[i]);
385 }
386
387
388 getch();
389}
390
391
392
393CDES ======================================================================================
394
395#include <stdio.h>
396#include <string.h>
397#include <openssl/des.h>
398
399
400unsigned char* DES_CFB_Encrypt(unsigned char* Key, unsigned char* Msg, int size){
401 unsigned char* Res;
402 int n = 0;
403 DES_cblock Key2;
404 DES_key_schedule schedule;
405
406 Res = (unsigned char*)malloc(size);
407
408 memcpy(Key2, Key, 8);
409 DES_set_odd_parity(&Key2);
410 if (DES_set_key_checked(&Key2, &schedule)){
411 printf("Key error, exiting...");
412 return NULL;
413 }
414
415 DES_cfb64_encrypt((unsigned char*)Msg, (unsigned char*)Res, size, &schedule, &Key2, &n, DES_ENCRYPT);
416
417 return Res;
418}
419
420
421unsigned char* DES_CFB_Decrypt(unsigned char *Key, unsigned char *Msg, int size){
422 unsigned char* Res;
423 int n = 0;
424
425 DES_cblock Key2;
426 DES_key_schedule schedule;
427
428 Res = (unsigned char*)malloc(size);
429
430 memcpy(Key2, Key, 8);
431 DES_set_odd_parity(&Key2);
432 if (DES_set_key_checked(&Key2, &schedule)){
433 printf("Key error, exiting...");
434 return NULL;
435 }
436
437 DES_cfb64_encrypt((unsigned char *)Msg, (unsigned char *)Res, size, &schedule, &Key2, &n, DES_DECRYPT);
438
439 return Res;
440}
441
442unsigned char* DES_3_CFB_Encrypt(unsigned char* Key, unsigned char* Msg, int size){
443 unsigned char* Res;
444 int n = 0;
445 DES_cblock kb1 = { 0xAE, 0xAE, 0xAE, 0xAE, 0xAE, 0xAE, 0xAE, 0xAE };
446 DES_cblock kb2 = { 0xAE, 0xAE, 0xAE, 0xAE, 0xAE, 0xAE, 0xAE, 0xAE };
447 DES_cblock kb3 = { 0xAE, 0xAE, 0xAE, 0xAE, 0xAE, 0xAE, 0xAE, 0xAE };
448 DES_key_schedule s1, s2, s3;
449
450 DES_cblock Key2;
451 DES_key_schedule schedule;
452
453 Res = (unsigned char*)malloc(size);
454
455 memcpy(Key2, Key, 8);
456 DES_set_odd_parity(&Key2);
457
458 if (DES_set_key_checked(&kb1, &s1) || DES_set_key_checked(&kb2, &s2) || DES_set_key_checked(&kb3, &s3)) {
459 printf("Key error, exiting ....\n");
460 return NULL;
461 }
462
463 DES_ede3_cfb64_encrypt((unsigned char*)Msg, (unsigned char*)Res, size, &s1, &s2, &s3, &Key2, &n, DES_ENCRYPT);
464
465 return Res;
466}
467
468unsigned char* DES_3_CFB_Decrypt(unsigned char* Key, unsigned char* Msg, int size){
469 unsigned char* Res;
470 int n = 0;
471 DES_cblock kb1 = { 0xAE, 0xAE, 0xAE, 0xAE, 0xAE, 0xAE, 0xAE, 0xAE };
472 DES_cblock kb2 = { 0xAE, 0xAE, 0xAE, 0xAE, 0xAE, 0xAE, 0xAE, 0xAE };
473 DES_cblock kb3 = { 0xAE, 0xAE, 0xAE, 0xAE, 0xAE, 0xAE, 0xAE, 0xAE };
474 DES_key_schedule s1, s2, s3;
475
476 DES_cblock Key2;
477 DES_key_schedule schedule;
478
479 Res = (unsigned char*)malloc(size);
480
481 memcpy(Key2, Key, 8);
482 DES_set_odd_parity(&Key2);
483
484 if (DES_set_key_checked(&kb1, &s1) || DES_set_key_checked(&kb2, &s2) || DES_set_key_checked(&kb3, &s3)) {
485 printf("Key error, exiting ....\n");
486 return NULL;
487 }
488
489 DES_ede3_cfb64_encrypt((unsigned char*)Msg, (unsigned char*)Res, size, &s1, &s2, &s3, &Key2, &n, DES_DECRYPT);
490
491 return Res;
492}
493
494
495
496void main() {
497 unsigned char key[8];
498 // void DES_random_key(DES_cblock *ret); // may be used to generate a random key
499 DES_cblock pass;
500 DES_random_key(&pass);
501 memcpy_s(key, 8, &pass, 8);
502 printf("\nPass: %s\n", key);
503
504 unsigned char* clear = NULL;
505 FILE* fSrc = NULL, *fEnc = NULL, *fDec = NULL;
506
507 fopen_s(&fSrc, "fis.txt", "rb");
508 fseek(fSrc, 0, SEEK_END);
509 long int inLen = ftell(fSrc);
510 fseek(fSrc, 0, SEEK_SET);
511
512 clear = (unsigned char*)malloc(inLen);
513 memset(clear, 0x00, inLen);
514 fread(clear, inLen, 1, fSrc);
515
516 fopen_s(&fEnc, "enc.txt", "wb");
517 fopen_s(&fDec, "dec.txt", "wb");
518 long int outLen = inLen;
519
520 unsigned char *decrypted;
521 unsigned char *encrypted;
522
523 encrypted = (unsigned char*)malloc(sizeof(outLen));
524 decrypted = (unsigned char*)malloc(sizeof(outLen));
525
526
527 printf("Clear text\t : %s \n", clear);
528 encrypted = DES_CFB_Encrypt(key, clear, outLen);
529 fwrite(encrypted, outLen, 1, fEnc);
530 //printf("Encrypted text\t : %s \n",encrypted);
531
532 decrypted = DES_CFB_Decrypt(key, encrypted, outLen);
533 fwrite(decrypted, outLen, 1, fDec);
534 //printf("Decrypted text\t : %s \n",decrypted);
535
536
537
538 fclose(fSrc);
539 fclose(fEnc);
540 fclose(fDec);
541}
542
543
544
545CAES ====================================================================
546
547
548#include <stdio.h>
549#include <string.h>
550#include <malloc.h>
551#include <openssl/aes.h>
552
553int main(int argc, char** argv)
554{
555 if(argc == 5) {
556 FILE* fSrc = NULL, *fDst = NULL;
557 errno_t err;
558 char opt[3];
559 char mode[7];
560 strcpy(opt, argv[1]);
561 strcpy(mode, argv[2]);
562
563 AES_KEY akey;
564 unsigned char* inBuf = NULL;
565 unsigned char* outBuf;
566 unsigned char ivec[16];
567 unsigned char userSymmetricKey[16] = {0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07};
568
569 if(strcmp(opt, "-e") == 0) {
570 fopen_s(&fSrc, argv[3], "rb");
571 fopen_s(&fDst, argv[4], "wb");
572 fseek(fSrc, 0, SEEK_END);
573 long int inLen = ftell(fSrc);
574 fseek(fSrc, 0, SEEK_SET);
575 long int outLen = 0;
576 if((inLen % 16) == 0)
577 outLen = inLen;
578 else
579 outLen = ((inLen/16)*16) + 16;
580
581 inBuf = (unsigned char*)malloc(outLen);
582 outBuf = (unsigned char*)malloc(outLen);
583 memset(inBuf, 0x00, outLen);
584 fread(inBuf, inLen, 1, fSrc);
585
586 AES_set_encrypt_key(userSymmetricKey, 128, &akey);
587 if(strcmp(mode, "-ecb") == 0) {
588 for(int i = 0; i < (outLen/16); i++)
589 AES_encrypt(&(inBuf[i*16]), &(outBuf[i*16]), &akey);
590 } else {
591 memset(&ivec, 0x01, sizeof(ivec));
592 AES_cbc_encrypt(inBuf, outBuf, outLen, &akey, ivec, AES_ENCRYPT);
593 }
594
595 fwrite(&inLen, sizeof(inLen), 1, fDst);
596 fwrite(outBuf, outLen, 1, fDst);
597 free(outBuf);
598 free(inBuf);
599 fclose(fDst);
600 fclose(fSrc);
601 } else {
602 fopen_s(&fSrc, argv[3], "rb");
603 fopen_s(&fDst, argv[4], "wb");
604 fseek(fSrc, 0, SEEK_END);
605 long int inLen = ftell(fSrc) - 4;
606 fseek(fSrc, 0, SEEK_SET);
607 long int outLen = 0;
608 fread(&outLen, sizeof(outLen), 1, fSrc);
609
610 inBuf = (unsigned char*)malloc(inLen);
611 outBuf = (unsigned char*)malloc(inLen);
612 memset(inBuf, 0x00, inLen);
613 fread(inBuf, inLen, 1, fSrc);
614
615 AES_set_decrypt_key(userSymmetricKey, 128, &akey);
616 if(strcmp(mode, "-ecb") == 0) {
617 for(int i = 0; i < (inLen/16); i++)
618 AES_decrypt(&(inBuf[i*16]), &(outBuf[i*16]), &akey);
619 } else {
620 memset(&ivec, 0x01, sizeof(ivec));
621 AES_cbc_encrypt(inBuf, outBuf, inLen, &akey, ivec, AES_DECRYPT);
622 }
623
624 fwrite(outBuf, outLen, 1, fDst);
625 free(outBuf);
626 free(inBuf);
627 fclose(fDst);
628 fclose(fSrc);
629 }
630 } else {
631 printf("\n Usage Mode: OpenSSLProj.exe -e -cbc fSrc.txt fDst.txt");
632 printf("\n Usage Mode: OpenSSLProj.exe -d -ecb fSrc.txt fDst.txt");
633 return 1;
634 }
635 printf("\n Process done.");
636 return 0;
637}
638
639
640CRAS ==============================================================================================
641
642#include <stdio.h>
643#include <malloc.h>
644#include <memory.h>
645
646#include <openssl/pem.h>
647#include <openssl/rsa.h>
648
649int main(int argc, char** argv)
650{
651 if(argc == 4) {
652 FILE* fsrc = NULL;
653 FILE* fdst = NULL;
654 FILE* frst = NULL;
655 errno_t err;
656
657 err = fopen_s(&fsrc, argv[1], "rb");
658 fseek(fsrc, 0, SEEK_END);
659 int fileLen = ftell(fsrc);
660 fseek(fsrc, 0, SEEK_SET);
661
662
663 RSA* apub;
664 RSA* apriv;
665 FILE* f;
666
667 unsigned char* e_data = NULL;
668 unsigned char* last_data = NULL;
669
670 apriv = RSA_new();
671 apub = RSA_new();
672
673 f = fopen("pubKeyFile.pem","r");
674 apub = PEM_read_RSAPublicKey(f, NULL, NULL, NULL);
675 fclose(f);
676
677 err = fopen_s(&fdst, argv[2], "wb");
678
679 //int b=RSA_size(apub);
680 int b = 116;
681 unsigned char* fsrcbuf = (unsigned char*)malloc(b+1);
682 fsrcbuf[b]=0x00;
683 e_data = (unsigned char *) malloc(b+1);
684 e_data[b]=0x00;
685 while(fread(fsrcbuf, sizeof(unsigned char), b, fsrc)== b){
686 RSA_public_encrypt(b, fsrcbuf, e_data, apub, RSA_PKCS1_PADDING);
687
688 fwrite(e_data, sizeof(unsigned char), b, fdst);
689 }
690 RSA_public_encrypt(fileLen % b, fsrcbuf, e_data, apub, RSA_PKCS1_PADDING);
691 fwrite(e_data, sizeof(unsigned char), b, fdst);
692
693 f = fopen("privKeyFile.pem","r");
694 apriv = PEM_read_RSAPrivateKey(f, NULL, NULL, NULL);
695 fclose(f);
696
697 //free(e_data);
698 //e_data = (unsigned char *) malloc(b + 1);
699 last_data = (unsigned char *) malloc(b + 1);
700 //e_data[b] = 0x00;
701 last_data[b] = 0x00;
702 fclose(fdst);
703
704 fopen_s(&fdst, argv[2], "rb");
705 err = fopen_s(&frst, argv[3], "wb");
706
707 while(fread(e_data, sizeof(unsigned char), b, fdst)==b){
708 RSA_private_decrypt(b, e_data, last_data, apriv, RSA_PKCS1_PADDING);
709 fwrite(last_data, sizeof(unsigned char), b, frst);
710 }
711 RSA_private_decrypt(RSA_size(apub), e_data, last_data, apriv, RSA_PKCS1_PADDING);
712 fwrite(last_data, sizeof(unsigned char),fileLen % b, frst);
713
714
715 free(last_data);
716 //free(e_data);
717 free(fsrcbuf);
718
719 RSA_free(apub);
720 RSA_free(apriv);
721
722 fclose(fdst);
723
724 fclose(frst);
725
726 fclose(fsrc);
727
728 } else {
729 printf("\n Usage mode: OpenSSLProj.exe f1.txt encryptf1.txt f9.txt");
730 return 1;
731 }
732
733 return 0;
734}
735
736
737CGENERATEKEY =======================================================================================
738
739#include <stdio.h>
740#include <malloc.h>
741#include <openssl/pem.h>
742#include <openssl/rsa.h>
743
744int main()
745{
746 RSA *rsaKP = NULL;
747
748 rsaKP = RSA_new();
749 rsaKP = RSA_generate_key(1024, 65535, NULL, NULL);
750
751 RSA_check_key(rsaKP);
752
753 FILE *fpPriv = NULL;
754 fopen_s(&fpPriv, "privKeyFile.pem","w+");
755 PEM_write_RSAPrivateKey(fpPriv, rsaKP, NULL, NULL, 0 ,0, NULL);
756 fclose(fpPriv);
757
758 FILE *fpPub = NULL;
759 fopen_s(&fpPub, "pubKeyFile.pem","w+");
760 PEM_write_RSAPublicKey(fpPub, rsaKP);
761 fclose(fpPub);
762
763 RSA_free(rsaKP);
764
765 printf("\n The RSA key pair generated! \n");
766
767 return 0;
768}
769
770
771CDIGITALSIGN =================================================================================
772
773#include <stdio.h>
774#include <malloc.h>
775#include <memory.h>
776
777#include <openssl/pem.h>
778#include <openssl/rsa.h>
779#include <openssl/md5.h>
780
781#define MESSAGE_CHUNK 128
782
783int main(int argc, char** argv)
784{
785 if(argc == 3) {
786 FILE* fsrc = NULL;
787 FILE* fdst = NULL;
788 errno_t err;
789 MD5_CTX ctx;
790
791 unsigned char finalDigest[MD5_DIGEST_LENGTH];
792 MD5_Init(&ctx);
793 unsigned char* fileBuffer = NULL;
794
795 err = fopen_s(&fsrc, argv[1], "rb");
796 fseek(fsrc, 0, SEEK_END);
797 int fileLen = ftell(fsrc);
798 fseek(fsrc, 0, SEEK_SET);
799
800 fileBuffer = (unsigned char*)malloc(fileLen);
801 fread(fileBuffer, sizeof(unsigned char), fileLen, fsrc);
802
803 unsigned char* tmpBuffer = fileBuffer;
804
805 while (fileLen > 0) {
806 if (fileLen > MESSAGE_CHUNK) {
807 MD5_Update(&ctx, tmpBuffer, MESSAGE_CHUNK);
808 }
809 else {
810 MD5_Update(&ctx, tmpBuffer, fileLen);
811 }
812 fileLen -= MESSAGE_CHUNK;
813 tmpBuffer += MESSAGE_CHUNK;
814 }
815
816 //MD5_Update(&ctx, fileBuffer, fileLen);
817
818 MD5_Final(finalDigest, &ctx);
819
820 for( int i=0; i<MD5_DIGEST_LENGTH; i++)
821 printf( "%2X ", finalDigest[i] );
822 printf("\n");
823
824
825 fclose(fsrc);
826
827 err = fopen_s(&fdst, argv[2], "wb");
828
829 RSA* apriv;
830 FILE* f;
831
832 unsigned char* buf = NULL;
833 unsigned char* e_data = NULL;
834 unsigned char* last_data = NULL;
835
836 apriv = RSA_new();
837
838 f = fopen("privKeyFile.pem","r");
839 apriv = PEM_read_RSAPrivateKey(f, NULL, NULL, NULL);
840 fclose(f);
841
842 buf = (unsigned char *) malloc(sizeof(finalDigest));
843 memcpy(buf, finalDigest, sizeof(finalDigest));
844
845 e_data = (unsigned char *) malloc(RSA_size(apriv)); //RSA_size => 1024 bits
846
847 RSA_private_encrypt(sizeof(finalDigest), buf, e_data, apriv, RSA_PKCS1_PADDING);
848
849 fwrite(e_data, RSA_size(apriv), 1, fdst);
850
851 fclose(fdst);
852
853 free(e_data);
854 free(buf);
855
856 RSA_free(apriv);
857 }
858 else {
859 printf("\n Usage mode: OpenSSLProj.exe fSrc.txt eSignFsrc.txt");
860 return 1;
861 }
862
863 return 0;
864}
865
866
867CDIGITALVERIFY =================================================================================
868
869#include <stdio.h>
870#include <malloc.h>
871#include <memory.h>
872#include <openssl/pem.h>
873#include <openssl/rsa.h>
874#include <openssl/md5.h>
875
876#define MESSAGE_CHUNK 128
877
878int main(int argc, char** argv)
879{
880 if(argc == 3) {
881 FILE* fsrc = NULL;
882 FILE* fsig = NULL;
883 errno_t err;
884 MD5_CTX ctx;
885
886 unsigned char finalDigest[MD5_DIGEST_LENGTH];
887 MD5_Init(&ctx);
888
889 unsigned char* fileBuffer = NULL;
890
891 err = fopen_s(&fsrc, argv[1], "rb");
892 fseek(fsrc, 0, SEEK_END);
893 int fileLen = ftell(fsrc);
894 fseek(fsrc, 0, SEEK_SET);
895
896 fileBuffer = (unsigned char*)malloc(fileLen);
897 fread(fileBuffer,sizeof(unsigned char), fileLen, fsrc);
898
899 unsigned char* tmpBuffer = fileBuffer;
900
901 while (fileLen > 0) {
902 if (fileLen > MESSAGE_CHUNK) {
903 MD5_Update(&ctx, tmpBuffer, MESSAGE_CHUNK);
904 }
905 else {
906 MD5_Update(&ctx, tmpBuffer, fileLen);
907 }
908 fileLen -= MESSAGE_CHUNK;
909 tmpBuffer += MESSAGE_CHUNK;
910 }
911
912 //MD5_Update(&ctx, fileBuffer, fileLen);
913
914 MD5_Final(finalDigest, &ctx);
915
916 for( int i=0; i<MD5_DIGEST_LENGTH; i++)
917 printf( "%2X ", finalDigest[i] );
918 printf("\n");
919
920 fclose(fsrc);
921
922 err = fopen_s(&fsig, argv[2], "rb");
923
924 RSA* apub;
925 FILE* f;
926 int ret;
927 unsigned char* buf = NULL;
928 unsigned char* last_data = NULL;
929
930 apub = RSA_new();
931
932 f = fopen("pubKeyFile.pem","r");
933 apub = PEM_read_RSAPublicKey(f, NULL, NULL, NULL);
934 fclose(f);
935
936 buf = (unsigned char *) malloc(RSA_size(apub));
937
938 fread(buf, RSA_size(apub), 1, fsig);
939
940 last_data = (unsigned char *) malloc(16);
941
942 RSA_public_decrypt(RSA_size(apub), buf, last_data, apub, RSA_PKCS1_PADDING);
943
944 fclose(fsig);
945
946 if ( memcmp(last_data, finalDigest, 16) == 0 )
947 printf("\n Signature OK!\n");
948 else
949 printf("\n Signature is wrong!\n");
950
951 free(last_data);
952 free(buf);
953
954 RSA_free(apub);
955
956 }
957 else {
958 printf("\n Usage mode: OpenSSLProj.exe fSrc.txt eSignFsrc.txt");
959 return 1;
960 }
961
962 return 0;
963}
964
965
966CGENERATEX509 =================================================================================
967
968#include <stdio.h>
969#include <malloc.h>
970#include <memory.h>
971
972#include <openssl/x509.h>
973#include <openssl/bio.h>
974#include <openssl/rsa.h>
975#include <openssl/evp.h>
976
977int main()
978{
979 X509* X509Cert = X509_new();
980
981 // set certificate version
982 X509_set_version(X509Cert, 0x2);
983
984 // set the certificate SN
985 ASN1_INTEGER_set(X509_get_serialNumber(X509Cert), 1);
986
987 // Issuer details
988 X509_NAME_add_entry_by_txt(X509_get_issuer_name(X509Cert), "C", MBSTRING_ASC, (unsigned char *)"RO", -1, -1, 0);
989 X509_NAME_add_entry_by_txt(X509_get_issuer_name(X509Cert), "O", MBSTRING_ASC, (unsigned char *)"ASE", -1, -1, 0);
990 X509_NAME_add_entry_by_txt(X509_get_issuer_name(X509Cert), "OU", MBSTRING_ASC, (unsigned char *)"ITC Security Master", -1, -1, 0);
991 X509_NAME_add_entry_by_txt(X509_get_issuer_name(X509Cert), "CN", MBSTRING_ASC, (unsigned char *)"Marius Popa", -1, -1, 0);
992
993 // Subject details
994 X509_NAME_add_entry_by_txt(X509_get_subject_name(X509Cert), "C", MBSTRING_ASC, (unsigned char *)"RO", -1, -1, 0);
995 X509_NAME_add_entry_by_txt(X509_get_subject_name(X509Cert), "O", MBSTRING_ASC, (unsigned char *)"ASE", -1, -1, 0);
996 X509_NAME_add_entry_by_txt(X509_get_subject_name(X509Cert), "OU", MBSTRING_ASC, (unsigned char *)"ITC Security Master", -1, -1, 0);
997 X509_NAME_add_entry_by_txt(X509_get_subject_name(X509Cert), "CN", MBSTRING_ASC, (unsigned char *)"Marius Popa", -1, -1, 0);
998
999 // Time in which the certificate acts (valid time)
1000 int DaysStart = 1;
1001 int DaysStop = 7;
1002 X509_gmtime_adj(X509_get_notBefore(X509Cert), (long)60*60*24*DaysStart);
1003 X509_gmtime_adj(X509_get_notAfter(X509Cert), (long)60*60*24*DaysStop);
1004
1005
1006 // RSA key pair generation
1007 EVP_PKEY* pkey = EVP_PKEY_new();
1008 RSA* rsa = RSA_generate_key(1024, 65535, NULL, NULL);
1009 EVP_PKEY_set1_RSA(pkey, rsa);
1010 X509_set_pubkey(X509Cert, pkey);
1011
1012 const EVP_MD* dgAlg = EVP_sha1();
1013
1014 X509_sign(X509Cert, pkey, dgAlg);
1015
1016 // Certification file
1017 BIO* out1 = BIO_new_file("SampleCert.cer", "w");
1018 i2d_X509_bio(out1, X509Cert);
1019 BIO_free(out1);
1020
1021 // Private key file
1022 BIO* out2 = BIO_new_file("SampleCert.key", "w");
1023 i2d_PrivateKey_bio(out2, pkey);
1024 BIO_free(out2);
1025
1026 RSA_free(rsa);
1027 EVP_PKEY_free(pkey);
1028 X509_free(X509Cert);
1029}