-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathxmlsec.py
3572 lines (3497 loc) · 143 KB
/
xmlsec.py
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
#! /usr/bin/env python
# -*- coding: utf-8 -*-
#
# $Id$
#
# PyXMLSec - Python bindings for XML Security Library (XMLSec)
#
# Copyright (C) 2003-2013 Easter-eggs, Valery Febvre
# http://pyxmlsec.labs.libre-entreprise.org
#
# Author: Valery Febvre <[email protected]>
#
# This is free software; see COPYING file in the source
# distribution for preciese wording.
"""
PyXMLSec - Python bindings for XML Security library (XMLSec)
Copyright (C) 2003-2013 Easter-eggs, Valery Febvre
Author : Valéry Febvre <[email protected]>
Homepage : http://pyxmlsec.labs.libre-entreprise.org
PyXMLSec was originally developped for Glasnost project.
http://glasnost.entrouvert.org
In 2003, the development of Glasnost is supported by the French Department of
Economy, Finance and Industry, as part of the UCIP - Collective Use of Internet
by SMEs - programme.
"""
__docformat__ = "plaintext en"
import libxml2
import xmlsecmod
from xmlsec_strings import *
class Error(Exception):
def __init__(self, msg):
self.msg = msg
def __str__(self):
return repr(self.msg)
###############################################################################
# app.h
###############################################################################
# Crypto Init/Shutdown
def cryptoInit():
"""
XMLSec library specific crypto engine initialization.
Returns : 0 on success or a negative value otherwise.
"""
return xmlsecmod.cryptoInit()
def cryptoShutdown():
"""
XMLSec library specific crypto engine shutdown.
Returns : 0 on success or a negative value otherwise.
"""
return xmlsecmod.cryptoShutdown()
def cryptoKeysMngrInit(mngr):
"""
Adds crypto specific key data stores in keys manager.
mngr : the keys manager.
Returns : 0 on success or a negative value otherwise.
"""
return xmlsecmod.cryptoKeysMngrInit(mngr)
# Key data ids methods
def keyDataAesId():
"""
The AES key data id.
Returns : AES key data id or None if an error occurs (xmlsec-crypto library
is not loaded or the AES key data id is not implemented).
"""
return KeyDataId(_obj=xmlsecmod.keyDataAesId())
def keyDataDesId():
"""
The DES key data id.
Returns : DES key data id or None if an error occurs (xmlsec-crypto library
is not loaded or the DES key data id is not implemented).
"""
return KeyDataId(_obj=xmlsecmod.keyDataDesId())
def keyDataDsaId():
"""
The DSA key data id.
Returns : DSA key data id or None if an error occurs (xmlsec-crypto library
is not loaded or the DSA key data id is not implemented).
"""
return KeyDataId(_obj=xmlsecmod.keyDataDsaId())
def keyDataHmacId():
"""
The HMAC key data id.
Returns : HMAC key data id or None if an error occurs (xmlsec-crypto
library is not loaded or the HMAC key data id is not implemented).
"""
return KeyDataId(_obj=xmlsecmod.keyDataHmacId())
def keyDataRsaId():
"""
The RSA key data id.
Returns : RSA key data id or None if an error occurs (xmlsec-crypto library
is not loaded or the RSA key data id is not implemented).
"""
return KeyDataId(_obj=xmlsecmod.keyDataRsaId())
def keyDataX509Id():
"""
The X509 key data id.
Returns : X509 key data id or None if an error occurs (xmlsec-crypto
library is not loaded or the X509 key data id is not implemented).
"""
return KeyDataId(_obj=xmlsecmod.keyDataX509Id())
def keyDataRawX509CertId():
"""
The raw X509 cert key data id.
Returns : raw x509 cert key data id or None if an error occurs
(xmlsec-crypto library is not loaded or the raw X509 cert key data id is
not implemented).
"""
return KeyDataId(_obj=xmlsecmod.keyDataRawX509CertId())
def x509StoreId():
"""
The X509 certificates key data store id.
Returns : X509 certificates key data store id or None if an error occurs
(xmlsec-crypto library is not loaded or the raw X509 cert key data id is
not implemented).
"""
# FIXME : should return KeyDataStoreId
return xmlsecmod.x509StoreId()
# Crypto Transforms Ids methods
def transformAes128CbcId():
"""
AES 128 CBC encryption transform id.
Returns : AES 128 CBC encryption transform id or None if an error occurs
(the xmlsec-crypto library is not loaded or this transform is not
implemented).
"""
return TransformId(_obj=xmlsecmod.transformAes128CbcId())
def transformAes192CbcId():
"""
AES 192 CBC encryption transform id.
Returns : AES 192 CBC encryption transform id or None if an error occurs
(the xmlsec-crypto library is not loaded or this transform is not
implemented).
"""
return TransformId(_obj=xmlsecmod.transformAes192CbcId())
def transformAes256CbcId():
"""
AES 256 CBC encryption transform id.
Returns : AES 256 CBC encryption transform id or None if an error occurs
(the xmlsec-crypto library is not loaded or this transform is not
implemented).
"""
return TransformId(_obj=xmlsecmod.transformAes256CbcId())
def transformKWAes128Id():
"""
The AES-128 kew wrapper transform id.
Returns : AES-128 kew wrapper transform id is or None if an error occurs
(the xmlsec-crypto library is not loaded or this transform is not
implemented).
"""
return TransformId(_obj=xmlsecmod.transformKWAes128Id())
def transformKWAes192Id():
"""
The AES-192 kew wrapper transform id.
Returns : AES-192 kew wrapper transform id is or None if an error occurs
(the xmlsec-crypto library is not loaded or this transform is not
implemented).
"""
return TransformId(_obj=xmlsecmod.transformKWAes192Id())
def transformKWAes256Id():
"""
The AES-256 kew wrapper transform id.
Returns : AES-256 kew wrapper transform id is or None if an error occurs
(the xmlsec-crypto library is not loaded or this transform is not
implemented).
"""
return TransformId(_obj=xmlsecmod.transformKWAes256Id())
def transformDes3CbcId():
"""
Triple DES CBC encryption transform id.
Returns : Triple DES encryption transform id or None if an error occurs
(the xmlsec-crypto library is not loaded or this transform is not
implemented).
"""
return TransformId(_obj=xmlsecmod.transformDes3CbcId())
def transformKWDes3Id():
"""
The Triple DES key wrapper transform id.
Returns : Triple DES key wrapper transform id or None if an error occurs
(the xmlsec-crypto library is not loaded or this transform is not
implemented).
"""
return TransformId(_obj=xmlsecmod.transformKWDes3Id())
def transformDsaSha1Id():
"""
The DSA-SHA1 signature transform id.
Returns : DSA-SHA1 signature transform id or None if an error occurs (the
xmlsec-crypto library is not loaded or this transform is not implemented).
"""
return TransformId(_obj=xmlsecmod.transformDsaSha1Id())
def transformHmacMd5Id():
"""
The HMAC-MD5 transform id.
Returns : HMAC-MD5 transform id or None if an error occurs (the
xmlsec-crypto library is not loaded or this transform is not implemented).
"""
return TransformId(_obj=xmlsecmod.transformHmacMd5Id())
def transformHmacRipemd160Id():
"""
The HMAC-RIPEMD160 transform id.
Returns : HMAC-RIPEMD160 transform id or None if an error occurs (the
xmlsec-crypto library is not loaded or this transform is not implemented).
"""
return TransformId(_obj=xmlsecmod.transformHmacRipemd160Id())
def transformHmacSha1Id():
"""
The HMAC-SHA1 transform id.
Returns : HMAC-SHA1 transform id or None if an error occurs
(the xmlsec-crypto library is not loaded or this transform is not
implemented).
"""
return TransformId(_obj=xmlsecmod.transformHmacSha1Id())
def transformHmacSha224Id():
"""
The HMAC-SHA224 transform id.
Returns : HMAC-SHA224 transform id or None if an error occurs
(the xmlsec-crypto library is not loaded or this transform is not
implemented).
"""
return TransformId(_obj=xmlsecmod.transformHmacSha224Id())
def transformHmacSha256Id():
"""
The HMAC-SHA256 transform id.
Returns : HMAC-SHA256 transform id or None if an error occurs
(the xmlsec-crypto library is not loaded or this transform is not
implemented).
"""
return TransformId(_obj=xmlsecmod.transformHmacSha256Id())
def transformHmacSha384Id():
"""
The HMAC-SHA384 transform id.
Returns : HMAC-SHA384 transform id or None if an error occurs
(the xmlsec-crypto library is not loaded or this transform is not
implemented).
"""
return TransformId(_obj=xmlsecmod.transformHmacSha384Id())
def transformHmacSha512Id():
"""
The HMAC-SHA512 transform id.
Returns : HMAC-SHA512 transform id or None if an error occurs
(the xmlsec-crypto library is not loaded or this transform is not
implemented).
"""
return TransformId(_obj=xmlsecmod.transformHmacSha512Id())
def transformMd5Id():
"""
The MD5 digest transform id.
Returns : MD5 digest transform id or None if an error occurs
(the xmlsec-crypto library is not loaded or this transform is not
implemented).
"""
return TransformId(_obj=xmlsecmod.transformMd5Id())
def transformRipemd160Id():
"""
RIPEMD-160 digest transform id.
Returns : RIPEMD-160 digest transform id or None if an error occurs (the
xmlsec-crypto library is not loaded or this transform is not implemented).
"""
return TransformId(_obj=xmlsecmod.transformRipemd160Id())
def transformRsaMd5Id():
"""
The RSA-MD5 signature transform id.
Returns : RSA-MD5 signature transform id or None if an error occurs (the
xmlsec-crypto library is not loaded or this transform is not implemented).
"""
return TransformId(_obj=xmlsecmod.transformRsaMd5Id())
def transformRsaRipemd160Id():
"""
The RSA-RIPEMD160 signature transform id.
Returns : RSA-RIPEMD160 signature transform id or None if an error occurs
(the xmlsec-crypto library is not loaded or this transform is not
implemented).
"""
return TransformId(_obj=xmlsecmod.transformRsaRipemd160Id())
def transformRsaSha1Id():
"""
The RSA-SHA1 signature transform id.
Returns : RSA-SHA1 signature transform id or None if an error occurs (the
xmlsec-crypto library is not loaded or this transform is not implemented).
"""
return TransformId(_obj=xmlsecmod.transformRsaSha1Id())
def transformRsaSha224Id():
"""
The RSA-SHA224 signature transform id.
Returns : RSA-SHA224 signature transform id or None if an error occurs (the
xmlsec-crypto library is not loaded or this transform is not implemented).
"""
return TransformId(_obj=xmlsecmod.transformRsaSha224Id())
def transformRsaSha256Id():
"""
The RSA-SHA256 signature transform id.
Returns : RSA-SHA256 signature transform id or None if an error occurs (the
xmlsec-crypto library is not loaded or this transform is not implemented).
"""
return TransformId(_obj=xmlsecmod.transformRsaSha256Id())
def transformRsaSha384Id():
"""
The RSA-SHA384 signature transform id.
Returns : RSA-SHA384 signature transform id or None if an error occurs (the
xmlsec-crypto library is not loaded or this transform is not implemented).
"""
return TransformId(_obj=xmlsecmod.transformRsaSha384Id())
def transformRsaSha512Id():
"""
The RSA-SHA512 signature transform id.
Returns : RSA-SHA512 signature transform id or None if an error occurs (the
xmlsec-crypto library is not loaded or this transform is not implemented).
"""
return TransformId(_obj=xmlsecmod.transformRsaSha512Id())
def transformRsaPkcs1Id():
"""
The RSA-PKCS1 key transport transform id.
Returns : RSA-PKCS1 key transport transform id or None if an error occurs
(the xmlsec-crypto library is not loaded or this transform is not
implemented).
"""
return TransformId(_obj=xmlsecmod.transformRsaPkcs1Id())
def transformRsaOaepId():
"""
The RSA-OAEP key transport transform id.
Returns : RSA-OAEP key transport transform id or None if an error occurs
(the xmlsec-crypto library is not loaded or this transform is not
implemented).
"""
return TransformId(_obj=xmlsecmod.transformRsaOaepId())
def transformSha1Id():
"""
SHA-1 digest transform id.
Returns : SHA-1 digest transform id or None if an error occurs (the
xmlsec-crypto library is not loaded or this transform is not implemented).
"""
return TransformId(_obj=xmlsecmod.transformSha1Id())
def transformSha224Id():
"""
The SHA224 digest transform id.
Returns : SHA224 digest transform id or None if an error occurs
(the xmlsec-crypto library is not loaded or this transform is not
implemented).
"""
return TransformId(_obj=xmlsecmod.transformSha224Id())
def transformSha256Id():
"""
The SHA256 digest transform id.
Returns : SHA256 digest transform id or None if an error occurs
(the xmlsec-crypto library is not loaded or this transform is not
implemented).
"""
return TransformId(_obj=xmlsecmod.transformSha256Id())
def transformSha384Id():
"""
The SHA384 digest transform id.
Returns : SHA384 digest transform id or None if an error occurs
(the xmlsec-crypto library is not loaded or this transform is not
implemented).
"""
return TransformId(_obj=xmlsecmod.transformSha384Id())
def transformSha512Id():
"""
The SHA512 digest transform id.
Returns : SHA512 digest transform id or None if an error occurs
(the xmlsec-crypto library is not loaded or this transform is not
implemented).
"""
return TransformId(_obj=xmlsecmod.transformSha512Id())
# High level routines form xmlsec command line utility
def cryptoAppInit(config=None):
"""
General crypto engine initialization. This function is used by XMLSec
command line utility and called before init function.
config : the path to crypto library configuration.
Returns : 0 on success or a negative value otherwise.
"""
return xmlsecmod.cryptoAppInit(config)
def cryptoAppShutdown():
"""
General crypto engine shutdown. This function is used by XMLSec command
line utility and called after shutdown function.
Returns : 0 on success or a negative value otherwise.
"""
return xmlsecmod.cryptoAppShutdown()
def cryptoAppDefaultKeysMngrInit(mngr):
"""
Initializes mngr with simple keys store simpleKeysStoreId and a default
crypto key data stores.
mngr : the keys manager.
Returns : 0 on success or a negative value otherwise.
"""
return xmlsecmod.cryptoAppDefaultKeysMngrInit(mngr)
def cryptoAppDefaultKeysMngrAdoptKey(mngr, key):
"""
Adds key to the keys manager mngr created with cryptoAppDefaultKeysMngrInit
function.
- mngr : the keys manager.
- key : the key.
Returns : 0 on success or a negative value otherwise.
"""
return xmlsecmod.cryptoAppDefaultKeysMngrAdoptKey(mngr, key)
def cryptoAppDefaultKeysMngrLoad(mngr, uri):
"""
Loads XML keys file from uri to the keys manager mngr created with
cryptoAppDefaultKeysMngrInit function.
mngr : the keys manager.
uri : the uri.
Returns : 0 on success or a negative value otherwise.
"""
return xmlsecmod.cryptoAppDefaultKeysMngrLoad(mngr, uri)
def cryptoAppDefaultKeysMngrSave(mngr, filename, type):
"""
Saves keys from mngr to XML keys file.
mngr : the keys manager.
filename : the destination filename.
type : the type of keys to save (public/private/symmetric).
Returns : 0 on success or a negative value otherwise.
"""
return xmlsecmod.cryptoAppDefaultKeysMngrSave(mngr, filename, type)
def cryptoAppKeysMngrCertLoad(mngr, filename, format, type):
"""
Reads cert from filename and adds to the list of trusted or known untrusted
certs in store.
mngr : the keys manager.
filename : the certificate file.
format : the certificate file format.
type : the flag that indicates if the certificate in filename trusted or not.
Returns : 0 on success or a negative value otherwise.
"""
return xmlsecmod.cryptoAppKeysMngrCertLoad(mngr, filename, format, type)
def cryptoAppKeysMngrCertLoadMemory(mngr, data, dataSize, format, type):
"""
Reads cert from memory and adds to the list of trusted or known untrusted
certs in store.
mngr : the keys manager.
data : the memory containing the certificate.
dataSize : the size of the memory containing the certificate.
format : the certificate file format.
type : the flag that indicates if the certificate in filename trusted or not.
Returns : 0 on success or a negative value otherwise.
"""
return xmlsecmod.cryptoAppKeysMngrCertLoadMemory(mngr, data, dataSize, format, type)
def cryptoAppKeyLoad(filename, format, pwd, pwdCallback, pwdCallbackCtx):
"""
Reads key from filename.
filename : the key filename.
format : the key file format.
pwd : the key file password.
pwdCallback : the key password callback.
pwdCallbackCtx : the user context for password callback.
Returns : the key or None if an error occurs.
"""
ret = xmlsecmod.cryptoAppKeyLoad(filename, format, pwd,
pwdCallback, pwdCallbackCtx)
if ret is None: raise Error('xmlSecCryptoAppKeyLoad() failed')
return Key(_obj=ret)
def cryptoAppKeyLoadMemory(data, dataSize, format, pwd, pwdCallback, pwdCallbackCtx):
"""
Reads key from filename.
data : the key data.
dataSize : the key data size.
format : the key file format.
pwd : the key file password.
pwdCallback : the key password callback.
pwdCallbackCtx : the user context for password callback.
Returns : the key or None if an error occurs.
"""
ret = xmlsecmod.cryptoAppKeyLoadMemory(data, dataSize, format, pwd,
pwdCallback, pwdCallbackCtx)
if ret is None: raise Error('xmlSecCryptoAppKeyLoadMemory() failed')
return Key(_obj=ret)
def cryptoAppPkcs12Load(filename, pwd, pwdCallback, pwdCallbackCtx):
"""
Reads key and all associated certificates from the PKCS12 file.
For uniformity, call cryptoAppKeyLoad instead of this function.
Pass in format=xmlsec.KeyDataFormatPkcs12.
filename : the PKCS12 key filename.
pwd : the PKCS12 file password.
pwdCallback : the password callback.
pwdCallbackCtx : the user context for password callback.
Returns : the key or None if an error occurs.
"""
ret = xmlsecmod.cryptoAppPkcs12Load(filename, pwd,
pwdCallback, pwdCallbackCtx)
if ret is None: raise Error('xmlSecCryptoAppKeyLoad() failed')
return Key(_obj=ret)
def cryptoAppKeyCertLoad(key, filename, format):
"""
Reads the certificate from filename and adds it to key.
key : the key.
filename : the certificate filename.
format : the certificate file format.
Returns : 0 on success or a negative value otherwise.
"""
return xmlsecmod.cryptoAppKeyCertLoad(key, filename, format)
def cryptoAppKeyCertLoadMemory(key, data, dataSize, format):
"""
Reads the certificate from filename and adds it to key.
key : the key.
data : the certificate data.
dataSize : the certificate data size.
format : the certificate file format.
Returns : 0 on success or a negative value otherwise.
"""
return xmlsecmod.cryptoAppKeyCertLoadMemory(key, data, dataSize, format)
def cryptoAppGetDefaultPwdCallback():
"""
Gets default password callback.
"""
return xmlsecmod.cryptoAppGetDefaultPwdCallback()
###############################################################################
# base64.h
###############################################################################
BASE64_LINESIZE = 64 # The default maximum base64 encoded line size.
# Standalone functions to do base64 encode/decode "at once"
def base64Encode(buf, columns):
"""
Encodes the data from input buffer.
buf : the input buffer.
columns : the output max line length (if 0 then no line breaks would be
inserted)
Returns : a string with base64 encoded data or None if an error occurs.
"""
return xmlsecmod.base64Encode(buf, len(buf), columns)
def base64Decode(str):
"""
Decodes input base64 encoded string.
str : the input buffer with base64 encoded string.
Returns : a string with decoded data or None if an error occurs.
"""
return xmlsecmod.base64Decode(str)
class Base64Ctx:
def __init__(self, encode, columns, _obj=None):
"""
Allocates and initializes new base64 context.
encode : the encode/decode flag (1 - encode, 0 - decode)
columns : the max line length.
Returns : the newly created Base64 context object or None if an
error occurs.
"""
if _obj != None:
self._o = _obj
return
self._o = xmlsecmod.base64CtxCreate(encode, columns)
if self._o is None: raise Error('xmlSecBase64CtxCreate() failed')
def destroy(self):
"""Destroys base64 context."""
xmlsecmod.base64CtxDestroy(self)
def initialize(self, encode, columns):
"""
Initializes new base64 context.
encode : the encode/decode flag (1 - encode, 0 - decode)
columns : the max line length.
Returns : 0 on success and a negative value otherwise.
"""
return xmlsecmod.base64CtxDestroy(self, encode, columns)
def finalize(self):
"""Frees all the resources allocated by Base64 context."""
xmlsecmod.base64CtxDestroy(self)
def update(self, inBuf, inBufSize, outBuf, outBufSize):
# FIXME
"""
Encodes or decodes the next piece of data from input buffer.
inBuf : the input buffer
inBufSize : the input buffer size
outBuf : the output buffer
outBufSize : the output buffer size
Returns : the number of bytes written to output buffer
or -1 if an error occurs.
"""
return xmlsecmod.base64CtxUpdate(self, inBuf, inBufSize, outBuf,
outBufSize)
def final(self, out, outSize):
# FIXME
"""
Encodes or decodes the last piece of data stored in the context and
finalizes the result.
out : the output buffer
outSize : the output buffer size
Returns : the number of bytes written to output buffer or -1 if an
error occurs.
"""
return xmlsecmod.base64CtxFinal(self, out, outSize)
###############################################################################
# buffer.h
###############################################################################
# The memory allocation mode (used by Buffer and List).
# the memory allocation mode that minimizes total allocated memory size.
AllocModeExact = 0
# the memory allocation mode that tries to minimize the number of malloc calls.
AllocModeDouble = 1
def bufferSetDefaultAllocMode(defAllocMode, defInitialSize):
"""
Sets new global default allocation mode and minimal intial size.
defAllocMode : the new default buffer allocation mode.
defInitialSize : the new default buffer minimal intial size.
"""
xmlsecmod.bufferSetDefaultAllocMode(defAllocMode, defInitialSize)
class Buffer:
def __init__(self, size=None, _obj=None):
"""
Creates and initalizes new memory buffer with given size. Caller is
responsible for calling destroy method to free the buffer.
size : the initial buffer size.
Returns : the buffer or None if an error occurs.
"""
if _obj != None:
self._o = _obj
return
self._o = xmlsecmod.bufferCreate(size)
if self._o is None: raise Error('xmlSecBufferCreate() failed')
def __isprivate(self, name):
return name == '_o'
def __getattr__(self, name):
if self.__isprivate(name):
return self.__dict__[name]
if name[:2] == "__" and name[-2:] == "__" and name != "__members__":
raise AttributeError, name
ret = xmlsecmod.bufferGetAttr(self, name)
if ret is None:
raise AttributeError, name
# data, size, maxSize, allocMode
return ret
def __setattr__(self, name, value):
if self.__isprivate(name):
self.__dict__[name] = value
else:
xmlsecmod.bufferSetAttr(self, name, value)
def destroy(self):
"""Destroys buffer object."""
return xmlsecmod.bufferDestroy(self)
def initialize(self, size):
"""
Initializes buffer object buf. Caller is responsible for calling
finalize method to free allocated resources.
size : the initial buffer size.
Returns : 0 on success or a negative value if an error occurs.
"""
return xmlsecmod.bufferInitialize(self, size)
def finalize(self):
"""Frees allocated resource for a buffer intialized with initialize method."""
xmlsecmod.bufferFinalize(self)
def getData(self):
"""
Gets buffer's data.
Returns : buffer's data.
"""
return xmlsecmod.bufferGetData(self)
def setData(self, data, size):
"""
Sets the value of the buffer to data.
data : the data.
size : the data size.
Returns : 0 on success or a negative value if an error occurs.
"""
return xmlsecmod.bufferSetData(self, data, size)
def getSize(self):
"""
Gets the current buffer data size.
Returns : the current data size.
"""
return xmlsecmod.bufferGetSize(self)
def setSize(self, size):
"""
Sets new buffer data size. If necessary, buffer grows to have at least
size bytes.
size : the new data size.
Returns : 0 on success or a negative value if an error occurs.
"""
return xmlsecmod.bufferSetSize(self, size)
def getMaxSize(self):
"""
Gets the maximum (allocated) buffer size.
Returns : the maximum (allocated) buffer size.
"""
return xmlsecmod.bufferGetMaxSize(self)
def setMaxSize(self, size):
"""
Sets new buffer maximum size. If necessary, buffer grows to have at
least size bytes.
size : the new maximum size.
Returns : 0 on success or a negative value if an error occurs.
"""
return xmlsecmod.bufferSetMaxSize(self, size)
def empty(self):
"""Empties the buffer."""
xmlsecmod.bufferEmpty(self)
def append(self, data, size):
"""
Appends the data after the current data stored in the buffer.
data : the data.
size : the data size.
Returns : 0 on success or a negative value if an error occurs.
"""
return xmlsecmod.bufferAppend(self, data, size)
def prepend(self, data, size):
"""
Prepends the data before the current data stored in the buffer.
data : the data.
size : the data size.
Returns : 0 on success or a negative value if an error occurs.
"""
return xmlsecmod.bufferPrepend(self, data, size)
def removeHead(self, size):
"""
Removes size bytes from the beginning of the current buffer.
size : the number of bytes to be removed.
Returns : 0 on success or a negative value if an error occurs.
"""
return xmlsecmod.bufferRemoveHead(self, size)
def removeTail(self, size):
"""
Removes size bytes from the end of current buffer.
size : the number of bytes to be removed.
Returns : 0 on success or a negative value if an error occurs.
"""
return xmlsecmod.bufferRemoveTail(self, size)
def readFile(self, filename):
"""
Reads the content of the file filename in the buffer.
filename : the filename.
Returns : 0 on success or a negative value if an error occurs.
"""
return xmlsecmod.bufferReadFile(self, filename)
def base64NodeContentRead(self, node):
"""
Reads the content of the node, base64 decodes it and stores the result
in the buffer.
node : the node.
Returns : 0 on success or a negative value if an error occurs.
"""
return xmlsecmod.bufferBase64NodeContentRead(self, node)
def base64NodeContentWrite(self, node, columns):
"""
Sets the content of the node to the base64 encoded buffer data.
node : the node.
columns : the max line size for base64 encoded data.
Returns : 0 on success or a negative value if an error occurs.
"""
return xmlsecmod.bufferBase64NodeContentWrite(self, node, columns)
def createOutputBuffer(self):
"""
Creates new LibXML output buffer to store data in the buf. Caller is
responsible for destroying buf when processing is done.
Returns : newly allocated output buffer or None if an error occurs.
"""
return libxml2.outputBuffer(_obj=xmlsecmod.bufferCreateOutputBuffer(self))
###############################################################################
# errors.h
###############################################################################
# An XMLSec function failed (error subject is the failed function).
ERRORS_R_XMLSEC_FAILED = 1
# Failed to allocate memory error.
ERRORS_R_MALLOC_FAILED = 2
# Failed to duplicate string error.
ERRORS_R_STRDUP_FAILED = 3
# Crypto (OpenSSL) function failed (error subject is the failed function).
ERRORS_R_CRYPTO_FAILED = 4
# LibXML function failed (error subject is the failed function).
ERRORS_R_XML_FAILED = 5
# LibXSLT function failed (error subject is the failed function).
ERRORS_R_XSLT_FAILED = 6
# IO operation failed.
ERRORS_R_IO_FAILED = 7
# The feature is disabled during compilation.
# Check './configure --help' for details on how to enable it.
ERRORS_R_DISABLED = 8
# Feature is not implemented.
ERRORS_R_NOT_IMPLEMENTED = 9
# Invalid size.
ERRORS_R_INVALID_SIZE = 11
# Invalid data.
ERRORS_R_INVALID_DATA = 12
# Invalid result.
ERRORS_R_INVALID_RESULT = 13
# Invalid type.
ERRORS_R_INVALID_TYPE = 14
# Invalid operation.
ERRORS_R_INVALID_OPERATION = 15
# Invalid status.
ERRORS_R_INVALID_STATUS = 16
# Invalid format.
ERRORS_R_INVALID_FORMAT = 17
# The data do not match our expectation.
ERRORS_R_DATA_NOT_MATCH = 18
# Invalid node (error subject is the node name).
ERRORS_R_INVALID_NODE = 21
# Invalid node content (error subject is the node name).
ERRORS_R_INVALID_NODE_CONTENT = 22
# Invalid node attribute (error subject is the node name).
ERRORS_R_INVALID_NODE_ATTRIBUTE = 23
# Missing node attribute (error subject is the node name).
ERRORS_R_MISSING_NODE_ATTRIBUTE = 25
# Node already present,
ERRORS_R_NODE_ALREADY_PRESENT = 26
# Unexpected node (error subject is the node name).
ERRORS_R_UNEXPECTED_NODE = 27
# Node not found (error subject is the required node name).
ERRORS_R_NODE_NOT_FOUND = 28
# This transform is invlaid here.
ERRORS_R_INVALID_TRANSFORM = 31
# Key is invalid for this transform.
ERRORS_R_INVALID_TRANSFORM_KEY = 32
# Invalid URI type.
ERRORS_R_INVALID_URI_TYPE = 33
# The transform requires the input document to be the same as context.
ERRORS_R_TRANSFORM_SAME_DOCUMENT_REQUIRED = 34
# The transform is disabled.
ERRORS_R_TRANSFORM_DISABLED = 35
# Key data is invalid.
ERRORS_R_INVALID_KEY_DATA = 41
# Data is not found (error subject is the data name).
ERRORS_R_KEY_DATA_NOT_FOUND = 42
# The key data is already exist.
ERRORS_R_KEY_DATA_ALREADY_EXIST = 43
# Invalid key size.
ERRORS_R_INVALID_KEY_DATA_SIZE = 44
# Key not found.
ERRORS_R_KEY_NOT_FOUND = 45
# The key data type disabled.
ERRORS_R_KEYDATA_DISABLED = 46
# Max allowed retrievals level reached.
ERRORS_R_MAX_RETRIEVALS_LEVEL = 51
# The retrieved key data type does not match the one specified
# in the <dsig:RetrievalMethod/> node.
ERRORS_R_MAX_RETRIEVAL_TYPE_MISMATCH = 52
# Max EncryptedKey level reached.
ERRORS_R_MAX_ENCKEY_LEVEL = 61
# Certificate verification failed.
ERRORS_R_CERT_VERIFY_FAILED = 71
# Requested certificate is not found.
ERRORS_R_CERT_NOT_FOUND = 72
# The certificate is revoked.
ERRORS_R_CERT_REVOKED = 73
# Failed to get certificate issuer.
ERRORS_R_CERT_ISSUER_FAILED = 74
# "Not valid before" verification failed.
ERRORS_R_CERT_NOT_YET_VALID = 75
# "Not valid after" verification failed.
ERRORS_R_CERT_HAS_EXPIRED = 76
# The <dsig:Reference> nodes not found.
ERRORS_R_DSIG_NO_REFERENCES = 81
# The <dsig:Reference> validation failed.
ERRORS_R_DSIG_INVALID_REFERENCE = 82
# Invalid assertion.
ERRORS_R_ASSERTION = 100
# The maximum xmlsec errors number.
ERRORS_MAX_NUMBER = 256
# Empty error message " ".
ERRORS_NO_MESSAGE = " "
def errorsSetCallback(callback):
"""
Sets the errors callback function to callback that will be called every
time an error occurs.
callback : the new errors callback function.
"""
xmlsecmod.errorsSetCallback(callback)
###############################################################################
# keyinfo.h
###############################################################################
# The KeyInfoCtx operation mode (read or write).
KeyInfoModeRead = 0
KeyInfoModeWrite = 1
# If flag is set then we will continue reading <dsig:KeyInfo /> element even
# when key is already found.
KEYINFO_FLAGS_DONT_STOP_ON_KEY_FOUND = 0x00000001
# If flag is set then we abort if an unknown <dsig:KeyInfo /> child is found.
KEYINFO_FLAGS_STOP_ON_UNKNOWN_CHILD = 0x00000002
# If flags is set then we abort if an unknown key name
# (content of <dsig:KeyName /> element) is found.
KEYINFO_FLAGS_KEYNAME_STOP_ON_UNKNOWN = 0x00000004
# If flags is set then we abort if an unknown <dsig:KeyValue /> child is found.
KEYINFO_FLAGS_KEYVALUE_STOP_ON_UNKNOWN_CHILD = 0x00000008
# If flag is set then we abort if an unknown href attribute of
# <dsig:RetrievalMethod /> element is found.
KEYINFO_FLAGS_RETRMETHOD_STOP_ON_UNKNOWN_HREF = 0x00000010
# If flag is set then we abort if an href attribute <dsig:RetrievalMethod />
# element does not match the real key data type.
KEYINFO_FLAGS_RETRMETHOD_STOP_ON_MISMATCH_HREF = 0x00000020
# If flags is set then we abort if an unknown <dsig:X509Data /> child is found.
KEYINFO_FLAGS_X509DATA_STOP_ON_UNKNOWN_CHILD = 0x00000100
# If flag is set then we'll load certificates from <dsig:X509Data /> element
# without verification.
KEYINFO_FLAGS_X509DATA_DONT_VERIFY_CERTS = 0x00000200
# If flag is set then we'll stop when we could not resolve reference to
# certificate from <dsig:X509IssuerSerial />, <dsig:X509SKI /> or
# <dsig:X509SubjectName /> elements.
KEYINFO_FLAGS_X509DATA_STOP_ON_UNKNOWN_CERT = 0x00000400
# If the flag is set then we'll stop when <dsig:X509Data /> element processing
# does not return a verified certificate.
KEYINFO_FLAGS_X509DATA_STOP_ON_INVALID_CERT = 0x00000800
# If the flag is set then we'll stop when <enc:EncryptedKey /> element
# processing fails.
KEYINFO_FLAGS_ENCKEY_DONT_STOP_ON_FAILED_DECRYPTION = 0x00001000
# If the flag is set then we'll stop when we found an empty node. Otherwise we
# just ignore it.
KEYINFO_FLAGS_STOP_ON_EMPTY_NODE = 0x00002000
# If the flag is set then we'll skip strict checking of certs and CRLs
KEYINFO_FLAGS_X509DATA_SKIP_STRICT_CHECKS = 0x00004000
def keyInfoNodeRead(keyInfoNode, key, keyInfoCtx):
"""
Parses the <dsig:KeyInfo/> element keyInfoNode, extracts the key data and
stores into key.
keyInfoNode : the <dsig:KeyInfo/> node.
key : the result key object.
keyInfoCtx : the <dsig:KeyInfo/> element processing context.
Returns : 0 on success or -1 if an error occurs.
"""
return xmlsecmod.keyInfoNodeRead(keyInfoNode, key, keyInfoCtx)
def keyInfoNodeWrite(keyInfoNode, key, keyInfoCtx):
"""
Writes the key into the <dsig:KeyInfo/> element template keyInfoNode.
keyInfoNode : the <dsig:KeyInfo/> node.
key : the result key object.
keyInfoCtx : the <dsig:KeyInfo/> element processing context.
Returns : 0 on success or -1 if an error occurs.
"""
return xmlsecmod.keyInfoNodeWrite(keyInfoNode, key, keyInfoCtx)
def keyInfoCtxCopyUserPref(dst, src):
"""
Copies user preferences from src context to dst context.
dst : the destination context object.
src : the source context object.
Returns : 0 on success and a negative value if an error occurs.
"""
return xmlsecmod.keyInfoCtxCopyUserPref(dst, src)
# Key data Ids methods
def keyDataNameId():
"""
The <dsig:KeyName/> element key data id
(http://www.w3.org/TR/xmldsig-core/sec-KeyName)
The KeyName element contains a string value (in which white space is
significant) which may be used by the signer to communicate a key identifier
to the recipient. Typically, KeyName contains an identifier related to the
key pair used to sign the message, but it may contain other protocol-related
information that indirectly identifies a key pair. (Common uses of KeyName
include simple string names for keys, a key index, a distinguished name (DN),
an email address, etc.)
Returns : the <dsig:KeyName/> element processing key data id.
"""
return KeyDataId(_obj=xmlsecmod.keyDataNameId())
def keyDataValueId():
"""
The <dsig:KeyValue/> element key data id
(http://www.w3.org/TR/xmldsig-core/sec-KeyValue)
The KeyValue element contains a single public key that may be useful in
validating the signature.
Returns : the <dsig:KeyValue/> element processing key data id.
"""
return KeyDataId(_obj=xmlsecmod.keyDataValueId())
def keyDataRetrievalMethodId():
"""
The <dsig:RetrievalMethod/> element key data id
(http://www.w3.org/TR/xmldsig-core/sec-RetrievalMethod)
A RetrievalMethod element within KeyInfo is used to convey a reference to
KeyInfo information that is stored at another location. For example, several
signatures in a document might use a key verified by an X.509v3 certificate
chain appearing once in the document or remotely outside the document; each
signature's KeyInfo can reference this chain using a single RetrievalMethod
element instead of including the entire chain with a sequence of
X509Certificate elements.
RetrievalMethod uses the same syntax and dereferencing behavior as
Reference's URI and The Reference Processing Model.
Returns : the <dsig:RetrievalMethod/> element processing key data id.
"""
return KeyDataId(_obj=xmlsecmod.keyDataRetrievalMethodId())
def keyDataEncryptedKeyId():
"""
The <enc:EncryptedKey/> element key data id
(http://www.w3.org/TR/xmlenc-core/sec-EncryptedKey)
The EncryptedKey element is used to transport encryption keys from the
originator to a known recipient(s). It may be used as a stand-alone XML
document, be placed within an application document, or appear inside an
EncryptedData element as a child of a ds:KeyInfo element. The key value
is always encrypted to the recipient(s). When EncryptedKey is decrypted
the resulting octets are made available to the EncryptionMethod algorithm
without any additional processing.
Returns : the <enc:EncryptedKey/> element processing key data id.
"""
return KeyDataId(_obj=xmlsecmod.keyDataEncryptedKeyId())