summaryrefslogtreecommitdiffstats
path: root/libkpgp/kpgpbase5.cpp
blob: d7066cb914a7797be94cf2f4d1617fec37b85d21 (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
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
/*
    kpgpbase5.cpp

    Copyright (C) 2001,2002 the KPGP authors
    See file AUTHORS.kpgp for details

    This file is part of KPGP, the KDE PGP/GnuPG support library.

    KPGP is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation; either version 2 of the License, or
    (at your option) any later version.

    You should have received a copy of the GNU General Public License
    along with this program; if not, write to the Free Software Foundation,
    Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
 */

#ifdef HAVE_CONFIG_H
#include <config.h>
#endif

#include "kpgpbase.h"
#include "kpgp.h"

#include <string.h> /* strncmp */
#include <assert.h>

#include <tqregexp.h>
#include <tqdatetime.h>

#include <klocale.h>
#include <kprocess.h>
#include <kdebug.h>


namespace Kpgp {

Base5::Base5()
  : Base()
{
}


Base5::~Base5()
{
}


int
Base5::encrypt( Block& block, const KeyIDList& recipients )
{
  return encsign( block, recipients, 0 );
}


int
Base5::clearsign( Block& block, const char *passphrase )
{
  return encsign( block, KeyIDList(), passphrase );
}


int
Base5::encsign( Block& block, const KeyIDList& recipients,
                const char *passphrase )
{
  TQCString cmd;
  int exitStatus = 0;
  int index;
  // used to work around a bug in pgp5. pgp5 treats files
  // with non ascii chars (umlauts, etc...) as binary files, but
  // we want a clear signature
  bool signonly = false;

  if(!recipients.isEmpty() && passphrase != 0)
    cmd = "pgpe +batchmode -afts ";
  else if(!recipients.isEmpty())
    cmd = "pgpe +batchmode -aft ";
  else if(passphrase != 0)
  {
    cmd = "pgps +batchmode -abft ";
    signonly = true;
  }
  else
  {
    errMsg = i18n("Neither recipients nor passphrase specified.");
    return OK;
  }

  if(passphrase != 0)
    cmd += addUserId();

  if(!recipients.isEmpty())
  {
    if(Module::getKpgp()->encryptToSelf())
    {
      cmd += " -r 0x";
      cmd += Module::getKpgp()->user();
    }

    for( KeyIDList::ConstIterator it = recipients.begin();
         it != recipients.end(); ++it ) {
      cmd += " -r 0x";
      cmd += (*it);
    }
  }

  clear();
  input = block.text();

  if (signonly)
  {
    input.append("\n");
    input.replace(TQRegExp("[ \t]+\n"), "\n");   //strip trailing whitespace
  }
  //We have to do this otherwise it's all in vain

  exitStatus = run(cmd.data(), passphrase);
  block.setError( error );

  if(exitStatus != 0)
    status = ERROR;

  // now parse the returned info
  if(error.find("Cannot unlock private key") != -1)
  {
    errMsg = i18n("The passphrase you entered is invalid.");
    status |= ERROR;
    status |= BADPHRASE;
  }
//if(!ignoreUntrusted)
//{
    TQCString aStr;
    index = -1;
    while((index = error.find("WARNING: The above key",index+1)) != -1)
    {
      int index2 = error.find("But you previously",index);
      int index3 = error.find("WARNING: The above key",index+1);
      if(index2 == -1 || (index2 > index3 && index3 != -1))
      {
	// the key wasn't valid, no encryption to this person
	// extract the person
	index2 = error.find('\n',index);
	index3 = error.find('\n',index2+1);
	aStr += error.mid(index2+1, index3-index2-1);
	aStr += ", ";
      }
    }
    if(!aStr.isEmpty())
    {
      aStr.truncate(aStr.length()-2);
      if(error.find("No valid keys found") != -1)
	errMsg = i18n("The key(s) you want to encrypt your message "
		      "to are not trusted. No encryption done.");
      else
	errMsg = i18n("The following key(s) are not trusted:\n%1\n"
                      "Their owner(s) will not be able to decrypt the message.")
		     .arg(TQString(aStr));
      status |= ERROR;
      status |= BADKEYS;
    }
//}
  if((index = error.find("No encryption keys found for")) != -1)
  {
    index = error.find(':',index);
    int index2 = error.find('\n',index);

    errMsg = i18n("Missing encryption key(s) for:\n%1")
      .arg(TQString(error.mid(index,index2-index)));
//    errMsg = TQString("Missing encryption key(s) for: %1")
//      .arg(error.mid(index,index2-index));
    status |= ERROR;
    status |= MISSINGKEY;
  }

  if(signonly) {
    // dash-escape the input
    if (input[0] == '-')
      input = "- " + input;
    for ( int idx = 0 ; (idx = input.find("\n-", idx)) >= 0 ; idx += 4 )
      input.replace(idx, 2, "\n- -");

    output = "-----BEGIN PGP SIGNED MESSAGE-----\n\n" + input + "\n" + output;
  }

  block.setProcessedText( output );
  block.setStatus( status );
  return status;
}


int
Base5::decrypt( Block& block, const char *passphrase )
{
  int exitStatus = 0;

  clear();
  input = block.text();
  exitStatus = run("pgpv -f +batchmode=1", passphrase);
  if( !output.isEmpty() )
    block.setProcessedText( output );
  block.setError( error );

  if(exitStatus == -1) {
    errMsg = i18n("Error running PGP");
    status = RUN_ERR;
    block.setStatus( status );
    return status;
  }

  // lets parse the returned information.
  int index;

  index = error.find("Cannot decrypt message");
  if(index != -1)
  {
    //kdDebug(5100) << "message is encrypted" << endl;
    status |= ENCRYPTED;

    // ok. we have an encrypted message. Is the passphrase bad,
    // or do we not have the secret key?
    if(error.find("Need a pass phrase") != -1)
    {
      if(passphrase != 0)
      {
	errMsg = i18n("Bad passphrase; could not decrypt.");
	kdDebug(5100) << "Base: passphrase is bad" << endl;
	status |= BADPHRASE;
	status |= ERROR;
      }
    }
    else
    {
      // we don't have the secret key
      status |= NO_SEC_KEY;
      status |= ERROR;
      errMsg = i18n("You do not have the secret key needed to decrypt this message.");
      kdDebug(5100) << "Base: no secret key for this message" << endl;
    }
    // check for persons
#if 0
    // ##### FIXME: This information is anyway currently not used
    //       I'll change it to always determine the recipients.
    index = error.find("can only be decrypted by:");
    if(index != -1)
    {
      index = error.find('\n',index);
      int end = error.find("\n\n",index);

      mRecipients.clear();
      int index2;
      while( (index2 = error.find('\n',index+1)) <= end )
      {
	TQCString item = error.mid(index+1,index2-index-1);
	item.stripWhiteSpace();
	mRecipients.append(item);
	index = index2;
      }
    }
#endif
  }
  index = error.find("Good signature");
  if(index != -1)
  {
    //kdDebug(5100) << "good signature" << endl;
    status |= SIGNED;
    status |= GOODSIG;

    // get key ID of signer
    index = error.find("Key ID ", index) + 7;
    block.setSignatureKeyId( error.mid(index, 8) );

    // get signer
    index = error.find('"',index) + 1;
    int index2 = error.find('"', index);
    block.setSignatureUserId( error.mid(index, index2-index) );

    /// ### FIXME get signature date
    block.setSignatureDate( "" );
  }
  index = error.find("BAD signature");
  if(index != -1)
  {
    //kdDebug(5100) << "BAD signature" << endl;
    status |= SIGNED;
    status |= ERROR;

    // get key ID of signer
    index = error.find("Key ID ", index) + 7;
    block.setSignatureKeyId( error.mid(index, 8) );

    // get signer
    index = error.find('"',index) + 1;
    int index2 = error.find('"', index);
    block.setSignatureUserId( error.mid(index, index2-index) );

    /// ### FIXME get signature date
    block.setSignatureDate( "" );
  }
  index = error.find("Signature by unknown key");
  if(index != -1)
  {
    index = error.find("keyid: 0x",index) + 9;
    block.setSignatureKeyId( error.mid(index, 8) );
    block.setSignatureUserId( TQString() );
    // FIXME: not a very good solution...
    status |= SIGNED;
    status |= GOODSIG;

    /// ### FIXME get signature date
    block.setSignatureDate( "" );
  }

  //kdDebug(5100) << "status = " << status << endl;
  block.setStatus( status );
  return status;
}


Key*
Base5::readPublicKey( const KeyID& keyId, const bool readTrust, Key* key )
{
  int exitStatus = 0;

  status = 0;
  exitStatus = run( "pgpk -ll 0x" + keyId, 0, true );

  if(exitStatus != 0) {
    status = ERROR;
    return 0;
  }

  key = parseSingleKey( output, key );

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

  if( readTrust )
  {
    exitStatus = run( "pgpk -c 0x" + keyId, 0, true );

    if(exitStatus != 0) {
      status = ERROR;
      return 0;
    }

    parseTrustDataForKey( key, output );
  }

  return key;
}


KeyList
Base5::publicKeys( const TQStringList & patterns )
{
  int exitStatus = 0;

  TQCString cmd = "pgpk -ll";
  for ( TQStringList::ConstIterator it = patterns.begin();
        it != patterns.end(); ++it ) {
    cmd += " ";
    cmd += TDEProcess::quote( *it ).local8Bit();
  }
  status = 0;
  exitStatus = run( cmd, 0, true );

  if(exitStatus != 0) {
    status = ERROR;
    return KeyList();
  }

  // now we need to parse the output for public keys
  KeyList keys = parseKeyList( output, false );

  // sort the list of public keys
  keys.sort();

  return keys;
}


KeyList
Base5::secretKeys( const TQStringList & patterns )
{
  int exitStatus = 0;

  status = 0;
  TQCString cmd = "pgpk -ll";
  for ( TQStringList::ConstIterator it = patterns.begin();
        it != patterns.end(); ++it ) {
    cmd += " ";
    cmd += TDEProcess::quote( *it ).local8Bit();
  }
  status = 0;
  exitStatus = run( cmd, 0, true );

  if(exitStatus != 0) {
    status = ERROR;
    return KeyList();
  }

  // now we need to parse the output for secret keys
  KeyList keys = parseKeyList( output, true );

  // sort the list of public keys
  keys.sort();

  return keys;
}


TQCString Base5::getAsciiPublicKey(const KeyID& keyID)
{
  int exitStatus = 0;

  if (keyID.isEmpty())
    return TQCString();

  status = 0;
  exitStatus = run( "pgpk -xa 0x" + keyID, 0, true );

  if(exitStatus != 0) {
    status = ERROR;
    return TQCString();
  }

  return output;
}


int
Base5::signKey(const KeyID& keyID, const char *passphrase)
{
  TQCString cmd;
  int exitStatus = 0;

  if(passphrase == 0) return false;

  cmd = "pgpk -s -f +batchmode=1 0x";
  cmd += keyID;
  cmd += addUserId();

  status = 0;
  exitStatus = run(cmd.data(), passphrase);

  if (exitStatus != 0)
    status = ERROR;

  return status;
}

//-- private functions --------------------------------------------------------

Key*
Base5::parseKeyData( const TQCString& output, int& offset, Key* key /* = 0 */ )
// This function parses the data for a single key which is output by PGP 5
// with the following command line:
//   pgpk -ll
// It expects the key data to start at offset and returns the start of
// the next key's data in offset.
{
  if( ( strncmp( output.data() + offset, "pub", 3 ) != 0 ) &&
      ( strncmp( output.data() + offset, "sec", 3 ) != 0 ) )
  {
    kdDebug(5100) << "Unknown key type or corrupt key data.\n";
    return 0;
  }

  if( key == 0 )
    key = new Key();
  else
    key->clear();

  Subkey *subkey = 0;
  bool primaryKey = true;

  while( true )
  {
    int eol;

    // search the end of the current line
    eol = output.find( '\n', offset );
    if( ( eol == -1 ) || ( eol == offset ) )
      break;

    //kdDebug(5100) << "Parsing: " << output.mid(offset, eol-offset) << endl;

    if( !strncmp( output.data() + offset, "pub", 3 ) ||
        !strncmp( output.data() + offset, "sec", 3 ) ||
        !strncmp( output.data() + offset, "sub", 3 ) )
    { // line contains key data
      //kdDebug(5100)<<"Key data:\n";
      int pos, pos2;

      subkey = new Subkey( "", false );
      key->addSubkey( subkey );

      // Key Flags
      /* From the PGP 5 manual page for pgpk:
         Following this column is a single  character  which
         describes other attributes of the object:

         @  The object is disabled
         +  The object is axiomatically trusted  (i.e.,  it's
            your key)
      */
      switch( output[offset+3] )
      {
      case ' ': // nothing special
        break;
      case '@': // disabled key
        subkey->setDisabled( true );
        key->setDisabled( true );
        break;
      default: // all other flags are ignored
        //kdDebug(5100) << "Unknown key flag.\n";
        ;
      }

      // Key Length
      pos = offset + 4;
      while( output[pos] == ' ' )
        pos++;
      pos2 = output.find( ' ', pos );
      subkey->setKeyLength( output.mid( pos, pos2-pos ).toUInt() );
      //kdDebug(5100) << "Key Length: "<<subkey->keyLength()<<endl;

      // Key ID
      pos = pos2 + 1;
      while( output[pos] == ' ' )
        pos++;
      pos += 2; // skip the '0x'
      pos2 = output.find( ' ', pos );
      subkey->setKeyID( output.mid( pos, pos2-pos ) );
      //kdDebug(5100) << "Key ID: "<<subkey->keyID()<<endl;

      // Creation Date
      pos = pos2 + 1;
      while( output[pos] == ' ' )
        pos++;
      pos2 = output.find( ' ', pos );
      int year = output.mid( pos, 4 ).toInt();
      int month = output.mid( pos+5, 2 ).toInt();
      int day = output.mid( pos+8, 2 ).toInt();
      TQDateTime dt( TQDate( year, month, day ), TQTime( 00, 00 ) );
      TQDateTime epoch( TQDate( 1970, 01, 01 ), TQTime( 00, 00 ) );
      // The calculated creation date isn't exactly correct because TQDateTime
      // doesn't know anything about timezones and always assumes local time
      // although epoch is of course UTC. But as PGP 5 anyway doesn't print
      // the time this doesn't matter too much.
      subkey->setCreationDate( epoch.secsTo( dt ) );

      // Expiration Date
      // if the primary key has been revoked the expiration date is not printed
      if( primaryKey || !key->revoked() )
      {
        pos = pos2 + 1;
        while( output[pos] == ' ' )
          pos++;
        pos2 = output.find( ' ', pos );
        if( output[pos] == '-' )
        { // key doesn't expire
          subkey->setExpirationDate( -1 );
        }
        else if( !strncmp( output.data() + pos, "*REVOKED*", 9 ) )
        { // key has been revoked
          subkey->setRevoked( true );
          key->setRevoked( true );
        }
        else
        {
          int year = output.mid( pos, 4 ).toInt();
          int month = output.mid( pos+5, 2 ).toInt();
          int day = output.mid( pos+8, 2 ).toInt();
          TQDateTime dt( TQDate( year, month, day ), TQTime( 00, 00 ) );
          subkey->setCreationDate( epoch.secsTo( dt ) );
          // has the key already expired?
          if( TQDateTime::currentDateTime() >= dt )
          {
            subkey->setExpired( true );
            key->setExpired( true );
          }
        }
      }
      else if( key->revoked() )
        subkey->setRevoked( true );

      // Key algorithm (RSA, DSS, Diffie-Hellman)
      bool sign = false;
      bool encr = false;
      pos = pos2 + 1;
      while( output[pos] == ' ' )
        pos++;
      pos2 = output.find( ' ', pos );
      if( !strncmp( output.data() + pos, "RSA", 3 ) )
      {
        sign = true;
        encr = true;
      }
      else if( !strncmp( output.data() + pos, "DSS", 3 ) )
        sign = true;
      else if( !strncmp( output.data() + pos, "Diffie-Hellman", 14 ) )
        encr = true;
      else
        kdDebug(5100)<<"Unknown key algorithm\n";

      // set key capabilities of the subkey
      subkey->setCanEncrypt( encr );
      subkey->setCanSign( sign );
      subkey->setCanCertify( sign );

      if( primaryKey )
      {
        // Global key capabilities
        bool canSign = false;
        bool canEncr = false;
        pos = pos2 + 1;
        while( output[pos] == ' ' )
          pos++;
        pos2 = eol;
        if( !strncmp( output.data() + pos, "Sign & Encrypt", 14 ) )
        {
          canSign = true;
          canEncr = true;
        }
        else if( !strncmp( output.data() + pos, "Sign only", 9 ) )
          canSign = true;
        else if( !strncmp( output.data() + pos, "Encrypt only", 12 ) )
          canEncr = true;
        else
          kdDebug(5100)<<"Unknown key capability\n";

        // set the global key capabilities
        if( !key->expired() && !key->revoked() )
        {
          key->setCanEncrypt( canEncr );
          key->setCanSign( canSign );
          key->setCanCertify( canSign );
        }
        //kdDebug(5100)<<"Key capabilities: "<<(key->canEncrypt()?"E":"")<<(key->canSign()?"SC":"")<<endl;
        primaryKey = false;
      }
    }
    else if( !strncmp( output.data() + offset, "f16", 3 ) ||
             !strncmp( output.data() + offset, "f20", 3 ) )
    { // line contains a fingerprint
      /* Examples:
         f16    Fingerprint16 = DE 2A 77 08 78 64 7C 42  72 75 B1 A7 3E 42 3F 79
         f20    Fingerprint20 = 226F 4B63 6DA2 7389 91D1  2A49 D58A 3EC1 5214 181E

       */
      int pos = output.find( '=', offset+3 ) + 2;
      TQCString fingerprint = output.mid( pos, eol-pos );
      // remove white space from the fingerprint
      for ( int idx = 0 ; (idx = fingerprint.find(' ', idx)) >= 0 ; )
	fingerprint.replace( idx, 1, "" );
      assert( subkey != 0 );
      subkey->setFingerprint( fingerprint );
      //kdDebug(5100)<<"Fingerprint: "<<fingerprint<<endl;
    }
    else if( !strncmp( output.data() + offset, "uid", 3 ) )
    { // line contains a uid
      int pos = offset+5;
      TQCString uid = output.mid( pos, eol-pos );
      key->addUserID( uid );
      // displaying of uids which contain non-ASCII characters is broken in
      // PGP 5.0i; it shows these characters as \ooo and truncates the uid
      // because it doesn't take the 3 extra characters per non-ASCII char
      // into account. Example (with an UTF-8 encoded &ouml;):
      // uid  Ingo Kl\303\266cker <ingo.kloecker@epo
      // because of this and because we anyway don't know which charset was
      // used to encode the uid we don't try to decode it
    }
    else if ( !strncmp( output.data() + offset, "sig", 3 ) ||
              !strncmp( output.data() + offset, "SIG", 3 ) ||
              !strncmp( output.data() + offset, "ret", 3 ) )
    { // line contains a signature
      // SIG = sig with own key; ret = sig with revoked key
      // we ignore it for now
    }

    offset = eol + 1;
  }

  return key;
}


Key*
Base5::parseSingleKey( const TQCString& output, Key* key /* = 0 */ )
{
  int offset;

  // search start of header line
  if( !strncmp( output.data(), "Type Bits", 9 ) )
    offset = 0;
  else
  {
    offset = output.find( "\nType Bits" ) + 1;
    if( offset == 0 )
      return 0;
  }

  // key data begins in the next line
  offset = output.find( '\n', offset ) + 1;
  if( offset == -1 )
    return 0;

  key = parseKeyData( output, offset, key );

  //kdDebug(5100) << "finished parsing keys" << endl;

  return key;
}


KeyList
Base5::parseKeyList( const TQCString& output, bool onlySecretKeys )
{
  KeyList keys;
  Key *key = 0;
  int offset;

  // search start of header line
  if( !strncmp( output.data(), "Type Bits", 9 ) )
    offset = 0;
  else
  {
    offset = output.find( "\nType Bits" ) + 1;
    if( offset == 0 )
      return keys;
  }

  // key data begins in the next line
  offset = output.find( '\n', offset ) + 1;
  if( offset == -1 )
    return keys;

  do
  {
    key = parseKeyData( output, offset );
    if( key != 0 )
    {
      // if only secret keys should be read test if the key is secret
      if( !onlySecretKeys || !key->secret() )
        keys.append( key );
      // skip the blank line which separates the keys
      offset++;
    }
  }
  while( key != 0 );

  //kdDebug(5100) << "finished parsing keys" << endl;

  return keys;
}


void
Base5::parseTrustDataForKey( Key* key, const TQCString& str )
{
  if( ( key == 0 ) || str.isEmpty() )
    return;

  TQCString keyID = "0x" + key->primaryKeyID();
  UserIDList userIDs = key->userIDs();

  // search the start of the trust data
  int offset = str.find( "\n\n  KeyID" ) + 9;
  if( offset == -1 + 9 )
    return;

  offset = str.find( '\n', offset ) + 1;
  if( offset == -1 + 1 )
    return;

  bool ultimateTrust = false;
  if( !strncmp( str.data() + offset+13, "ultimate", 8 ) )
    ultimateTrust = true;

  while( true )
  { // loop over all trust information about this key

    int eol;

    // search the end of the current line
    if( ( eol = str.find( '\n', offset ) ) == -1 )
      break;

    if( str[offset+23] != ' ' )
    { // line contains a validity value for a user ID

      // determine the validity
      Validity validity = KPGP_VALIDITY_UNKNOWN;
      if( !strncmp( str.data() + offset+23, "complete", 8 ) )
        if( ultimateTrust )
          validity = KPGP_VALIDITY_ULTIMATE;
        else
          validity = KPGP_VALIDITY_FULL;
      else if( !strncmp( str.data() + offset+23, "marginal", 8 ) )
        validity = KPGP_VALIDITY_MARGINAL;
      else if( !strncmp( str.data() + offset+23, "invalid", 7 ) )
        validity = KPGP_VALIDITY_UNDEFINED;

      // determine the user ID
      int pos = offset + 33;
      TQString uid = str.mid( pos, eol-pos );

      // set the validity of the corresponding user ID
      for( UserIDListIterator it( userIDs ); it.current(); ++it )
        if( (*it)->text() == uid )
        {
          kdDebug(5100)<<"Setting the validity of "<<uid<<" to "<<validity<<endl;
          (*it)->setValidity( validity );
          break;
        }
    }

    offset = eol + 1;
  }
}


} // namespace Kpgp