File: rsa_nss.c

package info (click to toggle)
pidgin-encryption 3.1-1
  • links: PTS
  • area: main
  • in suites: squeeze, wheezy
  • size: 2,916 kB
  • ctags: 961
  • sloc: sh: 10,460; ansic: 8,821; makefile: 376; yacc: 318
file content (938 lines) | stat: -rwxr-xr-x 30,015 bytes parent folder | download | duplicates (2)
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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
/*             NSS keys for the Pidgin-Encryption plugin                  */
/*             Copyright (C) 2001 William Tompkins                        */

/* This plugin is free software, distributed under the GNU General Public */
/* License.                                                               */
/* Please see the file "COPYING" distributed with this source code        */
/* for more details                                                       */
/*                                                                        */
/*                                                                        */
/*    This software is distributed in the hope that it will be useful,    */
/*   but WITHOUT ANY WARRANTY; without even the implied warranty of       */
/*   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU    */
/*   General Public License for more details.                             */

/*   To compile and use:                                                  */
/*     See INSTALL file.                                                  */

#include "internal.h"

#include <gdk/gdk.h>
#include <gtk/gtk.h>
#include <gtk/gtkplug.h>

#include <debug.h>
#include <gtkdialogs.h>

#include "glib/gmain.h"

#include <string.h>
#include <assert.h>

#ifdef _WIN32
#include "win32dep.h"
#endif

#include "rsa_nss.h"

#include <nspr.h>
#include <nss.h>
#include <ssl.h>
#include <secmod.h>
#include <pk11func.h>
#include <keyhi.h>
#include <nssb64.h>


#include "nls.h"
#include "nss_mgf1.h"
#include "nss_oaep.h"
#include "nss_pss.h"
#include "cryptutil.h"
#include "keys.h"
#include "cryptproto.h"
#include "state_ui.h"

char* rsa_nss_proto_string="NSS 1.0";

crypt_proto* rsa_nss_proto;

/*Functions exported through crypt_proto structure */
static int              rsa_nss_encrypt(unsigned char**, unsigned char*, int, crypt_key*);
static int              rsa_nss_decrypt(unsigned char**, unsigned char*, int, crypt_key*);
static int              rsa_nss_sign(unsigned char**, unsigned char*, int, crypt_key*, crypt_key*);
static int              rsa_nss_auth(unsigned char**, unsigned char*, int, crypt_key*, const char* name);
static crypt_key*       rsa_nss_make_key_from_str(char *key_str);
static GString*         rsa_nss_key_to_gstr(crypt_key* inkey);
static char*            rsa_nss_parseable(char* key);
static crypt_key*       rsa_nss_parse_sent_key(char *key_str);
static GString*         rsa_nss_make_sendable_key(crypt_key* inkey, const char* name);
static gchar*           rsa_nss_make_key_id(crypt_key* inkey);

void                    rsa_nss_gen_key_pair(crypt_key **, crypt_key **,
                                             const char* name, int keysize);
static void             rsa_nss_free(crypt_key*);
static crypt_key*       rsa_nss_make_pub_from_priv(crypt_key* priv);
static int              rsa_nss_calc_unencrypted_size(struct crypt_key*, int);
static int              rsa_nss_calc_unsigned_size(struct crypt_key*, int);

/* internals */
void rsa_nss_test(crypt_key *pub, crypt_key *priv);


gboolean rsa_nss_init() {

   gboolean nss_loaded_ok = FALSE;

  	PurplePlugin *plugin = purple_plugins_find_with_name("NSS");

   if (plugin != NULL) {
      nss_loaded_ok = purple_plugin_is_loaded(plugin);
      if (!nss_loaded_ok) {
         nss_loaded_ok = purple_plugin_load(plugin);
      }
   }

   if (!nss_loaded_ok) {
      purple_debug(PURPLE_DEBUG_ERROR, "pidgin-encryption", "Initializing NSS without Purple support\n");
      /* Purple doesn't seem to have NSS support: try to load it ourselves: */
      PR_Init(PR_SYSTEM_THREAD, PR_PRIORITY_NORMAL, 1);
      NSS_NoDB_Init(NULL);
      
      /* TODO: Fix this so autoconf does the work trying to find this lib. */
      SECMOD_AddNewModule("Builtins",
#ifndef _WIN32
                          "libnssckbi.so",
#else
                          "nssckbi.dll",
#endif
                          0, 0);
      NSS_SetDomesticPolicy();

      /*       purple_debug(PURPLE_DEBUG_ERROR, "pidgin-encryption", _("Can't load the NSS plugin\n")); */
      /*       PE_error_window(_("Purple was not compiled with the NSS plugin enabled.  " */
      /*                       "Pidgin-Encryption requires the NSS plugin to function.")); */
      /*       return FALSE; */
   }

   rsa_nss_proto = g_malloc(sizeof(crypt_proto));
   crypt_proto_list = g_slist_prepend(crypt_proto_list, rsa_nss_proto);

   rsa_nss_proto->encrypt = rsa_nss_encrypt;
   rsa_nss_proto->decrypt = rsa_nss_decrypt;
   rsa_nss_proto->sign = rsa_nss_sign;
   rsa_nss_proto->auth = rsa_nss_auth;
      
   rsa_nss_proto->make_key_from_str = rsa_nss_make_key_from_str;
   rsa_nss_proto->key_to_gstr = rsa_nss_key_to_gstr;
   rsa_nss_proto->parseable = rsa_nss_parseable;
   rsa_nss_proto->parse_sent_key = rsa_nss_parse_sent_key;
   rsa_nss_proto->make_sendable_key = rsa_nss_make_sendable_key;
   rsa_nss_proto->make_key_id = rsa_nss_make_key_id;
   rsa_nss_proto->gen_key_pair = rsa_nss_gen_key_pair;
   rsa_nss_proto->free = rsa_nss_free;
   rsa_nss_proto->make_pub_from_priv = rsa_nss_make_pub_from_priv;
   rsa_nss_proto->calc_unencrypted_size = rsa_nss_calc_unencrypted_size;
   rsa_nss_proto->calc_unsigned_size = rsa_nss_calc_unsigned_size;
   rsa_nss_proto->name = rsa_nss_proto_string;

   return TRUE;
}

static void rsa_nss_free(crypt_key* key){
   if (key->store.rsa_nss.pub) {
      SECKEY_DestroyPublicKey(key->store.rsa_nss.pub);
      key->store.rsa_nss.pub = 0;
   }
   if (key->store.rsa_nss.priv) {
      SECKEY_DestroyPrivateKey(key->store.rsa_nss.priv);
      key->store.rsa_nss.priv = 0;
   }
}

static SECItem*
get_random_iv(CK_MECHANISM_TYPE mechType)
{
   int        iv_size = PK11_GetIVLength(mechType);
   SECItem   *iv;
   SECStatus  rv; 
   
   iv = PORT_ZNew(SECItem);
   g_assert(iv != 0);
   g_assert(iv_size != 0);

   iv->data = PORT_NewArray(unsigned char, iv_size);
   g_assert(iv->data != 0);
   iv->len = iv_size;
   rv = PK11_GenerateRandom(iv->data, iv->len);
   g_assert(rv == SECSuccess);

   return iv;
}

static void generate_digest(char* digest, SECKEYPublicKey* key) {
   SECItem *hash = PK11_MakeIDFromPubKey(&key->u.rsa.modulus);
   int i = 0, digestPos = 0;
   
   while (i < hash->len && digestPos < KEY_DIGEST_LENGTH) {
      sprintf(digest + digestPos, "%02x", hash->data[i]);
      ++i;
      digestPos += 2;
   }
   SECITEM_ZfreeItem (hash, PR_TRUE);
}

static void generate_fingerprint(char* print, SECKEYPublicKey* key) {
   SECItem *hash = PK11_MakeIDFromPubKey(&key->u.rsa.modulus);
   int i;
   
   for (i= 0; i < hash->len - 1; ++i) {
      sprintf(print + (3*i), "%02x:", hash->data[i]);
   }
   sprintf(print + 3 * (hash->len - 1), "%02x", hash->data[(hash->len - 1)]);
   SECITEM_ZfreeItem (hash, PR_TRUE);
}

static SECKEYPublicKey *
copy_public_rsa_key(SECKEYPublicKey *pubk) {
   SECKEYPublicKey *copyk;
   PRArenaPool *arena;
   SECStatus rv;
   
   arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE);
   g_assert(arena != NULL);
   
   copyk = (SECKEYPublicKey *) PORT_ArenaZAlloc (arena, sizeof (SECKEYPublicKey));
   g_assert(copyk != NULL);

   copyk->arena = arena;
   copyk->keyType = pubk->keyType;

   copyk->pkcs11Slot = NULL;   /* go get own reference */
   copyk->pkcs11ID = CK_INVALID_HANDLE;
   
   rv = SECITEM_CopyItem(arena, &copyk->u.rsa.modulus,
                         &pubk->u.rsa.modulus);
   g_assert(rv == SECSuccess);
   
   rv = SECITEM_CopyItem (arena, &copyk->u.rsa.publicExponent,
                          &pubk->u.rsa.publicExponent);
   g_assert(rv == SECSuccess);
   
   return copyk;
}

void rsa_nss_gen_key_pair(crypt_key **pub_key, crypt_key **priv_key,
                          const char* name, int keysize) {

   GtkWidget *status_window, *main_box, *label1, *label2;
   char labelText[1000];
   PK11RSAGenParams rsaParams;
   PK11SlotInfo *slot;

   CK_MECHANISM_TYPE multiType[2] = {CKM_RSA_PKCS_KEY_PAIR_GEN, CKM_DES_CBC_PAD};

   /* Create the widgets */

   PIDGIN_DIALOG(status_window);
   gtk_window_set_wmclass(GTK_WINDOW(status_window), "keygen", "Pidgin");
   gtk_widget_realize(status_window);
   gtk_container_set_border_width(GTK_CONTAINER(status_window), 10);
   gtk_widget_set_size_request(status_window, 350, 100);
   gtk_window_set_title(GTK_WINDOW(status_window), "Status");
   main_box = gtk_vbox_new(FALSE, 0);
   gtk_container_add(GTK_CONTAINER(status_window), main_box);
   gtk_widget_show(main_box);
   
   g_snprintf(labelText, sizeof(labelText), _("Generating RSA Key Pair for %s"),
              name);
   label1 = gtk_label_new (labelText);
   label2 = gtk_label_new (_("This may take a little bit..."));
   
   gtk_container_add (GTK_CONTAINER (main_box), label1);
   gtk_widget_show(label1);
   gtk_container_add (GTK_CONTAINER (main_box), label2);
   gtk_widget_show(label2);
   
   gtk_widget_show (status_window);

   // I don't understand: if I remove one of these
   // two loops, the contents of the status window don't
   // get drawn.  Hmm...
   while (gtk_events_pending()) {
      gtk_main_iteration_do(FALSE);
   }
   gtk_main_iteration();
   while (gtk_events_pending()) {
      gtk_main_iteration_do(FALSE);
   }
   
   *priv_key = g_malloc(sizeof(crypt_key));

   rsaParams.keySizeInBits = keysize;
   rsaParams.pe = 65537L;
  
   slot = PK11_GetBestSlotMultiple(multiType, 2, 0);
   
   /* Generate "session" (first FALSE), "not sensitive" (next FALSE) key */
   (*priv_key)->store.rsa_nss.priv = 
      PK11_GenerateKeyPair(slot, CKM_RSA_PKCS_KEY_PAIR_GEN, &rsaParams,
                           &(*priv_key)->store.rsa_nss.pub,
                           PR_FALSE, PR_FALSE, 0);

   if (!(*priv_key)->store.rsa_nss.priv) {
      purple_debug(PURPLE_DEBUG_ERROR, "pidgin-encryption",
                 _("Could not generate key.  NSS Error: %d\n"),
                 PORT_GetError());
      exit(0);
   }

   (*priv_key)->proto = rsa_nss_proto;
   g_snprintf((*priv_key)->length, sizeof((*priv_key)->length), "%d", keysize);

   generate_digest((*priv_key)->digest, (*priv_key)->store.rsa_nss.pub);
   generate_fingerprint((*priv_key)->fingerprint, (*priv_key)->store.rsa_nss.pub);

   (*pub_key) = rsa_nss_make_pub_from_priv(*priv_key);

   gtk_widget_hide(status_window);
   gtk_widget_destroy(status_window);
}

char* rsa_nss_parseable(char *key) {
   /* If the key is ours, return a pointer to the ':' after our token */
   /* otherwise return 0                                              */
   /* if we were more sophisticated, we could look for older versions */
   /* of our protocol here, and accept them too.                      */
   if (strncmp(rsa_nss_proto_string, key, strlen(rsa_nss_proto_string)) == 0) {
      return key + strlen(rsa_nss_proto_string);
   } else {
      return 0;
   }
}


static GString* append_priv_key_to_gstr(GString *str, SECKEYPrivateKey* priv) {

   /* for now, we hope that everyone can use DES3.  This is for wrapping   */
   /* private keys, which isn't actually secure at this point anyways      */
   /* (security provided by the OS: no one else can read/write the keyfile */
   const CK_MECHANISM_TYPE SymEncryptionType = CKM_DES3_CBC_PAD;

   PK11SlotInfo *symSlot;
   PK11SymKey *symKey;

   SECItem symKeyItem;  /* storage space for binary key import */
   unsigned char symKeyData[24] = {0}; 

   SECItem *iv = NULL;  /* IV for CBC encoding                 */

   SECItem exportedKey; /* storage space for exported key */
   unsigned char exportedKeyData[5000] = {0};

   char* tmpstr;
   int errCode;

   if (priv == 0) return str;

   /* Wrap key using a null symmetric key.  When/If we add password protection to
      keys, we can generate the symmetric key from a hashed password instead */
   symSlot = PK11_GetBestSlot(SymEncryptionType, NULL);
   g_assert(symSlot != 0);
   
   symKeyItem.data = &symKeyData[0];
   symKeyItem.len = sizeof(symKeyData);
   
   symKey  = PK11_ImportSymKey(symSlot, PK11_GetKeyGen(SymEncryptionType),
                               PK11_OriginUnwrap, CKA_WRAP, &symKeyItem, NULL);
   
   iv = get_random_iv(SymEncryptionType);
   
   exportedKey.len = sizeof(exportedKeyData);
   exportedKey.data = exportedKeyData;
   
   errCode = PK11_WrapPrivKey(symSlot, symKey, priv, SymEncryptionType, iv,
                              &exportedKey, NULL);

   g_assert(errCode == SECSuccess);

   
   g_string_append(str, ",");

   tmpstr = NSSBase64_EncodeItem(0, 0, 0, iv);
   g_string_append(str, tmpstr);
   PORT_Free(tmpstr);
   
   g_string_append(str, ",");
   
   tmpstr = NSSBase64_EncodeItem(0, 0, 0, &exportedKey);
   g_string_append(str, tmpstr);
   PORT_Free(tmpstr);
   
   g_string_append(str, ",");
   
   PK11_FreeSymKey(symKey);
   SECITEM_ZfreeItem(iv, PR_TRUE);

   /* The Base64 routine may have inserted lots of return chars into the string: */
   /*   take them out.                                                           */
   PE_strip_returns(str);

   return str;
}

static GString* append_pub_key_to_gstr(GString *str, SECKEYPublicKey* pub) {
   char *tmpstr;
   SECItem *exportedKey;
   
   if (pub == 0) return str;

   exportedKey = SECKEY_EncodeDERSubjectPublicKeyInfo(pub);
   //   exportedKey = PK11_DEREncodePublicKey(pub);
   
   tmpstr = NSSBase64_EncodeItem(0, 0, 0, exportedKey);
   g_string_append(str, tmpstr);

   PORT_Free(tmpstr);
   SECITEM_FreeItem (exportedKey, PR_TRUE);

   /* The Base64 routine may have inserted lots of return chars into the string: take them out. */
   PE_strip_returns(str);

   return str;
}


GString* rsa_nss_make_sendable_key(crypt_key* inkey, const char* name) {
   GString *outString = g_string_new("");

   gchar* nonce_str = PE_new_incoming_nonce(name);
   g_string_append(outString, nonce_str);

   purple_debug(PURPLE_DEBUG_INFO, "pidgin-encryption", "Sending Nonce with key: %s\n", nonce_str);
   
   g_free(nonce_str);

   g_string_append(outString, ",");
   
   append_pub_key_to_gstr(outString, inkey->store.rsa_nss.pub);

   return outString;
}

gchar* rsa_nss_make_key_id(crypt_key* inkey) {
   return PE_nonce_to_str(&inkey->store.rsa_nss.nonce);
}

crypt_key* rsa_nss_parse_sent_key(char *key_str) {
   gchar** split_key = g_strsplit(key_str, ",", 2);
   crypt_key* key;
   
   if ((split_key[0] == 0) || (split_key[1] == 0)) {
      purple_debug(PURPLE_DEBUG_ERROR, "pidgin-encryption", "Error parsing RSANSS nonce/key\n");
      g_strfreev(split_key);
      return 0;
   }
   
   key = rsa_nss_make_key_from_str(split_key[1]);

   if (key == 0) {
      g_strfreev(split_key);
      return 0;
   }

   PE_str_to_nonce(&key->store.rsa_nss.nonce, split_key[0]);
   purple_debug(PURPLE_DEBUG_INFO, "pidgin-encryption", "Received Nonce with key: %s\n", split_key[0]);

   g_strfreev(split_key);

   return key;
}

GString* rsa_nss_key_to_gstr(crypt_key* inkey) {
   GString *outString = g_string_new("");
   
   append_pub_key_to_gstr(outString, inkey->store.rsa_nss.pub);

   append_priv_key_to_gstr(outString, inkey->store.rsa_nss.priv);

   return outString;
}

crypt_key* rsa_nss_make_key_from_str(char *key_str){
   gchar **split_key;
   
   crypt_key* key = g_malloc(sizeof(crypt_key));

   /* For Private keys: */
   const CK_MECHANISM_TYPE SymEncryptionType = CKM_DES3_CBC_PAD;
   PK11SlotInfo *symSlot;
   PK11SymKey *symKey;
   SECItem *pubKeyValue;
   SECItem symKeyItem;  /* storage space for binary key import */
   unsigned char symKeyData[24] = {0};
   SECItem *iv = 0, *wrappedKey = 0, label;
   CK_ATTRIBUTE_TYPE attribs[3] = { CKA_SIGN, CKA_DECRYPT, CKA_SIGN_RECOVER };
   const int NumAttribs = 3;
   int cur_piece;

   CERTSubjectPublicKeyInfo *certPubKeyInfo;

   /* key_str looks like "KKKKK" or "KKKKK,NNNN,MMMM", where */
   /* KKKKK is the Base64 encoding of the public key, or              */
   /* NNNN is the Base64 encoding of the IV, and                      */
   /* MMMM is the Base64 encoding of the encrypted private key        */


   key->proto = rsa_nss_proto;
   
   split_key = g_strsplit(key_str, ",", 3);

   key->store.rsa_nss.pub = 0;
   key->store.rsa_nss.priv = 0;

   cur_piece = 0;

   // Check for public key part, and get it:

   if (split_key[cur_piece] == 0) {
      purple_debug(PURPLE_DEBUG_ERROR, "pidgin-encryption", "(%d) %s",
                 1, _("Error parsing RSANSS key\n"));
      g_free(key);
      g_strfreev(split_key);
      return 0;
   }

   wrappedKey = NSSBase64_DecodeBuffer(0, 0, split_key[cur_piece], strlen(split_key[cur_piece]));

   if (wrappedKey == 0) {
      purple_debug(PURPLE_DEBUG_ERROR, "pidgin-encryption", "(%d) %s",
                 2, _("Error parsing RSANSS key\n"));
      g_free(key);
      g_strfreev(split_key);
      return 0;
   }

   certPubKeyInfo = SECKEY_DecodeDERSubjectPublicKeyInfo(wrappedKey);

   SECITEM_FreeItem(wrappedKey, PR_TRUE);
   
   if (certPubKeyInfo == NULL) {
      purple_debug(PURPLE_DEBUG_ERROR, "pidgin-encryption", "(%d) %s",
                 3, _("Error parsing RSANSS key\n"));
      g_free(key);
      g_strfreev(split_key);
      return 0;
   }
   
   key->store.rsa_nss.pub = SECKEY_ExtractPublicKey(certPubKeyInfo);

   if (key->store.rsa_nss.pub == NULL) {
      purple_debug(PURPLE_DEBUG_ERROR, "pidgin-encryption", "(%d) %s",
                 4, _("Error parsing RSANSS key\n"));
      g_free(key);
      g_strfreev(split_key);
      return 0;
   }

   SECKEY_DestroySubjectPublicKeyInfo(certPubKeyInfo);

   generate_digest(key->digest, key->store.rsa_nss.pub);
   generate_fingerprint(key->fingerprint, key->store.rsa_nss.pub);

   g_snprintf(key->length, sizeof(key->length), "%d",
              8 * SECKEY_PublicKeyStrength(key->store.rsa_nss.pub));

   if (split_key[++cur_piece] == 0) {
      /* No private part, so return a public key: */
      g_strfreev(split_key);
      return key;
   }

   /* ------------------------------------------------------------------------ */
   /*  Extract Private key:                                                    */
   /*                                                                          */

   iv = NSSBase64_DecodeBuffer(0, 0, split_key[cur_piece],
                               strlen(split_key[cur_piece]));

   if (split_key[++cur_piece] == 0) {
      /* only part of a private key */
      purple_debug(PURPLE_DEBUG_ERROR, "pidgin-encryption", "(%d) %s",
                 5, _("Error parsing RSANSS key\n"));
      g_free(key);
      g_strfreev(split_key);
      /* SECItem_FreeItem will ignore null arguments, so just call it to clean up */
      SECITEM_ZfreeItem (iv, PR_TRUE);
      return 0;
   }

   wrappedKey =  NSSBase64_DecodeBuffer(0, 0, split_key[cur_piece],
                                        strlen(split_key[cur_piece]));

   if ((iv == 0) || (wrappedKey == 0)) {
      purple_debug(PURPLE_DEBUG_ERROR, "pidgin-encryption", "(%d) %s",
                 6, _("Error parsing RSANSS key\n"));
      g_free(key);
      g_strfreev(split_key);
      SECITEM_ZfreeItem (iv, PR_TRUE);
      SECITEM_ZfreeItem (wrappedKey, PR_TRUE);      
      return 0;
   }

   pubKeyValue = SECITEM_DupItem(&key->store.rsa_nss.pub->u.rsa.modulus);

   symSlot = PK11_GetBestSlot(SymEncryptionType, NULL);
   g_assert(symSlot != 0);
   
   symKeyItem.data = &symKeyData[0];
   symKeyItem.len = sizeof(symKeyData);
   
   symKey  = PK11_ImportSymKey(symSlot, PK11_GetKeyGen(SymEncryptionType),
                               PK11_OriginUnwrap, CKA_WRAP, &symKeyItem, NULL);

   if (!symKey) {
      purple_debug(PURPLE_DEBUG_ERROR, "pidgin-encryption", "(%d) %s",
                 7, _("Error parsing RSANSS key\n"));
      g_strfreev(split_key);

      SECKEY_DestroyPublicKey(key->store.rsa_nss.pub);
      SECITEM_ZfreeItem (iv, PR_TRUE);
      SECITEM_ZfreeItem (pubKeyValue, PR_TRUE);
      g_free(key);
      return 0;
   }

   label.data = NULL; label.len = 0;

   key->store.rsa_nss.priv =
      PK11_UnwrapPrivKey(symSlot, symKey, SymEncryptionType, iv,
                         wrappedKey, &label, pubKeyValue,
                         PR_FALSE, PR_FALSE, CKK_RSA, attribs, NumAttribs, 0);
   
   SECITEM_ZfreeItem (iv, PR_TRUE);
   SECITEM_ZfreeItem (wrappedKey, PR_TRUE);
   SECITEM_FreeItem (pubKeyValue, PR_TRUE);
   PK11_FreeSymKey(symKey);

   if (key->store.rsa_nss.priv == 0) {
      purple_debug(PURPLE_DEBUG_ERROR, "pidgin-encryption", "(%d) %s",
                 8, _("Error parsing RSANSS key\n"));
      g_strfreev(split_key);

      SECKEY_DestroyPublicKey(key->store.rsa_nss.pub);
      g_free(key);
      return 0;
   }
   /* should sanity check public/private pair */

   g_strfreev(split_key);

   return key;
}   


crypt_key* rsa_nss_make_pub_from_priv(crypt_key* priv_key) {
   crypt_key* pub_key = g_malloc(sizeof(crypt_key));
   
   pub_key->proto = rsa_nss_proto;
   strcpy(pub_key->length, priv_key->length);
   strncpy(pub_key->digest, priv_key->digest, KEY_DIGEST_LENGTH);
   strncpy(pub_key->fingerprint, priv_key->fingerprint, KEY_FINGERPRINT_LENGTH);

   pub_key->store.rsa_nss.pub = copy_public_rsa_key(priv_key->store.rsa_nss.pub);
   pub_key->store.rsa_nss.priv = 0;
   
   return pub_key;
}

int rsa_nss_encrypt(unsigned char** encrypted, unsigned char* msg, int msg_len,
                    crypt_key* pub_key){

   SECKEYPublicKey * key = pub_key->store.rsa_nss.pub;

   int modulus_len = SECKEY_PublicKeyStrength(key);

   int unpadded_block_len = oaep_max_unpadded_len(modulus_len);

   int num_blocks = ((msg_len - 1) / unpadded_block_len) + 1;

   unsigned char* msg_cur, *encrypt_cur;

   int msg_block_len;

   unsigned char *padded_block = g_malloc(modulus_len);

   int ret;
   SECStatus rv;

   //   purple_debug(PURPLE_DEBUG_INFO, "pidgin-encryption", "Starting Encrypt\n");
   
   *encrypted = g_malloc(num_blocks * modulus_len);

   msg_cur = msg;
   encrypt_cur = *encrypted;
   
   while (msg_cur < msg + msg_len) {

      msg_block_len = unpadded_block_len;
      if (msg_cur + msg_block_len > msg + msg_len) {
         msg_block_len = msg + msg_len - msg_cur;
      }

      ret = oaep_pad_block(padded_block, modulus_len, msg_cur, msg_block_len);
      if (!ret) {
         g_free(padded_block);
         g_free(*encrypted);
         *encrypted = 0;
         return 0;
      }
      rv = PK11_PubEncryptRaw(key, encrypt_cur, padded_block,
                              modulus_len, 0);
      if (rv != SECSuccess) {
         g_free(padded_block);
         g_free(*encrypted);
         *encrypted = 0;
         return 0;
      }

      msg_cur += msg_block_len;
      encrypt_cur += modulus_len;
   }

   g_free(padded_block);
   //   purple_debug(PURPLE_DEBUG_INFO, "pidgin-encryption", "Ending Encrypt\n");

   return (encrypt_cur - *encrypted);
}

int rsa_nss_decrypt(unsigned char** decrypted, unsigned char* msg, int msg_len,
                    crypt_key* priv_key){
   
   SECKEYPrivateKey * key = priv_key->store.rsa_nss.priv;

   int modulus_len = SECKEY_PublicKeyStrength(priv_key->store.rsa_nss.pub);

   int unpadded_block_len = oaep_max_unpadded_len(modulus_len);

   int num_blocks = msg_len / modulus_len;

   unsigned char* msg_cur, *decrypt_cur;
   
   unsigned int decrypt_block_size;

   unsigned char *padded_block = g_malloc(modulus_len);

   int ret;
   SECStatus rv;
   
   purple_debug(PURPLE_DEBUG_INFO, "pidgin-encryption", "Starting Decrypt\n");

   *decrypted = g_malloc(num_blocks * unpadded_block_len + 1);

   msg_cur = msg;
   decrypt_cur = *decrypted;
   
   if (num_blocks * modulus_len != msg_len) {  /* not an even number of blocks */
      purple_debug(PURPLE_DEBUG_ERROR, "pidgin-encryption", "Not a multiple of block len: %d %d %d\n",
                 num_blocks, modulus_len, msg_len);
      g_free(padded_block);
      g_free(*decrypted);
      *decrypted = 0;
      return 0;
   }

   while (msg_cur < msg + msg_len) {

      rv = PK11_PubDecryptRaw(key, padded_block, &decrypt_block_size, modulus_len,
                              msg_cur, modulus_len);

      if (rv != SECSuccess) {
         purple_debug(PURPLE_DEBUG_ERROR, "pidgin-encryption", "PubDecryptRaw failed %d\n", rv);
         g_free(padded_block);
         g_free(*decrypted);
         *decrypted = 0;
         return 0;
      }

      g_assert(decrypt_block_size == modulus_len); /* for now. Don't understand how */
                                                   /* this could not be true        */

      ret = oaep_unpad_block(decrypt_cur, &decrypt_block_size, padded_block, modulus_len);
      if (!ret) {
         purple_debug(PURPLE_DEBUG_ERROR, "pidgin-encryption", "OAEP unpadding failed\n");
         g_free(padded_block);
         g_free(*decrypted);
         *decrypted = 0;
         return 0;
      }

      msg_cur += modulus_len;
      decrypt_cur += decrypt_block_size;
   }

   g_free(padded_block);

   /* Null terminate what just came out, in case someone tries to use it as a string */
   *decrypt_cur = 0;

   //   purple_debug(PURPLE_DEBUG_INFO, "pidgin-encryption", "Ending Decrypt\n");
   return (decrypt_cur - *decrypted);
}

int rsa_nss_sign(unsigned char** signed_msg, unsigned char* msg, int msg_len,
                 crypt_key* priv_key, crypt_key* pub_key) {

   SECKEYPrivateKey * key = priv_key->store.rsa_nss.priv;
   int modulus_len = SECKEY_PublicKeyStrength(priv_key->store.rsa_nss.pub);
   unsigned char *sig_pos, *tmp_sig;

   SECStatus rv;
   unsigned int out_block_size;

   const int salt_len = 20;

   gchar *nonce_str = PE_nonce_to_str(&pub_key->store.rsa_nss.nonce);
   int nonce_len = strlen(nonce_str);
   
   PE_incr_nonce(&pub_key->store.rsa_nss.nonce);

   *signed_msg = g_malloc(msg_len + modulus_len + nonce_len + 1);
   tmp_sig = g_malloc(modulus_len);
   memcpy(*signed_msg, nonce_str, nonce_len);
   (*signed_msg)[nonce_len]=':';

   memcpy(*signed_msg + nonce_len + 1, msg, msg_len);
   sig_pos = *signed_msg + msg_len + nonce_len + 1 ;

   g_free(nonce_str);
   
   pss_generate_sig(tmp_sig, modulus_len, *signed_msg, msg_len + nonce_len + 1, salt_len);

   rv = PK11_PubDecryptRaw(key, sig_pos, &out_block_size, modulus_len,
                           tmp_sig, modulus_len);

   if (rv != SECSuccess) {
      purple_debug(PURPLE_DEBUG_ERROR, "pidgin-encryption", "PK11_PubDecryptRaw Failed\n");
      g_free(*signed_msg);
      g_free(tmp_sig);
      *signed_msg = 0;
      return 0;
   }

   g_assert(out_block_size == modulus_len);  /* dunno why they yield out_block_size */

   g_free(tmp_sig);
   
   return msg_len + nonce_len + 1 + modulus_len;
}

// Returns length of authed string, or 0 if not authenticated
// g_malloc's space for the authed string, and null terminates the result
// If returning zero, may return a message ID (nonce) as the authed string

int rsa_nss_auth(unsigned char** authed, unsigned char* msg, int msg_len,
                 crypt_key* pub_key, const char* name) {
   
   SECKEYPublicKey * key = pub_key->store.rsa_nss.pub;
   int modulus_len = SECKEY_PublicKeyStrength(key);
   unsigned char *tmp_sig;

   SECStatus rv;
   int verified;

   gchar *nonce_msg, **nonce_msg_split;

   purple_debug(PURPLE_DEBUG_INFO, "pidgin-encryption", "Starting Auth\n");

   *authed = 0;

   if (msg_len < modulus_len) {
      purple_debug(PURPLE_DEBUG_ERROR, "pidgin-encryption", "Bad msg_len in Auth\n");
      return 0;
   }

   tmp_sig = g_malloc(modulus_len);

   rv = PK11_PubEncryptRaw(key, tmp_sig, msg + msg_len - modulus_len,
                           modulus_len, 0);

   if (rv != SECSuccess) {
      purple_debug(PURPLE_DEBUG_ERROR, "pidgin-encryption", "PK11_PubEncryptRaw Failed\n");
      g_free(tmp_sig);
      return 0;
   }

   /*   purple_debug(PURPLE_DEBUG_INFO, "pidgin-encryption", "Auth 2\n"); */

   verified = pss_check_sig(tmp_sig, modulus_len, msg, msg_len - modulus_len);

   g_free(tmp_sig);
   
   if (!verified) {
      purple_debug(PURPLE_DEBUG_ERROR, "pidgin-encryption", _("Bad signature on message (len %d, mod %d)\n"),
                 msg_len, modulus_len);
      return 0;
   }

   /*    purple_debug(PURPLE_DEBUG_INFO, "pidgin-encryption", "Auth 3\n"); */

   nonce_msg = g_strndup((char*)msg, msg_len - modulus_len);
   nonce_msg_split = g_strsplit(nonce_msg, ":", 2);
   g_free(nonce_msg);

   /*    purple_debug(PURPLE_DEBUG_INFO, "pidgin-encryption", "Auth 4\n"); */

   if ((nonce_msg_split[0] == 0) || (nonce_msg_split[1] == 0)) {
      purple_debug(PURPLE_DEBUG_ERROR, "pidgin-encryption", "No Nonce in message\n");
      g_strfreev(nonce_msg_split);
      return 0;
   }         
   
   /*    purple_debug(PURPLE_DEBUG_INFO, "pidgin-encryption", "Auth 5\n"); */

   if (!PE_check_incoming_nonce(name, nonce_msg_split[0])) {
      purple_debug(PURPLE_DEBUG_ERROR, "pidgin-encryption", "Bad Nonce in message\n");
      /* a hack: return the nonce that was sent, to send to other side, to cause */
      /*         message to be re-sent */
      *authed = (unsigned char*) g_strdup(nonce_msg_split[0]);
      
      g_strfreev(nonce_msg_split);
      return 0;
   }
   
   /*    purple_debug(PURPLE_DEBUG_INFO, "pidgin-encryption", "Auth 6\n"); */

   *authed = (unsigned char*)nonce_msg_split[1];
   g_free(nonce_msg_split[0]);
   g_free(nonce_msg_split);

   purple_debug(PURPLE_DEBUG_INFO, "pidgin-encryption", "Auth End\n");

   return strlen((char*)*authed);
}

int rsa_nss_calc_unencrypted_size(struct crypt_key* key, int insize) {
   int modulus_len = SECKEY_PublicKeyStrength(key->store.rsa_nss.pub);
   int unpadded_block_len = oaep_max_unpadded_len(modulus_len);

   int num_blocks = insize / modulus_len; /* floor: max number of blocks that could fit */

   return num_blocks * unpadded_block_len;
}

int rsa_nss_calc_unsigned_size(struct crypt_key* key, int insize) {
   int modulus_len, nonce_len;
   
   purple_debug(PURPLE_DEBUG_INFO, "pidgin-encryption", "calc_unsigned_size\n");

   modulus_len = SECKEY_PublicKeyStrength(key->store.rsa_nss.pub);
   nonce_len = PE_nonce_str_len();

   purple_debug(PURPLE_DEBUG_INFO, "pidgin-encryption", "modulus_len:%d:%d\n", modulus_len, nonce_len);
   
   if (insize < modulus_len + nonce_len) return 0;
   return insize - modulus_len - nonce_len - 1;  /* -1 from ":" after nonce */
}