summaryrefslogtreecommitdiff
path: root/src/mscrypto/symkeys.c
blob: 658a6d4991478850a69084cef62cbf3d80ceec42 (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
/**
 *
 * XMLSec library
 *
 * DES Algorithm support
 *
 * This is free software; see Copyright file in the source
 * distribution for preciese wording.
 *
 * Copyright (C) 2003 Cordys R&D BV, All rights reserved.
 */
#include "globals.h"

#include <stdlib.h>
#include <stdio.h>
#include <string.h>

#include <windows.h>
#include <wincrypt.h>

#include <xmlsec/xmlsec.h>
#include <xmlsec/xmltree.h>
#include <xmlsec/keys.h>
#include <xmlsec/keyinfo.h>
#include <xmlsec/transforms.h>
#include <xmlsec/errors.h>

#include <xmlsec/mscrypto/crypto.h>
#include "private.h"

/*****************************************************************************
 *
 * Symmetic (binary) keys - just a wrapper for xmlSecKeyDataBinary
 *
 ****************************************************************************/
static int      xmlSecMSCryptoSymKeyDataInitialize      (xmlSecKeyDataPtr data);
static int      xmlSecMSCryptoSymKeyDataDuplicate       (xmlSecKeyDataPtr dst,
                                                         xmlSecKeyDataPtr src);
static void     xmlSecMSCryptoSymKeyDataFinalize        (xmlSecKeyDataPtr data);
static int      xmlSecMSCryptoSymKeyDataXmlRead         (xmlSecKeyDataId id,
                                                         xmlSecKeyPtr key,
                                                         xmlNodePtr node,
                                                         xmlSecKeyInfoCtxPtr keyInfoCtx);
static int      xmlSecMSCryptoSymKeyDataXmlWrite        (xmlSecKeyDataId id,
                                                         xmlSecKeyPtr key,
                                                         xmlNodePtr node,
                                                         xmlSecKeyInfoCtxPtr keyInfoCtx);
static int      xmlSecMSCryptoSymKeyDataBinRead         (xmlSecKeyDataId id,
                                                         xmlSecKeyPtr key,
                                                         const unsigned char* buf,
                                                         xmlSecSize bufSize,
                                                         xmlSecKeyInfoCtxPtr keyInfoCtx);
static int      xmlSecMSCryptoSymKeyDataBinWrite        (xmlSecKeyDataId id,
                                                         xmlSecKeyPtr key,
                                                         unsigned char** buf,
                                                         xmlSecSize* bufSize,
                                                         xmlSecKeyInfoCtxPtr keyInfoCtx);
static int      xmlSecMSCryptoSymKeyDataGenerate        (xmlSecKeyDataPtr data,
                                                         xmlSecSize sizeBits,
                                                         xmlSecKeyDataType type);

static xmlSecKeyDataType xmlSecMSCryptoSymKeyDataGetType(xmlSecKeyDataPtr data);
static xmlSecSize xmlSecMSCryptoSymKeyDataGetSize         (xmlSecKeyDataPtr data);
static void     xmlSecMSCryptoSymKeyDataDebugDump       (xmlSecKeyDataPtr data,
                                                         FILE* output);
static void     xmlSecMSCryptoSymKeyDataDebugXmlDump    (xmlSecKeyDataPtr data,
                                                         FILE* output);
static int      xmlSecMSCryptoSymKeyDataKlassCheck      (xmlSecKeyDataKlass* klass);

/*
 * GENERIC HELPER FUNCTIONS
 */

#define xmlSecMSCryptoSymKeyDataCheckId(data) \
    (xmlSecKeyDataIsValid((data)) && \
     xmlSecMSCryptoSymKeyDataKlassCheck((data)->id))

static int
xmlSecMSCryptoSymKeyDataInitialize(xmlSecKeyDataPtr data) {
    xmlSecAssert2(xmlSecMSCryptoSymKeyDataCheckId(data), -1);

    return(xmlSecKeyDataBinaryValueInitialize(data));
}

static int
xmlSecMSCryptoSymKeyDataDuplicate(xmlSecKeyDataPtr dst, xmlSecKeyDataPtr src) {
    xmlSecAssert2(xmlSecMSCryptoSymKeyDataCheckId(dst), -1);
    xmlSecAssert2(xmlSecMSCryptoSymKeyDataCheckId(src), -1);
    xmlSecAssert2(dst->id == src->id, -1);

    return(xmlSecKeyDataBinaryValueDuplicate(dst, src));
}

static void
xmlSecMSCryptoSymKeyDataFinalize(xmlSecKeyDataPtr data) {
    xmlSecAssert(xmlSecMSCryptoSymKeyDataCheckId(data));

    xmlSecKeyDataBinaryValueFinalize(data);
}

static int
xmlSecMSCryptoSymKeyDataXmlRead(xmlSecKeyDataId id, xmlSecKeyPtr key,
                               xmlNodePtr node, xmlSecKeyInfoCtxPtr keyInfoCtx) {
    xmlSecAssert2(xmlSecMSCryptoSymKeyDataKlassCheck(id), -1);

    return(xmlSecKeyDataBinaryValueXmlRead(id, key, node, keyInfoCtx));
}

static int
xmlSecMSCryptoSymKeyDataXmlWrite(xmlSecKeyDataId id, xmlSecKeyPtr key,
                                    xmlNodePtr node, xmlSecKeyInfoCtxPtr keyInfoCtx) {
    xmlSecAssert2(xmlSecMSCryptoSymKeyDataKlassCheck(id), -1);

    return(xmlSecKeyDataBinaryValueXmlWrite(id, key, node, keyInfoCtx));
}

static int
xmlSecMSCryptoSymKeyDataBinRead(xmlSecKeyDataId id, xmlSecKeyPtr key,
                                const unsigned char* buf, xmlSecSize bufSize,
                                xmlSecKeyInfoCtxPtr keyInfoCtx) {
    xmlSecAssert2(xmlSecMSCryptoSymKeyDataKlassCheck(id), -1);

    return(xmlSecKeyDataBinaryValueBinRead(id, key, buf, bufSize, keyInfoCtx));
}

static int
xmlSecMSCryptoSymKeyDataBinWrite(xmlSecKeyDataId id, xmlSecKeyPtr key,
                                 unsigned char** buf, xmlSecSize* bufSize,
                                 xmlSecKeyInfoCtxPtr keyInfoCtx) {
    xmlSecAssert2(xmlSecMSCryptoSymKeyDataKlassCheck(id), -1);

    return(xmlSecKeyDataBinaryValueBinWrite(id, key, buf, bufSize, keyInfoCtx));
}

static int
xmlSecMSCryptoSymKeyDataGenerate(xmlSecKeyDataPtr data, xmlSecSize sizeBits, xmlSecKeyDataType type ATTRIBUTE_UNUSED) {
    xmlSecBufferPtr buffer;

    xmlSecAssert2(xmlSecMSCryptoSymKeyDataCheckId(data), -1);
    xmlSecAssert2(sizeBits > 0, -1);

    buffer = xmlSecKeyDataBinaryValueGetBuffer(data);
    xmlSecAssert2(buffer != NULL, -1);

    return(xmlSecMSCryptoGenerateRandom(buffer, (sizeBits + 7) / 8));
}

static xmlSecKeyDataType
xmlSecMSCryptoSymKeyDataGetType(xmlSecKeyDataPtr data) {
    xmlSecBufferPtr buffer;

    xmlSecAssert2(xmlSecMSCryptoSymKeyDataCheckId(data), xmlSecKeyDataTypeUnknown);

    buffer = xmlSecKeyDataBinaryValueGetBuffer(data);
    xmlSecAssert2(buffer != NULL, xmlSecKeyDataTypeUnknown);

    return((xmlSecBufferGetSize(buffer) > 0) ? xmlSecKeyDataTypeSymmetric : xmlSecKeyDataTypeUnknown);
}

static xmlSecSize
xmlSecMSCryptoSymKeyDataGetSize(xmlSecKeyDataPtr data) {
    xmlSecAssert2(xmlSecMSCryptoSymKeyDataCheckId(data), 0);

    return(xmlSecKeyDataBinaryValueGetSize(data));
}

static void
xmlSecMSCryptoSymKeyDataDebugDump(xmlSecKeyDataPtr data, FILE* output) {
    xmlSecAssert(xmlSecMSCryptoSymKeyDataCheckId(data));

    xmlSecKeyDataBinaryValueDebugDump(data, output);
}

static void
xmlSecMSCryptoSymKeyDataDebugXmlDump(xmlSecKeyDataPtr data, FILE* output) {
    xmlSecAssert(xmlSecMSCryptoSymKeyDataCheckId(data));

    xmlSecKeyDataBinaryValueDebugXmlDump(data, output);
}

static int
xmlSecMSCryptoSymKeyDataKlassCheck(xmlSecKeyDataKlass* klass) {

#ifndef XMLSEC_NO_DES
    if(klass == xmlSecMSCryptoKeyDataDesId) {
        return(1);
    } else 
#endif /* XMLSEC_NO_DES */

#ifndef XMLSEC_NO_AES
    if(klass == xmlSecMSCryptoKeyDataAesId) {
                return(1);
    } else
#endif /* XMLSEC_NO_AES */

#ifndef XMLSEC_NO_HMAC
    if(klass == xmlSecMSCryptoKeyDataHmacId) {
                return(1);
    } else
#endif /* XMLSEC_NO_HMAC */

    {
        return(0);
    }

    return(0);
}


/******************************************************************************
 *
 * Utils
 *
 * Low level helper routines for importing plain text keys in MS HKEY handle,
 * since MSCrypto API does not support import of plain text (session) keys
 * just like that. These functions are based upon MS kb article #228786
 * and "Base Provider Key BLOBs" article for priv key blob format.
 *
 ******************************************************************************/
BOOL
xmlSecMSCryptoCreatePrivateExponentOneKey(HCRYPTPROV hProv, HCRYPTKEY *hPrivateKey)
{
    HCRYPTKEY hKey = 0;
    LPBYTE keyBlob = NULL;
    DWORD keyBlobLen;
    PUBLICKEYSTRUC* pubKeyStruc;
    RSAPUBKEY* rsaPubKey;
    DWORD bitLen;
    BYTE *ptr;
    int n;
    BOOL res = FALSE;

    xmlSecAssert2(hProv != 0, FALSE);
    xmlSecAssert2(hPrivateKey != NULL, FALSE);

    /* just in case */
    *hPrivateKey = 0;

    /* Generate the private key */
    if(!CryptGenKey(hProv, AT_KEYEXCHANGE, CRYPT_EXPORTABLE, &hKey)) {
        xmlSecError(XMLSEC_ERRORS_HERE,
                    NULL,
                    "CryptGenKey",
                    XMLSEC_ERRORS_R_CRYPTO_FAILED,
                    XMLSEC_ERRORS_NO_MESSAGE);
        goto done;
    }

    /* Export the private key, we'll convert it to a private exponent of one key */
    if(!CryptExportKey(hKey, 0, PRIVATEKEYBLOB, 0, NULL, &keyBlobLen)) {
        xmlSecError(XMLSEC_ERRORS_HERE,
                    NULL,
                    "CryptExportKey",
                    XMLSEC_ERRORS_R_CRYPTO_FAILED,
                    XMLSEC_ERRORS_NO_MESSAGE);
        goto done;
    }

    keyBlob = (LPBYTE)xmlMalloc(sizeof(BYTE) * keyBlobLen);
    if(keyBlob == NULL) {
        xmlSecError(XMLSEC_ERRORS_HERE,
                    NULL,
                    NULL,
                    XMLSEC_ERRORS_R_MALLOC_FAILED,
                    XMLSEC_ERRORS_NO_MESSAGE);
        goto done;
    }

    if(!CryptExportKey(hKey, 0, PRIVATEKEYBLOB, 0, keyBlob, &keyBlobLen)) {
        xmlSecError(XMLSEC_ERRORS_HERE,
                    NULL,
                    "CryptExportKey",
                    XMLSEC_ERRORS_R_CRYPTO_FAILED,
                    XMLSEC_ERRORS_NO_MESSAGE);
        goto done;
    }
    CryptDestroyKey(hKey);
    hKey = 0;

    /* Get the bit length of the key */
    if(keyBlobLen < sizeof(PUBLICKEYSTRUC) + sizeof(RSAPUBKEY)) {
        xmlSecError(XMLSEC_ERRORS_HERE,
                    NULL,
                    "CryptExportKey",
                    XMLSEC_ERRORS_R_CRYPTO_FAILED,
                    "len=%ld", keyBlobLen);
        goto done;
    }
    pubKeyStruc = (PUBLICKEYSTRUC*)keyBlob;
    if(pubKeyStruc->bVersion != 0x02) {
        xmlSecError(XMLSEC_ERRORS_HERE,
                    NULL,
                    "CryptExportKey",
                    XMLSEC_ERRORS_R_CRYPTO_FAILED,
                    "pubKeyStruc->bVersion=%d", pubKeyStruc->bVersion);
        goto done;
    }
    if(pubKeyStruc->bType != PRIVATEKEYBLOB) {
        xmlSecError(XMLSEC_ERRORS_HERE,
                    NULL,
                    "CryptExportKey",
                    XMLSEC_ERRORS_R_CRYPTO_FAILED,
                    "pubKeyStruc->bType=%d", (int)pubKeyStruc->bType);
        goto done;
    }

    /* aleksey: don't ask me why it is RSAPUBKEY, just don't ask */
    rsaPubKey = (RSAPUBKEY*)(keyBlob + sizeof(PUBLICKEYSTRUC));

    /* check that we have RSA private key */
    if(rsaPubKey->magic != 0x32415352) {
        xmlSecError(XMLSEC_ERRORS_HERE,
                    NULL,
                    "CryptExportKey",
                    XMLSEC_ERRORS_R_CRYPTO_FAILED,
                    "rsaPubKey->magic=0x%08lx", rsaPubKey->magic);
        goto done;
    }
    bitLen = rsaPubKey->bitlen;

    /*  Modify the Exponent in Key BLOB format Key BLOB format is documented in SDK */
    rsaPubKey->pubexp = 1;

    /* Private-key BLOBs, type PRIVATEKEYBLOB, are used to store private keys outside a CSP.
     * Base provider private-key BLOBs have the following format:
     *
     * PUBLICKEYSTRUC  publickeystruc ;
     * RSAPUBKEY rsapubkey;
     * BYTE modulus[rsapubkey.bitlen/8];                1/8
     * BYTE prime1[rsapubkey.bitlen/16];                1/16
     * BYTE prime2[rsapubkey.bitlen/16];                1/16
     * BYTE exponent1[rsapubkey.bitlen/16];             1/16
     * BYTE exponent2[rsapubkey.bitlen/16];             1/16
     * BYTE coefficient[rsapubkey.bitlen/16];           1/16
     * BYTE privateExponent[rsapubkey.bitlen/8];        1/8
     */
    if(keyBlobLen < sizeof(PUBLICKEYSTRUC) + sizeof(RSAPUBKEY) + bitLen / 2 + bitLen / 16) {
        xmlSecError(XMLSEC_ERRORS_HERE,
                    NULL,
                    "CryptExportKey",
                    XMLSEC_ERRORS_R_CRYPTO_FAILED,
                    "len=%ld", keyBlobLen);
        goto done;
    }
    ptr = (BYTE*)(keyBlob + sizeof(PUBLICKEYSTRUC) + sizeof(RSAPUBKEY));

    /* Skip modulus, prime1, prime2 */
    ptr += bitLen / 8;
    ptr += bitLen / 16;
    ptr += bitLen / 16;

    /* Convert exponent1 to 1 */
    for (n = 0; n < (bitLen / 16); n++) {
        if (n == 0) ptr[n] = 1;
        else ptr[n] = 0;
    }
    ptr += bitLen / 16;

    /* Convert exponent2 to 1 */
    for (n = 0; n < (bitLen / 16); n++) {
        if (n == 0) ptr[n] = 1;
        else ptr[n] = 0;
    }
    ptr += bitLen / 16;

    /* Skip coefficient */
    ptr += bitLen / 16;

    /* Convert privateExponent to 1 */
    for (n = 0; n < (bitLen / 16); n++) {
        if (n == 0) ptr[n] = 1;
        else ptr[n] = 0;
    }

    /* Import the exponent-of-one private key. */
    if (!CryptImportKey(hProv, keyBlob, keyBlobLen, 0, 0, &hKey)) {
        xmlSecError(XMLSEC_ERRORS_HERE,
                    NULL,
                    "CryptImportKey",
                    XMLSEC_ERRORS_R_CRYPTO_FAILED,
                    XMLSEC_ERRORS_NO_MESSAGE);
        goto done;
    }
    (*hPrivateKey) = hKey;
    hKey = 0;
    res = TRUE;

done:
    if(keyBlob != NULL) {
        xmlFree(keyBlob);
    }
    if (hKey != 0) {
        CryptDestroyKey(hKey);
    }

    return res;
}

BOOL
xmlSecMSCryptoImportPlainSessionBlob(HCRYPTPROV hProv, HCRYPTKEY hPrivateKey,
                                     ALG_ID dwAlgId, LPBYTE pbKeyMaterial,
                                     DWORD dwKeyMaterial, BOOL bCheckKeyLength,
                                     HCRYPTKEY *hSessionKey) {
    ALG_ID dwPrivKeyAlg;
    LPBYTE keyBlob = NULL;
    DWORD keyBlobLen, rndBlobSize, dwSize, n;
    PUBLICKEYSTRUC* pubKeyStruc;
    ALG_ID* algId;
    DWORD dwPublicKeySize;
    DWORD dwProvSessionKeySize = 0;
    LPBYTE pbPtr;
    DWORD dwFlags;
    PROV_ENUMALGS_EX ProvEnum;
    HCRYPTKEY hTempKey = 0;
    BOOL fFound;
    BOOL res = FALSE;

    xmlSecAssert2(hProv != 0, FALSE);
    xmlSecAssert2(hPrivateKey != 0, FALSE);
    xmlSecAssert2(pbKeyMaterial != NULL, FALSE);
    xmlSecAssert2(dwKeyMaterial > 0, FALSE);
    xmlSecAssert2(hSessionKey != NULL, FALSE);

    /*  Double check to see if this provider supports this algorithm and key size */
    fFound = FALSE;
    dwFlags = CRYPT_FIRST;
    dwSize = sizeof(ProvEnum);
    while(CryptGetProvParam(hProv, PP_ENUMALGS_EX, (LPBYTE)&ProvEnum, &dwSize, dwFlags)) {
        if (ProvEnum.aiAlgid == dwAlgId) {
            fFound = TRUE;
            break;
        }
        dwSize = sizeof(ProvEnum);
        dwFlags = 0;
    }
    if(!fFound) {
        xmlSecError(XMLSEC_ERRORS_HERE,
                    NULL,
                    "CryptGetProvParam",
                    XMLSEC_ERRORS_R_CRYPTO_FAILED,
                    "algId=%d is not supported", dwAlgId);
        goto done;
    }

    if(bCheckKeyLength) {
        /* We have to get the key size(including padding) from an HCRYPTKEY handle.
         * PP_ENUMALGS_EX contains the key size without the padding so we can't use it.
         */
        if(!CryptGenKey(hProv, dwAlgId, 0, &hTempKey)) {
            xmlSecError(XMLSEC_ERRORS_HERE,
                        NULL,
                        "CryptGenKey",
                        XMLSEC_ERRORS_R_CRYPTO_FAILED,
                        "algId=%d", dwAlgId);
            goto done;
        }

        dwSize = sizeof(DWORD);
        if(!CryptGetKeyParam(hTempKey, KP_KEYLEN, (LPBYTE)&dwProvSessionKeySize, &dwSize, 0)) {
            xmlSecError(XMLSEC_ERRORS_HERE,
                        NULL,
                        "CryptGetKeyParam(KP_KEYLEN)",
                        XMLSEC_ERRORS_R_CRYPTO_FAILED,
                        "algId=%d", dwAlgId);
            goto done;
        }
        CryptDestroyKey(hTempKey);
        hTempKey = 0;

        /* yell if key is too big */
        if ((dwKeyMaterial * 8) > dwProvSessionKeySize) {
            xmlSecError(XMLSEC_ERRORS_HERE,
                        NULL,
                        NULL,
                        XMLSEC_ERRORS_R_INVALID_SIZE,
                        "dwKeyMaterial=%ld;dwProvSessionKeySize=%ld",
                        dwKeyMaterial, dwProvSessionKeySize);
            goto done;
        }
    } else {
        dwProvSessionKeySize = dwKeyMaterial * 8;
    }

    /* Get private key's algorithm */
    dwSize = sizeof(ALG_ID);
    if(!CryptGetKeyParam(hPrivateKey, KP_ALGID, (LPBYTE)&dwPrivKeyAlg, &dwSize, 0)) {
        xmlSecError(XMLSEC_ERRORS_HERE,
                    NULL,
                    "CryptGetKeyParam(KP_ALGID)",
                    XMLSEC_ERRORS_R_CRYPTO_FAILED,
                    "algId=%d", dwAlgId);
        goto done;
    }

    /* Get private key's length in bits */
    dwSize = sizeof(DWORD);
    if(!CryptGetKeyParam(hPrivateKey, KP_KEYLEN, (LPBYTE)&dwPublicKeySize, &dwSize, 0)) {
        xmlSecError(XMLSEC_ERRORS_HERE,
                    NULL,
                    "CryptGetKeyParam(KP_KEYLEN)",
                    XMLSEC_ERRORS_R_CRYPTO_FAILED,
                    "algId=%d", dwAlgId);
        goto done;
    }

    /* 3 is for the first reserved byte after the key material and the 2 reserved bytes at the end. */
    if(dwPublicKeySize / 8 < dwKeyMaterial + 3) {
        xmlSecError(XMLSEC_ERRORS_HERE,
                    NULL,
                    NULL,
                    XMLSEC_ERRORS_R_INVALID_SIZE,
                    "dwKeyMaterial=%ld;dwPublicKeySize=%ld",
                    dwKeyMaterial, dwPublicKeySize);
        goto done;
    }
    rndBlobSize = dwPublicKeySize / 8 - (dwKeyMaterial + 3);

    /* Simple key BLOBs, type SIMPLEBLOB, are used to store and transport session keys outside a CSP.
     * Base provider simple-key BLOBs are always encrypted with a key exchange public key. The pbData
     * member of the SIMPLEBLOB is a sequence of bytes in the following format:
     *
     * PUBLICKEYSTRUC  publickeystruc ;
     * ALG_ID algid;
     * BYTE encryptedkey[rsapubkey.bitlen/8];
     */

    /* calculate Simple blob's length */
    keyBlobLen = sizeof(PUBLICKEYSTRUC) + sizeof(ALG_ID) + (dwPublicKeySize / 8);

    /* allocate simple blob buffer */
    keyBlob = (LPBYTE)xmlMalloc(sizeof(BYTE) * keyBlobLen);
    if(keyBlob == NULL) {
        xmlSecError(XMLSEC_ERRORS_HERE,
                    NULL,
                    NULL,
                    XMLSEC_ERRORS_R_MALLOC_FAILED,
                    XMLSEC_ERRORS_NO_MESSAGE);
        goto done;
    }
    memset(keyBlob, 0, keyBlobLen);

    /* initialize PUBLICKEYSTRUC */
    pubKeyStruc             = (PUBLICKEYSTRUC*)(keyBlob);
    pubKeyStruc->bType      = SIMPLEBLOB;
    pubKeyStruc->bVersion   = 0x02;
    pubKeyStruc->reserved   = 0;
    pubKeyStruc->aiKeyAlg   = dwAlgId;

    /* Copy private key algorithm to buffer */
    algId                   = (ALG_ID*)(keyBlob + sizeof(PUBLICKEYSTRUC));
    (*algId)                = dwPrivKeyAlg;

    /* Place the key material in reverse order */
    pbPtr                   = (BYTE*)(keyBlob + sizeof(PUBLICKEYSTRUC) + sizeof(ALG_ID));
    for (n = 0; n < dwKeyMaterial; n++) {
        pbPtr[n] = pbKeyMaterial[dwKeyMaterial - n - 1];
    }
    pbPtr += dwKeyMaterial;

    /* skip reserved byte */
    pbPtr += 1;

    /* Generate random data for the rest of the buffer */
    if((rndBlobSize > 0) && !CryptGenRandom(hProv, rndBlobSize, pbPtr)) {
        xmlSecError(XMLSEC_ERRORS_HERE,
                    NULL,
                    "CryptGenRandom",
                    XMLSEC_ERRORS_R_CRYPTO_FAILED,
                    "rndBlobSize=%ld", rndBlobSize);
        goto done;
    }
    /* aleksey: why are we doing this? */
    for (n = 0; n < rndBlobSize; n++) {
        if (pbPtr[n] == 0) pbPtr[n] = 1;
    }

    /* set magic number at the end */
    keyBlob[keyBlobLen - 2] = 2;

    if(!CryptImportKey(hProv, keyBlob , keyBlobLen, hPrivateKey, CRYPT_EXPORTABLE, hSessionKey)) {
        xmlSecError(XMLSEC_ERRORS_HERE,
                    NULL,
                    "CryptImportKey",
                    XMLSEC_ERRORS_R_CRYPTO_FAILED,
                    "algId=%d", dwAlgId);
        goto done;
    }

    /* success */
    res = TRUE;

done:
    if(hTempKey != 0) {
        CryptDestroyKey(hTempKey);
    }
    if(keyBlob != NULL) {
        xmlFree(keyBlob);
    }
    return(res);
}

#ifndef XMLSEC_NO_AES
/**************************************************************************
 *
 * <xmlsec:AESKeyValue> processing
 *
 *************************************************************************/
static xmlSecKeyDataKlass xmlSecMSCryptoKeyDataAesKlass = {
    sizeof(xmlSecKeyDataKlass),
    xmlSecKeyDataBinarySize,

    /* data */
    xmlSecNameAESKeyValue,
    xmlSecKeyDataUsageKeyValueNode | xmlSecKeyDataUsageRetrievalMethodNodeXml,
                                                /* xmlSecKeyDataUsage usage; */
    xmlSecHrefAESKeyValue,                      /* const xmlChar* href; */
    xmlSecNodeAESKeyValue,                      /* const xmlChar* dataNodeName; */
    xmlSecNs,                                   /* const xmlChar* dataNodeNs; */

    /* constructors/destructor */
    xmlSecMSCryptoSymKeyDataInitialize,         /* xmlSecKeyDataInitializeMethod initialize; */
    xmlSecMSCryptoSymKeyDataDuplicate,          /* xmlSecKeyDataDuplicateMethod duplicate; */
    xmlSecMSCryptoSymKeyDataFinalize,           /* xmlSecKeyDataFinalizeMethod finalize; */
    xmlSecMSCryptoSymKeyDataGenerate,           /* xmlSecKeyDataGenerateMethod generate; */

    /* get info */
    xmlSecMSCryptoSymKeyDataGetType,            /* xmlSecKeyDataGetTypeMethod getType; */
    xmlSecMSCryptoSymKeyDataGetSize,            /* xmlSecKeyDataGetSizeMethod getSize; */
    NULL,                                       /* xmlSecKeyDataGetIdentifier getIdentifier; */

    /* read/write */
    xmlSecMSCryptoSymKeyDataXmlRead,            /* xmlSecKeyDataXmlReadMethod xmlRead; */
    xmlSecMSCryptoSymKeyDataXmlWrite,           /* xmlSecKeyDataXmlWriteMethod xmlWrite; */
    xmlSecMSCryptoSymKeyDataBinRead,            /* xmlSecKeyDataBinReadMethod binRead; */
    xmlSecMSCryptoSymKeyDataBinWrite,           /* xmlSecKeyDataBinWriteMethod binWrite; */

    /* debug */
    xmlSecMSCryptoSymKeyDataDebugDump,          /* xmlSecKeyDataDebugDumpMethod debugDump; */
    xmlSecMSCryptoSymKeyDataDebugXmlDump,       /* xmlSecKeyDataDebugDumpMethod debugXmlDump; */

    /* reserved for the future */
    NULL,                                       /* void* reserved0; */
    NULL,                                       /* void* reserved1; */
};

/**
 * xmlSecMSCryptoKeyDataAesGetKlass:
 *
 * The AES key data klass.
 *
 * Returns: AES key data klass.
 */
xmlSecKeyDataId
xmlSecMSCryptoKeyDataAesGetKlass(void) {
    return(&xmlSecMSCryptoKeyDataAesKlass);
}

/**
 * xmlSecMSCryptoKeyDataAesSet:
 * @data:               the pointer to AES key data.
 * @buf:                the pointer to key value.
 * @bufSize:            the key value size (in bytes).
 *
 * Sets the value of AES key data.
 *
 * Returns: 0 on success or a negative value if an error occurs.
 */
int
xmlSecMSCryptoKeyDataAesSet(xmlSecKeyDataPtr data, const xmlSecByte* buf, xmlSecSize bufSize) {
    xmlSecBufferPtr buffer;

    xmlSecAssert2(xmlSecKeyDataCheckId(data, xmlSecMSCryptoKeyDataAesId), -1);
    xmlSecAssert2(buf != NULL, -1);
    xmlSecAssert2(bufSize > 0, -1);

    buffer = xmlSecKeyDataBinaryValueGetBuffer(data);
    xmlSecAssert2(buffer != NULL, -1);

    return(xmlSecBufferSetData(buffer, buf, bufSize));
}
#endif /* XMLSEC_NO_AES */

#ifndef XMLSEC_NO_DES
/**************************************************************************
 *
 * <xmlsec:DESKeyValue> processing
 *
 *************************************************************************/
static xmlSecKeyDataKlass xmlSecMSCryptoKeyDataDesKlass = {
    sizeof(xmlSecKeyDataKlass),
    xmlSecKeyDataBinarySize,

    /* data */
    xmlSecNameDESKeyValue,
    xmlSecKeyDataUsageKeyValueNode | xmlSecKeyDataUsageRetrievalMethodNodeXml,
                                                /* xmlSecKeyDataUsage usage; */
    xmlSecHrefDESKeyValue,                      /* const xmlChar* href; */
    xmlSecNodeDESKeyValue,                      /* const xmlChar* dataNodeName; */
    xmlSecNs,                                   /* const xmlChar* dataNodeNs; */

    /* constructors/destructor */
    xmlSecMSCryptoSymKeyDataInitialize,         /* xmlSecKeyDataInitializeMethod initialize; */
    xmlSecMSCryptoSymKeyDataDuplicate,          /* xmlSecKeyDataDuplicateMethod duplicate; */
    xmlSecMSCryptoSymKeyDataFinalize,           /* xmlSecKeyDataFinalizeMethod finalize; */
    xmlSecMSCryptoSymKeyDataGenerate,           /* xmlSecKeyDataGenerateMethod generate; */

    /* get info */
    xmlSecMSCryptoSymKeyDataGetType,            /* xmlSecKeyDataGetTypeMethod getType; */
    xmlSecMSCryptoSymKeyDataGetSize,            /* xmlSecKeyDataGetSizeMethod getSize; */
        NULL,                                   /* xmlSecKeyDataGetIdentifier getIdentifier; */

    /* read/write */
    xmlSecMSCryptoSymKeyDataXmlRead,            /* xmlSecKeyDataXmlReadMethod xmlRead; */
    xmlSecMSCryptoSymKeyDataXmlWrite,           /* xmlSecKeyDataXmlWriteMethod xmlWrite; */
    xmlSecMSCryptoSymKeyDataBinRead,            /* xmlSecKeyDataBinReadMethod binRead; */
    xmlSecMSCryptoSymKeyDataBinWrite,           /* xmlSecKeyDataBinWriteMethod binWrite; */

    /* debug */
    xmlSecMSCryptoSymKeyDataDebugDump,          /* xmlSecKeyDataDebugDumpMethod debugDump; */
    xmlSecMSCryptoSymKeyDataDebugXmlDump,       /* xmlSecKeyDataDebugDumpMethod debugXmlDump; */

    /* reserved for the future */
    NULL,                                       /* void* reserved0; */
    NULL,                                       /* void* reserved1; */
};

/**
 * xmlSecMSCryptoKeyDataDesGetKlass:
 *
 * The DES key data klass.
 *
 * Returns: DES key data klass.
 */
xmlSecKeyDataId
xmlSecMSCryptoKeyDataDesGetKlass(void) {
    return(&xmlSecMSCryptoKeyDataDesKlass);
}
#endif /* XMLSEC_NO_DES */

#ifndef XMLSEC_NO_HMAC
/**************************************************************************
 *
 * <xmlsec:HMACKeyValue> processing
 *
 *************************************************************************/
static xmlSecKeyDataKlass xmlSecMSCryptoKeyDataHmacKlass = {
    sizeof(xmlSecKeyDataKlass),
    xmlSecKeyDataBinarySize,

    /* data */
    xmlSecNameHMACKeyValue,
    xmlSecKeyDataUsageKeyValueNode | xmlSecKeyDataUsageRetrievalMethodNodeXml,
                                                /* xmlSecKeyDataUsage usage; */
    xmlSecHrefHMACKeyValue,                     /* const xmlChar* href; */
    xmlSecNodeHMACKeyValue,                     /* const xmlChar* dataNodeName; */
    xmlSecNs,                                   /* const xmlChar* dataNodeNs; */

    /* constructors/destructor */
    xmlSecMSCryptoSymKeyDataInitialize,         /* xmlSecKeyDataInitializeMethod initialize; */
    xmlSecMSCryptoSymKeyDataDuplicate,          /* xmlSecKeyDataDuplicateMethod duplicate; */
    xmlSecMSCryptoSymKeyDataFinalize,           /* xmlSecKeyDataFinalizeMethod finalize; */
    xmlSecMSCryptoSymKeyDataGenerate,           /* xmlSecKeyDataGenerateMethod generate; */

    /* get info */
    xmlSecMSCryptoSymKeyDataGetType,            /* xmlSecKeyDataGetTypeMethod getType; */
    xmlSecMSCryptoSymKeyDataGetSize,            /* xmlSecKeyDataGetSizeMethod getSize; */
        NULL,                                   /* xmlSecKeyDataGetIdentifier getIdentifier; */

    /* read/write */
    xmlSecMSCryptoSymKeyDataXmlRead,            /* xmlSecKeyDataXmlReadMethod xmlRead; */
    xmlSecMSCryptoSymKeyDataXmlWrite,           /* xmlSecKeyDataXmlWriteMethod xmlWrite; */
    xmlSecMSCryptoSymKeyDataBinRead,            /* xmlSecKeyDataBinReadMethod binRead; */
    xmlSecMSCryptoSymKeyDataBinWrite,           /* xmlSecKeyDataBinWriteMethod binWrite; */

    /* debug */
    xmlSecMSCryptoSymKeyDataDebugDump,          /* xmlSecKeyDataDebugDumpMethod debugDump; */
    xmlSecMSCryptoSymKeyDataDebugXmlDump,       /* xmlSecKeyDataDebugDumpMethod debugXmlDump; */

    /* reserved for the future */
    NULL,                                       /* void* reserved0; */
    NULL,                                       /* void* reserved1; */
};

/**
 * xmlSecMSCryptoKeyDataHmacGetKlass:
 *
 * The HMAC key data klass.
 *
 * Returns: HMAC key data klass.
 */
xmlSecKeyDataId
xmlSecMSCryptoKeyDataHmacGetKlass(void) {
    return(&xmlSecMSCryptoKeyDataHmacKlass);
}

/**
 * xmlSecMSCryptoKeyDataHmacSet:
 * @data:               the pointer to HMAC key data.
 * @buf:                the pointer to key value.
 * @bufSize:            the key value size (in bytes).
 *
 * Sets the value of HMAC key data.
 *
 * Returns: 0 on success or a negative value if an error occurs.
 */
int
xmlSecMSCryptoKeyDataHmacSet(xmlSecKeyDataPtr data, const xmlSecByte* buf, xmlSecSize bufSize) {
    xmlSecBufferPtr buffer;

    xmlSecAssert2(xmlSecKeyDataCheckId(data, xmlSecMSCryptoKeyDataHmacId), -1);
    xmlSecAssert2(buf != NULL, -1);
    xmlSecAssert2(bufSize > 0, -1);

    buffer = xmlSecKeyDataBinaryValueGetBuffer(data);
    xmlSecAssert2(buffer != NULL, -1);

    return(xmlSecBufferSetData(buffer, buf, bufSize));
}


#endif /* XMLSEC_NO_HMAC */