1
+ #if SECURITY_DEP
2
+ using System . Security . Cryptography . X509Certificates ;
3
+
4
+ namespace Mono . Unity
5
+ {
6
+ internal unsafe static class CertHelper
7
+ {
8
+ public static void AddCertificatesToNativeChain ( UnityTls . unitytls_x509list * nativeCertificateChain , X509CertificateCollection certificates , UnityTls . unitytls_errorstate * errorState )
9
+ {
10
+ foreach ( var certificate in certificates ) {
11
+ AddCertificateToNativeChain ( nativeCertificateChain , certificate , errorState ) ;
12
+ }
13
+ }
14
+
15
+ public static void AddCertificateToNativeChain ( UnityTls . unitytls_x509list * nativeCertificateChain , X509Certificate certificate , UnityTls . unitytls_errorstate * errorState )
16
+ {
17
+ byte [ ] certDer = certificate . GetRawCertData ( ) ;
18
+ fixed( byte * certDerPtr = certDer ) {
19
+ UnityTls . NativeInterface . unitytls_x509list_append_der ( nativeCertificateChain , certDerPtr , certDer . Length , errorState ) ;
20
+ }
21
+
22
+ var certificateImpl2 = certificate . Impl as X509Certificate2Impl ;
23
+ if ( certificateImpl2 != null ) {
24
+ var intermediates = certificateImpl2 . IntermediateCertificates ;
25
+ if ( intermediates != null && intermediates . Count > 0 ) {
26
+ for ( int i = 0 ; i < intermediates . Count ; ++ i ) {
27
+ AddCertificateToNativeChain ( nativeCertificateChain , new X509Certificate ( intermediates [ i ] ) , errorState ) ;
28
+ }
29
+ }
30
+ }
31
+ }
32
+
33
+ public static X509CertificateCollection NativeChainToManagedCollection ( UnityTls . unitytls_x509list_ref nativeCertificateChain , UnityTls . unitytls_errorstate * errorState )
34
+ {
35
+ X509CertificateCollection certificates = new X509CertificateCollection ( ) ;
36
+
37
+ var cert = UnityTls . NativeInterface . unitytls_x509list_get_x509 ( nativeCertificateChain , 0 , errorState ) ;
38
+ for ( int i = 0 ; cert . handle != UnityTls . NativeInterface . UNITYTLS_INVALID_HANDLE ; ++ i ) {
39
+ size_t certBufferSize = UnityTls . NativeInterface . unitytls_x509_export_der ( cert , null , 0 , errorState ) ;
40
+ var certBuffer = new byte [ certBufferSize ] ; // Need to reallocate every time since X509Certificate constructor takes no length but only a byte array.
41
+ fixed( byte * certBufferPtr = certBuffer ) {
42
+ UnityTls . NativeInterface . unitytls_x509_export_der ( cert , certBufferPtr , certBufferSize , errorState ) ;
43
+ }
44
+ certificates . Add ( new X509Certificate ( certBuffer ) ) ;
45
+
46
+ cert = UnityTls . NativeInterface . unitytls_x509list_get_x509 ( nativeCertificateChain , i , errorState ) ;
47
+ }
48
+
49
+ return certificates ;
50
+ }
51
+ }
52
+ }
53
+ #endif
0 commit comments