mirrored from https://www.bouncycastle.org/repositories/bc-csharp
-
Notifications
You must be signed in to change notification settings - Fork 602
Expand file tree
/
Copy pathPgpSecretKey.cs
More file actions
1247 lines (1074 loc) · 51.7 KB
/
Copy pathPgpSecretKey.cs
File metadata and controls
1247 lines (1074 loc) · 51.7 KB
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
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
using System;
using System.Collections.Generic;
using System.IO;
using Org.BouncyCastle.Asn1;
using Org.BouncyCastle.Asn1.Cryptlib;
using Org.BouncyCastle.Asn1.EdEC;
using Org.BouncyCastle.Asn1.Gnu;
using Org.BouncyCastle.Asn1.Pkcs;
using Org.BouncyCastle.Asn1.X509;
using Org.BouncyCastle.Asn1.X9;
using Org.BouncyCastle.Crypto;
using Org.BouncyCastle.Crypto.Parameters;
using Org.BouncyCastle.Crypto.Utilities;
using Org.BouncyCastle.Math;
using Org.BouncyCastle.Math.EC.Rfc8032;
using Org.BouncyCastle.Security;
using Org.BouncyCastle.Utilities;
namespace Org.BouncyCastle.Bcpg.OpenPgp
{
/// <summary>General class to handle a PGP secret key object.</summary>
public class PgpSecretKey
: PgpObject
{
private readonly SecretKeyPacket secret;
private readonly PgpPublicKey pub;
internal PgpSecretKey(SecretKeyPacket secret, PgpPublicKey pub)
{
this.secret = secret;
this.pub = pub;
}
internal PgpSecretKey(PgpPrivateKey privKey, PgpPublicKey pubKey, SymmetricKeyAlgorithmTag encAlgorithm,
byte[] rawPassPhrase, bool clearPassPhrase, bool useSha1, SecureRandom rand, bool isMasterKey)
{
BcpgObject secKey;
this.pub = pubKey;
switch (pubKey.Algorithm)
{
case PublicKeyAlgorithmTag.RsaEncrypt:
case PublicKeyAlgorithmTag.RsaSign:
case PublicKeyAlgorithmTag.RsaGeneral:
RsaPrivateCrtKeyParameters rsK = (RsaPrivateCrtKeyParameters) privKey.Key;
secKey = new RsaSecretBcpgKey(rsK.Exponent, rsK.P, rsK.Q);
break;
case PublicKeyAlgorithmTag.Dsa:
DsaPrivateKeyParameters dsK = (DsaPrivateKeyParameters) privKey.Key;
secKey = new DsaSecretBcpgKey(dsK.X);
break;
case PublicKeyAlgorithmTag.ECDH:
{
if (privKey.Key is ECPrivateKeyParameters ecdhK)
{
secKey = new ECSecretBcpgKey(ecdhK.D);
}
else
{
// The native format for X25519 private keys is little-endian
X25519PrivateKeyParameters xK = (X25519PrivateKeyParameters)privKey.Key;
#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER
secKey = new ECSecretBcpgKey(new BigInteger(1, xK.DataSpan, bigEndian: false));
#else
secKey = new ECSecretBcpgKey(new BigInteger(1, xK.GetEncoded(), bigEndian: false));
#endif
}
break;
}
case PublicKeyAlgorithmTag.ECDsa:
ECPrivateKeyParameters ecK = (ECPrivateKeyParameters)privKey.Key;
secKey = new ECSecretBcpgKey(ecK.D);
break;
case PublicKeyAlgorithmTag.EdDsa_Legacy:
{
if (privKey.Key is Ed25519PrivateKeyParameters ed25519K)
{
#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER
secKey = new EdSecretBcpgKey(new BigInteger(1, ed25519K.DataSpan));
#else
secKey = new EdSecretBcpgKey(new BigInteger(1, ed25519K.GetEncoded()));
#endif
}
else if (privKey.Key is Ed448PrivateKeyParameters ed448K)
{
#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER
secKey = new EdSecretBcpgKey(new BigInteger(1, ed448K.DataSpan));
#else
secKey = new EdSecretBcpgKey(new BigInteger(1, ed448K.GetEncoded()));
#endif
}
else
{
throw new PgpException("unknown EdDSA key class");
}
break;
}
case PublicKeyAlgorithmTag.ElGamalEncrypt:
case PublicKeyAlgorithmTag.ElGamalGeneral:
ElGamalPrivateKeyParameters esK = (ElGamalPrivateKeyParameters) privKey.Key;
secKey = new ElGamalSecretBcpgKey(esK.X);
break;
default:
throw new PgpException("unknown key class");
}
try
{
MemoryStream bOut = new MemoryStream();
BcpgOutputStream pOut = new BcpgOutputStream(bOut);
secKey.Encode(pOut);
byte[] keyData = bOut.ToArray();
byte[] checksumData = Checksum(useSha1, keyData, keyData.Length);
keyData = Arrays.Concatenate(keyData, checksumData);
if (encAlgorithm == SymmetricKeyAlgorithmTag.Null)
{
if (isMasterKey)
{
this.secret = new SecretKeyPacket(pub.publicPk, encAlgorithm, null, null, keyData);
}
else
{
this.secret = new SecretSubkeyPacket(pub.publicPk, encAlgorithm, null, null, keyData);
}
}
else
{
S2k s2k;
byte[] iv;
byte[] encData;
if (pub.Version >= 4)
{
encData = EncryptKeyDataV4(keyData, encAlgorithm, HashAlgorithmTag.Sha1, rawPassPhrase,
clearPassPhrase, rand, out s2k, out iv);
}
else
{
encData = EncryptKeyDataV3(keyData, encAlgorithm, rawPassPhrase, clearPassPhrase, rand, out s2k,
out iv);
}
int s2kUsage = useSha1 ? SecretKeyPacket.UsageSha1 : SecretKeyPacket.UsageChecksum;
if (isMasterKey)
{
this.secret = new SecretKeyPacket(pub.publicPk, encAlgorithm, s2kUsage, s2k, iv, encData);
}
else
{
this.secret = new SecretSubkeyPacket(pub.publicPk, encAlgorithm, s2kUsage, s2k, iv, encData);
}
}
}
catch (PgpException)
{
throw;
}
catch (Exception e)
{
throw new PgpException("Exception encrypting key", e);
}
}
/// <remarks>
/// Conversion of the passphrase characters to bytes is performed using Convert.ToByte(), which is
/// the historical behaviour of the library (1.7 and earlier).
/// </remarks>
public PgpSecretKey(int certificationLevel, PgpKeyPair keyPair, string id,
SymmetricKeyAlgorithmTag encAlgorithm, char[] passPhrase, bool useSha1,
PgpSignatureSubpacketVector hashedPackets, PgpSignatureSubpacketVector unhashedPackets,
SecureRandom rand)
: this(certificationLevel, keyPair, id, encAlgorithm, false, passPhrase, useSha1, hashedPackets, unhashedPackets, rand)
{
}
/// <remarks>
/// If utf8PassPhrase is true, conversion of the passphrase to bytes uses UTF8, otherwise the conversion
/// is performed using Convert.ToByte(), which is the historical behaviour of the library (1.7 and earlier).
/// </remarks>
public PgpSecretKey(int certificationLevel, PgpKeyPair keyPair, string id,
SymmetricKeyAlgorithmTag encAlgorithm, bool utf8PassPhrase, char[] passPhrase, bool useSha1,
PgpSignatureSubpacketVector hashedPackets, PgpSignatureSubpacketVector unhashedPackets, SecureRandom rand)
: this(certificationLevel, keyPair, id, encAlgorithm,
PgpUtilities.EncodePassPhrase(passPhrase, utf8PassPhrase), true, useSha1, hashedPackets,
unhashedPackets, rand)
{
}
/// <remarks>
/// Allows the caller to handle the encoding of the passphrase to bytes.
/// </remarks>
public PgpSecretKey(int certificationLevel, PgpKeyPair keyPair, string id,
SymmetricKeyAlgorithmTag encAlgorithm, byte[] rawPassPhrase, bool useSha1,
PgpSignatureSubpacketVector hashedPackets, PgpSignatureSubpacketVector unhashedPackets, SecureRandom rand)
: this(certificationLevel, keyPair, id, encAlgorithm, rawPassPhrase, false, useSha1, hashedPackets,
unhashedPackets, rand)
{
}
internal PgpSecretKey(int certificationLevel, PgpKeyPair keyPair, string id,
SymmetricKeyAlgorithmTag encAlgorithm, byte[] rawPassPhrase, bool clearPassPhrase, bool useSha1,
PgpSignatureSubpacketVector hashedPackets, PgpSignatureSubpacketVector unhashedPackets, SecureRandom rand)
: this(keyPair.PrivateKey,
CertifiedPublicKey(certificationLevel, keyPair, id, hashedPackets, unhashedPackets), encAlgorithm,
rawPassPhrase, clearPassPhrase, useSha1, rand, true)
{
}
/// <remarks>
/// Conversion of the passphrase characters to bytes is performed using Convert.ToByte(), which is
/// the historical behaviour of the library (1.7 and earlier).
/// </remarks>
public PgpSecretKey(int certificationLevel, PgpKeyPair keyPair, string id,
SymmetricKeyAlgorithmTag encAlgorithm, HashAlgorithmTag hashAlgorithm, char[] passPhrase,
bool useSha1, PgpSignatureSubpacketVector hashedPackets, PgpSignatureSubpacketVector unhashedPackets,
SecureRandom rand)
: this(certificationLevel, keyPair, id, encAlgorithm, hashAlgorithm, false, passPhrase, useSha1,
hashedPackets, unhashedPackets, rand)
{
}
/// <remarks>
/// If utf8PassPhrase is true, conversion of the passphrase to bytes uses UTF8, otherwise
/// the conversion is performed using Convert.ToByte(), which is the historical behaviour of the library (1.7
/// and earlier).
/// </remarks>
public PgpSecretKey(int certificationLevel, PgpKeyPair keyPair, string id,
SymmetricKeyAlgorithmTag encAlgorithm, HashAlgorithmTag hashAlgorithm, bool utf8PassPhrase,
char[] passPhrase, bool useSha1, PgpSignatureSubpacketVector hashedPackets,
PgpSignatureSubpacketVector unhashedPackets, SecureRandom rand)
: this(certificationLevel, keyPair, id, encAlgorithm, hashAlgorithm,
PgpUtilities.EncodePassPhrase(passPhrase, utf8PassPhrase), true, useSha1, hashedPackets,
unhashedPackets, rand)
{
}
/// <remarks>
/// Allows the caller to handle the encoding of the passphrase to bytes.
/// </remarks>
public PgpSecretKey(int certificationLevel, PgpKeyPair keyPair, string id,
SymmetricKeyAlgorithmTag encAlgorithm, HashAlgorithmTag hashAlgorithm, byte[] rawPassPhrase,
bool useSha1, PgpSignatureSubpacketVector hashedPackets, PgpSignatureSubpacketVector unhashedPackets,
SecureRandom rand)
: this(certificationLevel, keyPair, id, encAlgorithm, hashAlgorithm, rawPassPhrase, false, useSha1,
hashedPackets, unhashedPackets, rand)
{
}
internal PgpSecretKey(int certificationLevel, PgpKeyPair keyPair, string id,
SymmetricKeyAlgorithmTag encAlgorithm, HashAlgorithmTag hashAlgorithm, byte[] rawPassPhrase,
bool clearPassPhrase, bool useSha1, PgpSignatureSubpacketVector hashedPackets,
PgpSignatureSubpacketVector unhashedPackets, SecureRandom rand)
: this(keyPair.PrivateKey,
CertifiedPublicKey(certificationLevel, keyPair, id, hashedPackets, unhashedPackets, hashAlgorithm),
encAlgorithm, rawPassPhrase, clearPassPhrase, useSha1, rand, true)
{
}
private static PgpPublicKey CertifiedPublicKey(int certificationLevel, PgpKeyPair keyPair, string id,
PgpSignatureSubpacketVector hashedPackets, PgpSignatureSubpacketVector unhashedPackets)
{
PgpSignatureGenerator sGen;
try
{
sGen = new PgpSignatureGenerator(keyPair.PublicKey.Algorithm, HashAlgorithmTag.Sha1);
}
catch (Exception e)
{
throw new PgpException("Creating signature generator: " + e.Message, e);
}
//
// Generate the certification
//
sGen.InitSign(certificationLevel, keyPair.PrivateKey);
sGen.SetHashedSubpackets(hashedPackets);
sGen.SetUnhashedSubpackets(unhashedPackets);
try
{
PgpSignature certification = sGen.GenerateCertification(id, keyPair.PublicKey);
return PgpPublicKey.AddCertification(keyPair.PublicKey, id, certification);
}
catch (Exception e)
{
throw new PgpException("Exception doing certification: " + e.Message, e);
}
}
private static PgpPublicKey CertifiedPublicKey(int certificationLevel, PgpKeyPair keyPair, string id,
PgpSignatureSubpacketVector hashedPackets, PgpSignatureSubpacketVector unhashedPackets,
HashAlgorithmTag hashAlgorithm)
{
PgpSignatureGenerator sGen;
try
{
sGen = new PgpSignatureGenerator(keyPair.PublicKey.Algorithm, hashAlgorithm);
}
catch (Exception e)
{
throw new PgpException("Creating signature generator: " + e.Message, e);
}
//
// Generate the certification
//
sGen.InitSign(certificationLevel, keyPair.PrivateKey);
sGen.SetHashedSubpackets(hashedPackets);
sGen.SetUnhashedSubpackets(unhashedPackets);
try
{
PgpSignature certification = sGen.GenerateCertification(id, keyPair.PublicKey);
return PgpPublicKey.AddCertification(keyPair.PublicKey, id, certification);
}
catch (Exception e)
{
throw new PgpException("Exception doing certification: " + e.Message, e);
}
}
public PgpSecretKey(int certificationLevel, PublicKeyAlgorithmTag algorithm, AsymmetricKeyParameter pubKey,
AsymmetricKeyParameter privKey, DateTime time, string id, SymmetricKeyAlgorithmTag encAlgorithm,
char[] passPhrase, PgpSignatureSubpacketVector hashedPackets, PgpSignatureSubpacketVector unhashedPackets,
SecureRandom rand)
: this(certificationLevel, new PgpKeyPair(algorithm, pubKey, privKey, time), id, encAlgorithm, passPhrase,
false, hashedPackets, unhashedPackets, rand)
{
}
public PgpSecretKey(int certificationLevel, PublicKeyAlgorithmTag algorithm, AsymmetricKeyParameter pubKey,
AsymmetricKeyParameter privKey, DateTime time, string id, SymmetricKeyAlgorithmTag encAlgorithm,
char[] passPhrase, bool useSha1, PgpSignatureSubpacketVector hashedPackets,
PgpSignatureSubpacketVector unhashedPackets, SecureRandom rand)
: this(certificationLevel, new PgpKeyPair(algorithm, pubKey, privKey, time), id, encAlgorithm, passPhrase,
useSha1, hashedPackets, unhashedPackets, rand)
{
}
/// <summary>
/// Check if this key has an algorithm type that makes it suitable to use for signing.
/// </summary>
/// <remarks>
/// Note: with version 4 keys KeyFlags subpackets should also be considered when present for
/// determining the preferred use of the key.
/// </remarks>
/// <returns>
/// <c>true</c> if this key algorithm is suitable for use with signing.
/// </returns>
public bool IsSigningKey
{
get
{
switch (pub.Algorithm)
{
case PublicKeyAlgorithmTag.RsaGeneral:
case PublicKeyAlgorithmTag.RsaSign:
case PublicKeyAlgorithmTag.Dsa:
case PublicKeyAlgorithmTag.ECDsa:
case PublicKeyAlgorithmTag.EdDsa_Legacy:
case PublicKeyAlgorithmTag.ElGamalGeneral:
return true;
default:
return false;
}
}
}
/// <summary>True, if this is a master key.</summary>
public bool IsMasterKey => pub.IsMasterKey;
/// <summary>Detect if the Secret Key's Private Key is empty or not</summary>
public bool IsPrivateKeyEmpty
{
get
{
byte[] secKeyData = secret.GetSecretKeyData();
return secKeyData == null || secKeyData.Length < 1;
}
}
/// <summary>The algorithm the key is encrypted with.</summary>
public SymmetricKeyAlgorithmTag KeyEncryptionAlgorithm => secret.EncAlgorithm;
/// <summary>The Key ID of the public key associated with this key.</summary>
/// <remarks>
/// A Key ID is an 8-octet scalar. We convert it (big-endian) to an Int64 (UInt64 is not CLS compliant).
/// </remarks>
public long KeyId => pub.KeyId;
/// <summary>The fingerprint of the public key associated with this key.</summary>
public byte[] GetFingerprint() => pub.GetFingerprint();
/// <summary>Return the S2K usage associated with this key.</summary>
public int S2kUsage => secret.S2kUsage;
/// <summary>Return the S2K used to process this key.</summary>
public S2k S2k => secret.S2k;
/// <summary>The public key associated with this key.</summary>
public PgpPublicKey PublicKey => pub;
/// <summary>Allows enumeration of any user IDs associated with the key.</summary>
/// <returns>An <c>IEnumerable</c> of <c>string</c> objects.</returns>
public IEnumerable<string> UserIds => pub.GetUserIds();
/// <summary>Allows enumeration of any user attribute vectors associated with the key.</summary>
/// <returns>An <c>IEnumerable</c> of <c>string</c> objects.</returns>
public IEnumerable<PgpUserAttributeSubpacketVector> UserAttributes => pub.GetUserAttributes();
private byte[] ExtractKeyData(byte[] rawPassPhrase, bool clearPassPhrase)
{
byte[] encData = secret.GetSecretKeyData();
SymmetricKeyAlgorithmTag encAlgorithm = secret.EncAlgorithm;
if (encAlgorithm == SymmetricKeyAlgorithmTag.Null)
return encData;
// TODO Factor this block out as 'decryptData'
try
{
KeyParameter key = PgpUtilities.DoMakeKeyFromPassPhrase(encAlgorithm, secret.S2k, rawPassPhrase,
clearPassPhrase);
byte[] iv = secret.GetIV();
byte[] data;
if (secret.PublicKeyPacket.Version >= 4)
{
data = RecoverKeyData(encAlgorithm, "/CFB/NoPadding", key, iv, encData, 0, encData.Length);
bool useSha1 = secret.S2kUsage == SecretKeyPacket.UsageSha1;
byte[] check = Checksum(useSha1, data, useSha1 ? data.Length - 20 : data.Length - 2);
if (!Arrays.FixedTimeEquals(check.Length, check, 0, data, data.Length - check.Length))
throw new PgpException("Checksum mismatch in checksum of " + check.Length + " bytes");
}
else // version 2 or 3, RSA only.
{
data = new byte[encData.Length];
iv = Arrays.Clone(iv);
//
// read in the four numbers
//
int pos = 0;
for (int i = 0; i != 4; i++)
{
int encLen = ((((encData[pos] & 0xff) << 8) | (encData[pos + 1] & 0xff)) + 7) / 8;
data[pos] = encData[pos];
data[pos + 1] = encData[pos + 1];
pos += 2;
if (encLen > (encData.Length - pos))
throw new PgpException("out of range encLen found in encData");
byte[] tmp = RecoverKeyData(encAlgorithm, "/CFB/NoPadding", key, iv, encData, pos, encLen);
Array.Copy(tmp, 0, data, pos, encLen);
pos += encLen;
if (i != 3)
{
Array.Copy(encData, pos - iv.Length, iv, 0, iv.Length);
}
}
//
// verify and copy checksum
//
data[pos] = encData[pos];
data[pos + 1] = encData[pos + 1];
int cs = ((encData[pos] << 8) & 0xff00) | (encData[pos + 1] & 0xff);
int calcCs = 0;
for (int j = 0; j < pos; j++)
{
calcCs += data[j] & 0xff;
}
calcCs &= 0xffff;
if (calcCs != cs)
{
throw new PgpException("Checksum mismatch: passphrase wrong, expected "
+ cs.ToString("X")
+ " found " + calcCs.ToString("X"));
}
}
return data;
}
catch (PgpException)
{
throw;
}
catch (Exception e)
{
throw new PgpException("Exception decrypting key", e);
}
}
private static byte[] RecoverKeyData(SymmetricKeyAlgorithmTag encAlgorithm, string modeAndPadding,
KeyParameter key, byte[] iv, byte[] keyData, int keyOff, int keyLen)
{
IBufferedCipher c;
try
{
string cName = PgpUtilities.GetSymmetricCipherName(encAlgorithm);
c = CipherUtilities.GetCipher(cName + modeAndPadding);
}
catch (Exception e)
{
throw new PgpException("Exception creating cipher", e);
}
c.Init(forEncryption: false, new ParametersWithIV(key, iv));
return c.DoFinal(keyData, keyOff, keyLen);
}
/// <summary>Extract a <c>PgpPrivateKey</c> from this secret key's encrypted contents.</summary>
/// <remarks>
/// Conversion of the passphrase characters to bytes is performed using Convert.ToByte(), which is
/// the historical behaviour of the library (1.7 and earlier).
/// </remarks>
public PgpPrivateKey ExtractPrivateKey(char[] passPhrase) =>
DoExtractPrivateKey(PgpUtilities.EncodePassPhrase(passPhrase, utf8: false), clearPassPhrase: true);
/// <summary>Extract a <c>PgpPrivateKey</c> from this secret key's encrypted contents.</summary>
/// <remarks>
/// The passphrase is encoded to bytes using UTF8.
/// </remarks>
public PgpPrivateKey ExtractPrivateKeyUtf8(char[] passPhrase) =>
DoExtractPrivateKey(PgpUtilities.EncodePassPhrase(passPhrase, utf8: true), clearPassPhrase: true);
/// <summary>Extract a <c>PgpPrivateKey</c> from this secret key's encrypted contents.</summary>
/// <remarks>
/// Allows the caller to handle the encoding of the passphrase to bytes.
/// </remarks>
public PgpPrivateKey ExtractPrivateKeyRaw(byte[] rawPassPhrase) =>
DoExtractPrivateKey(rawPassPhrase, clearPassPhrase: false);
internal PgpPrivateKey DoExtractPrivateKey(byte[] rawPassPhrase, bool clearPassPhrase)
{
if (IsPrivateKeyEmpty)
return null;
PublicKeyPacket pubPk = secret.PublicKeyPacket;
try
{
byte[] data = ExtractKeyData(rawPassPhrase, clearPassPhrase);
BcpgInputStream bcpgIn = BcpgInputStream.Wrap(new MemoryStream(data, false));
AsymmetricKeyParameter privateKey;
switch (pubPk.Algorithm)
{
case PublicKeyAlgorithmTag.RsaEncrypt:
case PublicKeyAlgorithmTag.RsaGeneral:
case PublicKeyAlgorithmTag.RsaSign:
RsaPublicBcpgKey rsaPub = (RsaPublicBcpgKey)pubPk.Key;
RsaSecretBcpgKey rsaPriv = new RsaSecretBcpgKey(bcpgIn);
RsaPrivateCrtKeyParameters rsaPrivSpec = new RsaPrivateCrtKeyParameters(
rsaPriv.Modulus,
rsaPub.PublicExponent,
rsaPriv.PrivateExponent,
rsaPriv.PrimeP,
rsaPriv.PrimeQ,
rsaPriv.PrimeExponentP,
rsaPriv.PrimeExponentQ,
rsaPriv.CrtCoefficient);
privateKey = rsaPrivSpec;
break;
case PublicKeyAlgorithmTag.Dsa:
DsaPublicBcpgKey dsaPub = (DsaPublicBcpgKey)pubPk.Key;
DsaSecretBcpgKey dsaPriv = new DsaSecretBcpgKey(bcpgIn);
DsaParameters dsaParams = new DsaParameters(dsaPub.P, dsaPub.Q, dsaPub.G);
privateKey = new DsaPrivateKeyParameters(dsaPriv.X, dsaParams);
break;
case PublicKeyAlgorithmTag.ECDH:
{
ECDHPublicBcpgKey ecdhPub = (ECDHPublicBcpgKey)pubPk.Key;
ECSecretBcpgKey ecdhPriv = new ECSecretBcpgKey(bcpgIn);
var curveOid = ecdhPub.CurveOid;
if (EdECObjectIdentifiers.id_X25519.Equals(curveOid) ||
CryptlibObjectIdentifiers.curvey25519.Equals(curveOid))
{
// 'reverse' because the native format for X25519 private keys is little-endian
privateKey = PrivateKeyFactory.CreateKey(new PrivateKeyInfo(
new AlgorithmIdentifier(curveOid),
new DerOctetString(Arrays.ReverseInPlace(BigIntegers.AsUnsignedByteArray(ecdhPriv.X)))));
}
else if (EdECObjectIdentifiers.id_X448.Equals(curveOid))
{
// 'reverse' because the native format for X448 private keys is little-endian
privateKey = PrivateKeyFactory.CreateKey(new PrivateKeyInfo(
new AlgorithmIdentifier(curveOid),
new DerOctetString(Arrays.ReverseInPlace(BigIntegers.AsUnsignedByteArray(ecdhPriv.X)))));
}
else
{
privateKey = new ECPrivateKeyParameters("ECDH", ecdhPriv.X, ecdhPub.CurveOid);
}
break;
}
case PublicKeyAlgorithmTag.ECDsa:
{
ECPublicBcpgKey ecdsaPub = (ECPublicBcpgKey)pubPk.Key;
ECSecretBcpgKey ecdsaPriv = new ECSecretBcpgKey(bcpgIn);
privateKey = new ECPrivateKeyParameters("ECDSA", ecdsaPriv.X, ecdsaPub.CurveOid);
break;
}
case PublicKeyAlgorithmTag.EdDsa_Legacy:
{
EdDsaPublicBcpgKey eddsaPub = (EdDsaPublicBcpgKey)pubPk.Key;
EdSecretBcpgKey ecdsaPriv = new EdSecretBcpgKey(bcpgIn);
var curveOid = eddsaPub.CurveOid;
if (EdECObjectIdentifiers.id_Ed25519.Equals(curveOid) ||
GnuObjectIdentifiers.Ed25519.Equals(curveOid))
{
privateKey = PrivateKeyFactory.CreateKey(new PrivateKeyInfo(
new AlgorithmIdentifier(curveOid),
new DerOctetString(BigIntegers.AsUnsignedByteArray(Ed25519.SecretKeySize, ecdsaPriv.X))));
}
else if (EdECObjectIdentifiers.id_Ed448.Equals(curveOid))
{
privateKey = PrivateKeyFactory.CreateKey(new PrivateKeyInfo(
new AlgorithmIdentifier(curveOid),
new DerOctetString(BigIntegers.AsUnsignedByteArray(Ed448.SecretKeySize, ecdsaPriv.X))));
}
else
{
throw new InvalidOperationException();
}
break;
}
case PublicKeyAlgorithmTag.ElGamalEncrypt:
case PublicKeyAlgorithmTag.ElGamalGeneral:
ElGamalPublicBcpgKey elPub = (ElGamalPublicBcpgKey)pubPk.Key;
ElGamalSecretBcpgKey elPriv = new ElGamalSecretBcpgKey(bcpgIn);
ElGamalParameters elParams = new ElGamalParameters(elPub.P, elPub.G);
privateKey = new ElGamalPrivateKeyParameters(elPriv.X, elParams);
break;
default:
throw new PgpException("unknown public key algorithm encountered");
}
return new PgpPrivateKey(KeyId, pubPk, privateKey);
}
catch (PgpException)
{
throw;
}
catch (Exception e)
{
throw new PgpException("Exception constructing key", e);
}
}
private static byte[] Checksum(bool useSha1, byte[] bytes, int length)
{
if (useSha1)
{
try
{
var digest = PgpUtilities.CreateDigest(HashAlgorithmTag.Sha1);
return DigestUtilities.DoFinal(digest, bytes, 0, length);
}
catch (Exception e)
{
throw new PgpException("Can't find SHA-1", e);
}
}
else
{
int checkSum = 0;
for (int i = 0; i != length; i++)
{
checkSum += bytes[i];
}
return Pack.UInt16_To_BE((ushort)checkSum);
}
}
public byte[] GetEncoded()
{
MemoryStream bOut = new MemoryStream();
Encode(bOut);
return bOut.ToArray();
}
public void Encode(Stream outStr)
{
BcpgOutputStream bcpgOut = BcpgOutputStream.Wrap(outStr);
secret.Encode(bcpgOut);
pub.trustPk?.Encode(bcpgOut);
if (pub.subSigs == null) // is not a sub key
{
foreach (PgpSignature keySig in pub.keySigs)
{
keySig.Encode(bcpgOut);
}
for (int i = 0; i != pub.ids.Count; i++)
{
var pubID = pub.ids[i];
if (pubID is UserIdPacket id)
{
id.Encode(bcpgOut);
}
else if (pubID is PgpUserAttributeSubpacketVector v)
{
new UserAttributePacket(v.ToSubpacketArray()).Encode(bcpgOut);
}
else
{
throw new InvalidOperationException();
}
pub.idTrusts[i]?.Encode(bcpgOut);
foreach (PgpSignature sig in pub.idSigs[i])
{
sig.Encode(bcpgOut);
}
}
}
else
{
foreach (PgpSignature subSig in pub.subSigs)
{
subSig.Encode(bcpgOut);
}
}
// For clarity; really only required if using partial body lengths
bcpgOut.Finish();
}
/// <summary>
/// Return a copy of the passed in secret key, encrypted using a new password
/// and the passed in algorithm.
/// </summary>
/// <remarks>
/// Conversion of the passphrase characters to bytes is performed using Convert.ToByte(), which is
/// the historical behaviour of the library (1.7 and earlier).
/// </remarks>
/// <param name="key">The PgpSecretKey to be copied.</param>
/// <param name="oldPassPhrase">The current password for the key.</param>
/// <param name="newPassPhrase">The new password for the key.</param>
/// <param name="newEncAlgorithm">The algorithm to be used for the encryption.</param>
/// <param name="rand">Source of randomness.</param>
public static PgpSecretKey CopyWithNewPassword(PgpSecretKey key, char[] oldPassPhrase, char[] newPassPhrase,
SymmetricKeyAlgorithmTag newEncAlgorithm, SecureRandom rand)
{
var rawOldPassPhrase = PgpUtilities.EncodePassPhrase(oldPassPhrase, utf8: false);
var rawNewPassPhrase = PgpUtilities.EncodePassPhrase(newPassPhrase, utf8: false);
return DoCopyWithNewPassword(key, rawOldPassPhrase, rawNewPassPhrase, clearPassPhrase: true,
newEncAlgorithm, rand);
}
/// <summary>
/// Return a copy of the passed in secret key, encrypted using a new password
/// and the passed in algorithm.
/// </summary>
/// <remarks>
/// The passphrase is encoded to bytes using UTF8.
/// </remarks>
/// <param name="key">The PgpSecretKey to be copied.</param>
/// <param name="oldPassPhrase">The current password for the key.</param>
/// <param name="newPassPhrase">The new password for the key.</param>
/// <param name="newEncAlgorithm">The algorithm to be used for the encryption.</param>
/// <param name="rand">Source of randomness.</param>
public static PgpSecretKey CopyWithNewPasswordUtf8(PgpSecretKey key, char[] oldPassPhrase, char[] newPassPhrase,
SymmetricKeyAlgorithmTag newEncAlgorithm, SecureRandom rand)
{
var rawOldPassPhrase = PgpUtilities.EncodePassPhrase(oldPassPhrase, utf8: true);
var rawNewPassPhrase = PgpUtilities.EncodePassPhrase(newPassPhrase, utf8: true);
return DoCopyWithNewPassword(key, rawOldPassPhrase, rawNewPassPhrase, clearPassPhrase: true,
newEncAlgorithm, rand);
}
/// <summary>
/// Return a copy of the passed in secret key, encrypted using a new password
/// and the passed in algorithm.
/// </summary>
/// <remarks>
/// Allows the caller to handle the encoding of the passphrase to bytes.
/// </remarks>
/// <param name="key">The PgpSecretKey to be copied.</param>
/// <param name="rawOldPassPhrase">The current password for the key.</param>
/// <param name="rawNewPassPhrase">The new password for the key.</param>
/// <param name="newEncAlgorithm">The algorithm to be used for the encryption.</param>
/// <param name="rand">Source of randomness.</param>
public static PgpSecretKey CopyWithNewPasswordRaw(PgpSecretKey key, byte[] rawOldPassPhrase,
byte[] rawNewPassPhrase, SymmetricKeyAlgorithmTag newEncAlgorithm, SecureRandom rand)
{
return DoCopyWithNewPassword(key, rawOldPassPhrase, rawNewPassPhrase, clearPassPhrase: false,
newEncAlgorithm, rand);
}
internal static PgpSecretKey DoCopyWithNewPassword(PgpSecretKey key, byte[] rawOldPassPhrase,
byte[] rawNewPassPhrase, bool clearPassPhrase, SymmetricKeyAlgorithmTag newEncAlgorithm, SecureRandom rand)
{
if (key.IsPrivateKeyEmpty)
throw new PgpException("no private key in this SecretKey - public key present only.");
byte[] rawKeyData = key.ExtractKeyData(rawOldPassPhrase, clearPassPhrase);
int s2kUsage = key.secret.S2kUsage;
byte[] iv = null;
S2k s2k = null;
byte[] keyData;
PublicKeyPacket pubKeyPacket = key.secret.PublicKeyPacket;
if (newEncAlgorithm == SymmetricKeyAlgorithmTag.Null)
{
s2kUsage = SecretKeyPacket.UsageNone;
if (key.secret.S2kUsage == SecretKeyPacket.UsageSha1) // SHA-1 hash, need to rewrite Checksum
{
keyData = new byte[rawKeyData.Length - 18];
Array.Copy(rawKeyData, 0, keyData, 0, keyData.Length - 2);
byte[] check = Checksum(useSha1: false, keyData, keyData.Length - 2);
keyData[keyData.Length - 2] = check[0];
keyData[keyData.Length - 1] = check[1];
}
else
{
keyData = rawKeyData;
}
}
else
{
if (s2kUsage == SecretKeyPacket.UsageNone)
{
s2kUsage = SecretKeyPacket.UsageChecksum;
}
try
{
if (pubKeyPacket.Version >= 4)
{
keyData = EncryptKeyDataV4(rawKeyData, newEncAlgorithm, HashAlgorithmTag.Sha1, rawNewPassPhrase, clearPassPhrase, rand, out s2k, out iv);
}
else
{
keyData = EncryptKeyDataV3(rawKeyData, newEncAlgorithm, rawNewPassPhrase, clearPassPhrase, rand, out s2k, out iv);
}
}
catch (PgpException)
{
throw;
}
catch (Exception e)
{
throw new PgpException("Exception encrypting key", e);
}
}
SecretKeyPacket secret;
if (key.secret is SecretSubkeyPacket)
{
secret = new SecretSubkeyPacket(pubKeyPacket, newEncAlgorithm, s2kUsage, s2k, iv, keyData);
}
else
{
secret = new SecretKeyPacket(pubKeyPacket, newEncAlgorithm, s2kUsage, s2k, iv, keyData);
}
return new PgpSecretKey(secret, key.pub);
}
/// <summary>Replace the passed the public key on the passed in secret key.</summary>
/// <param name="secretKey">Secret key to change.</param>
/// <param name="publicKey">New public key.</param>
/// <returns>A new secret key.</returns>
/// <exception cref="ArgumentException">If KeyId's do not match.</exception>
public static PgpSecretKey ReplacePublicKey(PgpSecretKey secretKey, PgpPublicKey publicKey)
{
if (publicKey.KeyId != secretKey.KeyId)
throw new ArgumentException("KeyId's do not match");
return new PgpSecretKey(secretKey.secret, publicKey);
}
private static byte[] EncryptKeyDataV3(byte[] rawKeyData, SymmetricKeyAlgorithmTag encAlgorithm,
byte[] rawPassPhrase, bool clearPassPhrase, SecureRandom random, out S2k s2k, out byte[] iv)
{
// Version 2 or 3 - RSA Keys only
s2k = null;
iv = null;
KeyParameter encKey = PgpUtilities.DoMakeKeyFromPassPhrase(encAlgorithm, s2k, rawPassPhrase,
clearPassPhrase);
byte[] keyData = new byte[rawKeyData.Length];
//
// process 4 numbers
//
int pos = 0;
for (int i = 0; i != 4; i++)
{
int encLen = ((((rawKeyData[pos] & 0xff) << 8) | (rawKeyData[pos + 1] & 0xff)) + 7) / 8;
keyData[pos] = rawKeyData[pos];
keyData[pos + 1] = rawKeyData[pos + 1];
if (encLen > (rawKeyData.Length - (pos + 2)))
throw new PgpException("out of range encLen found in rawKeyData");
byte[] tmp;
if (i == 0)
{
tmp = EncryptData(encAlgorithm, encKey, rawKeyData, pos + 2, encLen, random, ref iv);
}
else
{
byte[] tmpIv = Arrays.CopyOfRange(keyData, pos - iv.Length, pos);
tmp = EncryptData(encAlgorithm, encKey, rawKeyData, pos + 2, encLen, random, ref tmpIv);
}
Array.Copy(tmp, 0, keyData, pos + 2, tmp.Length);
pos += 2 + encLen;
}
//
// copy in checksum.
//
keyData[pos] = rawKeyData[pos];
keyData[pos + 1] = rawKeyData[pos + 1];
return keyData;
}
private static byte[] EncryptKeyDataV4(byte[] rawKeyData, SymmetricKeyAlgorithmTag encAlgorithm,
HashAlgorithmTag hashAlgorithm, byte[] rawPassPhrase, bool clearPassPhrase, SecureRandom random,
out S2k s2k, out byte[] iv)
{
// TODO Configurable iterations?
s2k = S2k.GenerateSaltedAndIterated(random, hashAlgorithm, 0x60);
KeyParameter key = PgpUtilities.DoMakeKeyFromPassPhrase(encAlgorithm, s2k, rawPassPhrase, clearPassPhrase);
iv = null;
return EncryptData(encAlgorithm, key, rawKeyData, 0, rawKeyData.Length, random, ref iv);
}
private static byte[] EncryptData(SymmetricKeyAlgorithmTag encAlgorithm, KeyParameter key, byte[] data,
int dataOff, int dataLen, SecureRandom random, ref byte[] iv)
{
IBufferedCipher c;
try
{
string cName = PgpUtilities.GetSymmetricCipherName(encAlgorithm);
c = CipherUtilities.GetCipher(cName + "/CFB/NoPadding");
}
catch (Exception e)
{
throw new PgpException("Exception creating cipher", e);
}
if (iv == null)
{
iv = SecureRandom.GetNextBytes(random, c.GetBlockSize());
}
c.Init(true, new ParametersWithRandom(new ParametersWithIV(key, iv), random));
return c.DoFinal(data, dataOff, dataLen);
}
/// <summary>
/// Parse a secret key from one of the GPG S expression keys associating it with the passed in public key.
/// </summary>