2017-05-27 3 views
5

J'essaie d'obtenir un X509Certificate2 d'un BountyCastle X509Certificate et un PKCS12. J'utilise le code suivant:BouncyCastle longueur indéfinie ASN1

certificate = new X509Certificate2(rawData, password, storageFlags); 

je produis le rawData, comme ce qui suit:

using (MemoryStream pfxData = new MemoryStream()) 
{ 
    X509CertificateEntry[] chain = new X509CertificateEntry[1]; 

    chain[0] = new X509CertificateEntry(x509); 
    pkcsStore.SetKeyEntry(applicationName, new AsymmetricKeyEntry(subjectKeyPair.Private), chain); 
    pkcsStore.Save(pfxData, passcode.ToCharArray(), random); 
    var rawData = pfx.ToArray(); 
} 

Le problème est que je reçois l'exception suivante:

enter image description here

Après J'ai compris, quelques jours de recherches, que le problème est basé sur l'implémentation mono de ASN1. Cette implémentation n'autorise pas "Encodage de longueur indéfini". Si j'utilise le code sur Windows cela fonctionne très bien.

Ma question

Est-il possible, pour convertir le flux pfxData à une structure ASN1 valide?

Je l'ai essayé avec le code suivant:

Asn1InputStream asn1InputStream = new Asn1InputStream(pfxData); 
var asn1Object = asn1InputStream.ReadObject(); 

MemoryStream memoryStream = new MemoryStream(); 
new Asn1OutputStream((Stream)memoryStream).WriteObject(asn1Object); 
var asn1ByteArray = memoryStream.ToArray(); 

certificate = new X509Certificate2(asn1ByteArray); 

Mais avec ce code, je reçois l'exception suivante:

"Index was out of range. Must be non-negative and less than the size of the collection.\nParameter name: startIndex"

J'utilise Xamarin PCL avec la norme .NET 1.3 et je peux n'utilisez que le paquet Nuget "Portable.BouncyCastle".

UPDATE Exception Stack Trace (Conversion BER à DER):

05-28 15:19:54.895 D/Mono (3808): Assembly Ref addref Mono.Security[0x9b4fe080] -> System[0xac8de400]: 17 
05-28 15:19:54.957 I/mono-stdout(3808): System.AggregateException: One or more errors occurred. ---> System.Security.Cryptography.CryptographicException: Unable to decode certificate. ---> System.Security.Cryptography.CryptographicException: Input data cannot be coded as a valid certificate. ---> System.ArgumentOutOfRangeException: Index was out of range. Must be non-negative and less than the size of the collection. 
System.AggregateException: One or more errors occurred. ---> System.Security.Cryptography.CryptographicException: Unable to decode certificate. ---> System.Security.Cryptography.CryptographicException: Input data cannot be coded as a valid certificate. ---> System.ArgumentOutOfRangeException: Index was out of range. Must be non-negative and less than the size of the collection. 
Parameter name: startIndex 
    at System.String.IndexOf (System.String value, System.Int32 startIndex, System.Int32 count, System.StringComparison comparisonType) [0x0002a] in <d18287e1d683419a8ec3216fd78947b9>:0 
    at System.String.IndexOf (System.String value, System.Int32 startIndex, System.StringComparison comparisonType) [0x00009] in <d18287e1d683419a8ec3216fd78947b9>:0 
    at System.String.IndexOf (System.String value, System.Int32 startIndex) [0x00000] in <d18287e1d683419a8ec3216fd78947b9>:0 
    at Mono.Security.X509.X509Certificate.PEM (System.String type, System.Byte[] data) [0x00030] in <2940be14d5a1446694e2193e9029b558>:0 
    at Mono.Security.X509.X509Certificate..ctor (System.Byte[] data) [0x00014] in <2940be14d5a1446694e2193e9029b558>:0 
    --- End of inner exception stack trace --- 
    at Mono.Security.X509.X509Certificate..ctor (System.Byte[] data) [0x0002f] in <2940be14d5a1446694e2193e9029b558>:0 
05-28 15:19:54.958 I/mono-stdout(3808): Parameter name: startIndex 
    at System.Security.Cryptography.X509Certificates.X509Certificate2ImplMono.Import (System.Byte[] rawData, System.String password, System.Security.Cryptography.X509Certificates.X509KeyStorageFlags keyStorageFlags) [0x0000b] in <1a27f8ea09e3480db932cbde0eaedfb2>:0 
    --- End of inner exception stack trace --- 
    at System.Security.Cryptography.X509Certificates.X509Certificate2ImplMono.Import (System.Byte[] rawData, System.String password, System.Security.Cryptography.X509Certificates.X509KeyStorageFlags keyStorageFlags) [0x00031] in <1a27f8ea09e3480db932cbde0eaedfb2>:0 
    at System.Security.Cryptography.X509Certificates.X509Helper2.Import (System.Byte[] rawData, System.String password, System.Security.Cryptography.X509Certificates.X509KeyStorageFlags keyStorageFlags, System.Boolean disableProvider) [0x00020] in <1a27f8ea09e3480db932cbde0eaedfb2>:0 
    at System.Security.Cryptography.X509Certificates.X509Certificate2.Import (System.Byte[] rawData, System.String password, System.Security.Cryptography.X509Certificates.X509KeyStorageFlags keyStorageFlags) [0x00000] in <1a27f8ea09e3480db932cbde0eaedfb2>:0 
    at System.Security.Cryptography.X509Certificates.X509Certificate2..ctor (System.Byte[] rawData) [0x00011] in <1a27f8ea09e3480db932cbde0eaedfb2>:0 
05-28 15:19:54.958 I/mono-stdout(3808): at System.String.IndexOf (System.String value, System.Int32 startIndex, System.Int32 count, System.StringComparison comparisonType) [0x0002a] in <d18287e1d683419a8ec3216fd78947b9>:0 
    at APP.Models.Services.ACommunicationService.CreateCertificate (System.String storeType, System.String storePath, System.String password, System.String applicationUri, System.String applicationName, System.String subjectName, System.Collections.Generic.IList`1[T] domainNames, System.UInt16 keySize, System.DateTime startTime, System.UInt16 lifetimeInMonths, System.UInt16 hashSizeInBits, System.Boolean isCA, System.Security.Cryptography.X509Certificates.X509Certificate2 issuerCAKeyCert) [0x003b5] in C:\projects\APP - Kopie\APP_XamarinApplication\APP\APP\APP\Models\Services\ACommunicationService.cs:517 
05-28 15:19:54.958 I/mono-stdout(3808): at System.String.IndexOf (System.String value, System.Int32 startIndex, System.StringComparison comparisonType) [0x00009] in <d18287e1d683419a8ec3216fd78947b9>:0 
    at APP.Models.Services.ACommunicationService.CreateCertificate (System.String storeType, System.String storePath, System.String applicationUri, System.String applicationName, System.String subjectName, System.Collections.Generic.IList`1[T] serverDomainNames, System.UInt16 keySize, System.UInt16 lifetimeInMonths, System.UInt16 hashSizeInBits) [0x00001] in C:\projects\APP - Kopie\APP_XamarinApplication\APP\APP\APP\Models\Services\ACommunicationService.cs:318 
    at APP.Models.Services.ACommunicationService+<ACommunicationServiceAsync>d__18.MoveNext() [0x00972] in C:\projects\APP - Kopie\APP_XamarinApplication\APP\APP\APP\Models\Services\ACommunicationService.cs:214 
    --- End of inner exception stack trace --- 
05-28 15:19:54.959 I/mono-stdout(3808): at System.String.IndexOf (System.String value, System.Int32 startIndex) [0x00000] in <d18287e1d683419a8ec3216fd78947b9>:0 
    at System.Threading.Tasks.Task.ThrowIfExceptional (System.Boolean includeTaskCanceledExceptions) [0x00011] in <d18287e1d683419a8ec3216fd78947b9>:0 
    at System.Threading.Tasks.Task.Wait (System.Int32 millisecondsTimeout, System.Threading.CancellationToken cancellationToken) [0x00043] in <d18287e1d683419a8ec3216fd78947b9>:0 
    at System.Threading.Tasks.Task.Wait() [0x00000] in <d18287e1d683419a8ec3216fd78947b9>:0 
    at APP.Models.Services.ACommunicationService..ctor (PCLStorage.IFolder rootFolder) [0x00010] in C:\projects\APP - Kopie\APP_XamarinApplication\APP\APP\APP\Models\Services\ACommunicationService.cs:46 
05-28 15:19:54.959 I/mono-stdout(3808): at Mono.Security.X509.X509Certificate.PEM (System.String type, System.Byte[] data) [0x00030] in <2940be14d5a1446694e2193e9029b558>:0 
05-28 15:19:54.959 I/mono-stdout(3808): at Mono.Security.X509.X509Certificate..ctor (System.Byte[] data) [0x00014] in <2940be14d5a1446694e2193e9029b558>:0 
05-28 15:19:54.959 I/mono-stdout(3808): --- End of inner exception stack trace --- 
05-28 15:19:54.959 I/mono-stdout(3808): at Mono.Security.X509.X509Certificate..ctor (System.Byte[] data) [0x0002f] in <2940be14d5a1446694e2193e9029b558>:0 
05-28 15:19:54.959 I/mono-stdout(3808): at System.Security.Cryptography.X509Certificates.X509Certificate2ImplMono.Import (System.Byte[] rawData, System.String password, System.Security.Cryptography.X509Certificates.X509KeyStorageFlags keyStorageFlags) [0x0000b] in <1a27f8ea09e3480db932cbde0eaedfb2>:0 
---> (Inner Exception #0) System.Security.Cryptography.CryptographicException: Unable to decode certificate. ---> System.Security.Cryptography.CryptographicException: Input data cannot be coded as a valid certificate. ---> System.ArgumentOutOfRangeException: Index was out of range. Must be non-negative and less than the size of the collection. 
05-28 15:19:54.961 I/mono-stdout(3808): --- End of inner exception stack trace --- 
05-28 15:19:54.961 I/mono-stdout(3808): at System.Security.Cryptography.X509Certificates.X509Certificate2ImplMono.Import (System.Byte[] rawData, System.String password, System.Security.Cryptography.X509Certificates.X509KeyStorageFlags keyStorageFlags) [0x00031] in <1a27f8ea09e3480db932cbde0eaedfb2>:0 
05-28 15:19:54.961 I/mono-stdout(3808): at System.Security.Cryptography.X509Certificates.X509Helper2.Import (System.Byte[] rawData, System.String password, System.Security.Cryptography.X509Certificates.X509KeyStorageFlags keyStorageFlags, System.Boolean disableProvider) [0x00020] in <1a27f8ea09e3480db932cbde0eaedfb2>:0 
05-28 15:19:54.962 I/mono-stdout(3808): at System.Security.Cryptography.X509Certificates.X509Certificate2.Import (System.Byte[] rawData, System.String password, System.Security.Cryptography.X509Certificates.X509KeyStorageFlags keyStorageFlags) [0x00000] in <1a27f8ea09e3480db932cbde0eaedfb2>:0 
05-28 15:19:54.962 I/mono-stdout(3808): at System.Security.Cryptography.X509Certificates.X509Certificate2..ctor (System.Byte[] rawData) [0x00011] in <1a27f8ea09e3480db932cbde0eaedfb2>:0 
Parameter name: startIndex 
05-28 15:19:54.963 I/mono-stdout(3808): at APP.Models.Services.ACommunicationService.CreateCertificate (System.String storeType, System.String storePath, System.String password, System.String applicationUri, System.String applicationName, System.String subjectName, System.Collections.Generic.IList`1[T] domainNames, System.UInt16 keySize, System.DateTime startTime, System.UInt16 lifetimeInMonths, System.UInt16 hashSizeInBits, System.Boolean isCA, System.Security.Cryptography.X509Certificates.X509Certificate2 issuerCAKeyCert) [0x003b5] in C:\projects\APP - Kopie\APP_XamarinApplication\APP\APP\APP\Models\Services\ACommunicationService.cs:517 
05-28 15:19:54.963 I/mono-stdout(3808): at APP.Models.Services.ACommunicationService.CreateCertificate (System.String storeType, System.String storePath, System.String applicationUri, System.String applicationName, System.String subjectName, System.Collections.Generic.IList`1[T] serverDomainNames, System.UInt16 keySize, System.UInt16 lifetimeInMonths, System.UInt16 hashSizeInBits) [0x00001] in C:\projects\APP - Kopie\APP_XamarinApplication\APP\APP\APP\Models\Services\ACommunicationService.cs:318 
05-28 15:19:54.964 I/mono-stdout(3808): at APP.Models.Services.ACommunicationService+<ACommunicationServiceAsync>d__18.MoveNext() [0x00972] in C:\projects\APP - Kopie\APP_XamarinApplication\APP\APP\APP\Models\Services\ACommunicationService.cs:214 
05-28 15:19:54.964 I/mono-stdout(3808): --- End of inner exception stack trace --- 
05-28 15:19:54.965 I/mono-stdout(3808): at System.Threading.Tasks.Task.ThrowIfExceptional (System.Boolean includeTaskCanceledExceptions) [0x00011] in <d18287e1d683419a8ec3216fd78947b9>:0 
05-28 15:19:54.965 I/mono-stdout(3808): at System.Threading.Tasks.Task.Wait (System.Int32 millisecondsTimeout, System.Threading.CancellationToken cancellationToken) [0x00043] in <d18287e1d683419a8ec3216fd78947b9>:0 
05-28 15:19:54.965 I/mono-stdout(3808): at System.Threading.Tasks.Task.Wait() [0x00000] in <d18287e1d683419a8ec3216fd78947b9>:0 
    at System.String.IndexOf (System.String value, System.Int32 startIndex, System.Int32 count, System.StringComparison comparisonType) [0x0002a] in <d18287e1d683419a8ec3216fd78947b9>:0 
05-28 15:19:54.965 I/mono-stdout(3808): at APP.Models.Services.ACommunicationService..ctor (PCLStorage.IFolder rootFolder) [0x00010] in C:\projects\APP - Kopie\APP_XamarinApplication\APP\APP\APP\Models\Services\ACommunicationService.cs:46 
05-28 15:19:54.966 I/mono-stdout(3808): ---> (Inner Exception #0) System.Security.Cryptography.CryptographicException: Unable to decode certificate. ---> System.Security.Cryptography.CryptographicException: Input data cannot be coded as a valid certificate. ---> System.ArgumentOutOfRangeException: Index was out of range. Must be non-negative and less than the size of the collection. 
05-28 15:19:54.966 I/mono-stdout(3808): Parameter name: startIndex 
05-28 15:19:54.967 I/mono-stdout(3808): at System.String.IndexOf (System.String value, System.Int32 startIndex, System.Int32 count, System.StringComparison comparisonType) [0x0002a] in <d18287e1d683419a8ec3216fd78947b9>:0 
    at System.String.IndexOf (System.String value, System.Int32 startIndex, System.StringComparison comparisonType) [0x00009] in <d18287e1d683419a8ec3216fd78947b9>:0 
    at System.String.IndexOf (System.String value, System.Int32 startIndex) [0x00000] in <d18287e1d683419a8ec3216fd78947b9>:0 
    at Mono.Security.X509.X509Certificate.PEM (System.String type, System.Byte[] data) [0x00030] in <2940be14d5a1446694e2193e9029b558>:0 
    at Mono.Security.X509.X509Certificate..ctor (System.Byte[] data) [0x00014] in <2940be14d5a1446694e2193e9029b558>:0 
    --- End of inner exception stack trace --- 
    at Mono.Security.X509.X509Certificate..ctor (System.Byte[] data) [0x0002f] in <2940be14d5a1446694e2193e9029b558>:0 
    at System.Security.Cryptography.X509Certificates.X509Certificate2ImplMono.Import (System.Byte[] rawData, System.String password, System.Security.Cryptography.X509Certificates.X509KeyStorageFlags keyStorageFlags) [0x0000b] in <1a27f8ea09e3480db932cbde0eaedfb2>:0 
    --- End of inner exception stack trace --- 
    at System.Security.Cryptography.X509Certificates.X509Certificate2ImplMono.Import (System.Byte[] rawData, System.String password, System.Security.Cryptography.X509Certif 
icates.X509KeyStorageFlags keyStorageFlags) [0x00031] in <1a27f8ea09e3480db932cbde0eaedfb2>:0 
    at System.Security.Cryptography.X509Certificates.X509Helper2.Import (System.Byte[] rawData, System.String password, System.Security.Cryptography.X509Certificates.X509KeyStorageFlags keyStorageFlags, System.Boolean disableProvider) [0x00020] in <1a27f8ea09e3480db932cbde0eaedfb2>:0 
    at System.Security.Cryptography.X509Certificates.X509Certificate2.Import (System.Byte[] rawData, System.String password, System.Security.Cryptography.X509Certificates.X509KeyStorageFlags keyStorageFlags) [0x00000] in <1a27f8ea09e3480db932cbde0eaedfb2>:0 
    at System.Security.Cryptography.X509Certificates.X509Certificate2..ctor (System.Byte[] rawData) [0x00011] in <1a27f8ea09e3480db932cbde0eaedfb2>:0 
    at APP.Models.Services.ACommunicationService.CreateCertificate (System.String storeType, System.String storePath, System.String password, System.String applicationUri, System.String applicationName, System.String subjectName, System.Collections.Generic.IList`1[T] domainNames, System.UInt16 keySize, System.DateTime startTime, 
System.UInt16 lifetimeInMonths, System.UInt16 hashSizeInBits, System.Boolean isCA, System.Security.Cryptography.X509Certificates.X509Certificate2 issuerCAKeyCert) [0x003b5] in C:\projects\APP - Kopie\APP_XamarinApplication\APP\APP\APP\Models\Services\ACommunicationService.cs:517 
    at APP.Models.Services.ACommunicationService.CreateCertificate (System.String storeType, System.String storePath, System.String applicationUri, System.String applicationName, System.String subjectName, System.Collections.Generic.IList`1[T] serverDomainNames, System.UInt16 keySize, System.UInt16 lifetimeInMonths, System.UInt16 hashSizeInBits) [0x00001] in C:\projects\APP - Kopie\APP_XamarinApplication\APP\APP\APP\Models\Services\ACommunicationService.cs:318 
    at APP.Models.Services.ACommunicationService+<ACommunicationServiceAsync>d__18.MoveNext() [0x00972] in C:\projects\APP - Kopie\APP_XamarinApplication\APP\APP\APP\Models\Services\ACommunicationService.cs:214 <--- 
05-28 15:19:54.968 I/mono-stdout(3808): at System.String.IndexOf (System.String value, System.Int32 startIndex, System.StringComparison comparisonType) [0x00009] in <d18287e1d683419a8ec3216fd78947b9>:0 
05-28 15:19:54.969 I/mono-stdout(3808): at System.String.IndexOf (System.String value, System.Int32 startIndex) [0x00000] in <d18287e1d683419a8ec3216fd78947b9>:0 
05-28 15:19:54.969 I/mono-stdout(3808): at Mono.Security.X509.X509Certificate.PEM (System.String type, System.Byte[] data) [0x00030] in <2940be14d5a1446694e2193e9029b558>:0 
05-28 15:19:54.969 I/mono-stdout(3808): at Mono.Security.X509.X509Certificate..ctor (System.Byte[] data) [0x00014] in <2940be14d5a1446694e2193e9029b558>:0 
05-28 15:19:54.969 I/mono-stdout(3808): --- End of inner exception stack trace --- 
05-28 15:19:54.969 I/mono-stdout(3808): at Mono.Security.X509.X509Certificate..ctor (System.Byte[] data) [0x0002f] in <2940be14d5a1446694e2193e9029b558>:0 
05-28 15:19:54.969 I/mono-stdout(3808): at System.Security.Cryptography.X509Certificates.X509Certificate2ImplMono.Import (System.Byte[] rawData, System.String password, System.Security.Cryptography.X509Certificates.X509KeyStorageFlags keyStorageFlags) [0x0000b] in <1a27f8ea09e3480db932cbde0eaedfb2>:0 
05-28 15:19:54.969 I/mono-stdout(3808): --- End of inner exception stack trace --- 
05-28 15:19:54.969 I/mono-stdout(3808): at System.Security.Cryptography.X509Certificates.X509Certificate2ImplMono.Import (System.Byte[] rawData, System.String password, System.Security.Cryptography.X509Certificates.X509KeyStorageFlags keyStorageFlags) [0x00031] in <1a27f8ea09e3480db932cbde0eaedfb2>:0 
05-28 15:19:54.970 I/mono-stdout(3808): at System.Security.Cryptography.X509Certificates.X509Helper2.Import (System.Byte[] rawData, System.String password, System.Security.Cryptography.X509Certificates.X509KeyStorageFlags keyStorageFlags, System.Boolean disableProvider) [0x00020] in <1a27f8ea09e3480db932cbde0eaedfb2>:0 
05-28 15:19:54.970 I/mono-stdout(3808): at System.Security.Cryptography.X509Certificates.X509Certificate2.Import (System.Byte[] rawData, System.String password, System.Security.Cryptography.X509Certificates.X509KeyStorageFlags keyStorageFlags) [0x00000] in <1a27f8ea09e3480db932cbde0eaedfb2>:0 
05-28 15:19:54.970 I/mono-stdout(3808): at System.Security.Cryptography.X509Certificates.X509Certificate2..ctor (System.Byte[] rawData) [0x00011] in <1a27f8ea09e3480db932cbde0eaedfb2>:0 
05-28 15:19:54.970 I/mono-stdout(3808): at APP.Models.Services.ACommunicationService.CreateCertificate (System.String storeType, System.String storePath, System.String password, System.String applicationUri, System.String applicationName, System.String subjectName, System.Collections.Generic.IList`1[T] domainNames, System.UInt16 keySize, System.DateTime startTime, System.UInt16 lifetimeInMonths, System.UInt16 hashSizeInBits, System.Boolean isCA, System.Security.Cryptography.X509Certificates.X509Certificate2 issuerCAKeyCert) [0x003b5] in C:\projects\APP - Kopie\APP_XamarinApplication\APP\APP\APP\Models\Services\ACommunicationService.cs:517 
05-28 15:19:54.971 I/mono-stdout(3808): at APP.Models.Services.ACommunicationService.CreateCertificate (System.String storeType, System.String storePath, System.String applicationUri, System.String applicationName, System.String subjectName, System.Collections.Generic.IList`1[T] serverDomainNames, System.UInt16 keySize, System.UInt16 lifetimeInMonths, System.UInt16 hashSizeInBits) [0x00001] in C:\projects\APP - Kopie\APP_XamarinApplication\APP\APP\APP\Models\Services\ACommunicationService.cs:318 
05-28 15:19:54.971 I/mono-stdout(3808): at APP.Models.Services.ACommunicationService+<ACommunicationServiceAsync>d__18.MoveNext() [0x00972] in C:\projects\APP - Kopie\APP_XamarinApplication\APP\APP\APP\Models\Services\ACommunicationService.cs:214 <--- 

EDIT: J'ai posté la même question dans BouncyCastle GitHub: BouncyCastle GitHub

EDIT 2: Je testé pour enregistrer le PKCS et créer un X509Certificate2 avec le constructeur de chaîne, comme suit:

var pkcsPath = pkcsStorePath + "/pkcs.p12"; 
File.WriteAllBytes(pkcsPath, pfxData.ToArray()); 

// Exception is thrown on this line (Undefined length): 
certificate = new X509Certificate2(pkcsPath, string.Empty); 

Edit 3: J'ai trouvé la méthode var util = Pkcs12Utilities.ConvertToDefiniteLength(pfxData.ToArray(), certPassword.ToCharArray()); dans la bibliothèque BouncyCastle et si j'utilise cette méthode juste avant la ligne File.WriteAllBytes(pkcsPath, util);, l'exception « encoding de longueur non définie. » est parti. Mais maintenant, je reçois l'exception suivante:

06-01 21:05:54.903 I/mono-stdout(31001): System.Security.Cryptography.CryptographicException: Input data cannot be coded as a valid certificate. ---> System.Security.Cryptography.CryptographicException: Input data cannot be coded as a valid certificate. 
System.Security.Cryptography.CryptographicException: Input data cannot be coded as a valid certificate. ---> System.Security.Cryptography.CryptographicException: Input data cannot be coded as a valid certificate. 
    at Mono.Security.X509.X509Certificate.Parse (System.Byte[] data) [0x0003b] in <2940be14d5a1446694e2193e9029b558>:0 
    --- End of inner exception stack trace --- 
    at Mono.Security.X509.X509Certificate.Parse (System.Byte[] data) [0x00322] in <2940be14d5a1446694e2193e9029b558>:0 
    at Mono.Security.X509.X509Certificate..ctor (System.Byte[] data) [0x00030] in <2940be14d5a1446694e2193e9029b558>:0 
06-01 21:05:54.905 I/mono-stdout(31001): at Mono.Security.X509.X509Certificate.Parse (System.Byte[] data) [0x0003b] in <2940be14d5a1446694e2193e9029b558>:0 
    at System.Security.Cryptography.X509Certificates.X509Certificate2ImplMono.Import (System.Byte[] rawData, System.String password, System.Security.Cryptography.X509Certificates.X509KeyStorageFlags keyStorageFlags) [0x00041] in <1a27f8ea09e3480db932cbde0eaedfb2>:0 
    at System.Security.Cryptography.X509Certificates.X509Helper2.Import (System.Byte[] rawData, System.String password, System.Security.Cryptography.X509Certificates.X509KeyStorageFlags keyStorageFlags, System.Boolean disableProvider) [0x00020] in <1a27f8ea09e3480db932cbde0eaedfb2>:0 
    at System.Security.Cryptography.X509Certificates.X509Certificate2.Import (System.Byte[] rawData, System.String password, System.Security.Cryptography.X509Certificates.X509KeyStorageFlags keyStorageFlags) [0x00000] in <1a27f8ea09e3480db932cbde0eaedfb2>:0 
    at System.Security.Cryptography.X509Certificates.X509Certificate2..ctor (System.Byte[] rawData, System.String password) [0x00011] in <1a27f8ea09e3480db932cbde0eaedfb2>:0 
    at Pkcs12TestProject.MyClass.CreateCertific 
ate (System.String storeType, System.String storePath, System.String password, System.String applicationUri, System.String applicationName, System.String subjectName, System.Collections.Generic.IList`1[T] domainNames, System.UInt16 keySize, System.DateTime startTime, System.UInt16 lifetimeInMonths, System.UInt16 hashSizeInBits, System.Boolean isCA, System.Security.Cryptography.X509Certificates.X509Certificate2 issuerCAKeyCert, System.String pkcsStorePath) [0x00377] in C:\OneDrive\VS\Pkcs12TestProject\Pkcs12TestProject\Pkcs12TestProject\MyClass.cs:223 
06-01 21:05:54.906 I/mono-stdout(31001): --- End of inner exception stack trace --- 
06-01 21:05:54.906 I/mono-stdout(31001): at Mono.Security.X509.X509Certificate.Parse (System.Byte[] data) [0x00322] in <2940be14d5a1446694e2193e9029b558>:0 
06-01 21:05:54.906 I/mono-stdout(31001): at Mono.Security.X509.X509Certificate..ctor (System.Byte[] data) [0x00030] in <2940be14d5a1446694e2193e9029b558>:0 
06-01 21:05:54.906 I/mono-stdout(31001): at System.Security.Cryptography.X509Certificates.X509Certificate2ImplMono.Import (System.Byte[] rawData, System.String password, System.Security.Cryptography.X509Certificates.X509KeyStorageFlags keyStorageFlags) [0x00041] in <1a27f8ea09e3480db932cbde0eaedfb2>:0 
06-01 21:05:54.906 I/mono-stdout(31001): at System.Security.Cryptography.X509Certificates.X509Helper2.Import (System.Byte[] rawData, System.String password, System.Security.Cryptography.X509Certificates.X509KeyStorageFlags keyStorageFlags, System.Boolean disableProvider) [0x00020] in <1a27f8ea09e3480db932cbde0eaedfb2>:0 
06-01 21:05:54.906 I/mono-stdout(31001): at System.Security.Cryptography.X509Certificates.X509Certificate2.Import (System.Byte[] rawData, System.String password, System.Security.Cryptography.X509Certificates.X509KeyStorageFlags keyStorageFlags) [0x00000] in <1a27f8ea09e3480db932cbde0eaedfb2>:0 
06-01 21:05:54.907 I/mono-stdout(31001): at System.Security.Cryptography.X509Certificates.X509Certificate2..ctor (System.Byte[] rawData, System.String password) [0x00011] in <1a27f8ea09e3480db932cbde0eaedfb2>:0 
06-01 21:05:54.907 I/mono-stdout(31001): at Pkcs12TestProject.MyClass.CreateCertificate (System.String storeType, System.String storePath, System.String password, System.String applicationUri, System.String applicationName, System.String subjectName, System.Collections.Generic.IList`1[T] domainNames, System.UInt16 keySize, System.DateTime startTime, System.UInt16 lifetimeInMonths, System.UInt16 hashSizeInBits, System.Boolean isCA, System.Security.Cryptography.X509Certificates.X509Certificate2 issuerCAKeyCert, System.String pkcsStorePath) [0x00377] in C:\OneDrive\VS\Pkcs12TestProject\Pkcs12TestProject\Pkcs12TestProject\MyClass.cs:223 

Edit 4: Si j'utilise le certificat X509 de BountyCastle comme rawdata dans la méthode X509Certificate2, il fonctionne très bien! Mais il est sans la clé privée ..

+0

La longueur indéfinie n'est pas autorisée dans DER (DER est un sous-ensemble plus restreint de BER). – Crypt32

+0

Merci, mais comment puis-je utiliser votre indice dans C#? –

+0

Avez-vous une classe DotNetUtilities de Bouncy Castle disponible? Il peut convertir cert bouncy en .Net cert, que vous pouvez utiliser .Net cert pour créer X509Certificate2 – tomassino

Répondre

2

J'ai trouvé quelques rapports de bogue sur votre problème avec des solutions de contournement possibles décrites. Je n'ai pas un environnement approprié pour le tester moi-même - désolé.Mais de l'histoire, il semble que cela n'a pas vraiment été résolu:

  1. Bugreport:

Cela indique explicitement des problèmes avec BouncyCastle comme vous l'expérience. Sebastian Pouliot publie un exemple de code dans comment3 qu'il pense pouvoir être utilisé (ou des parties de celui-ci) pour contourner le problème en utilisant mono.security.dll. Je ne sais pas si votre cas de figure permet de l'utiliser. Il est livré avec MonoDroid.
Il va dans les détails dans ce comment et a le code exemple lié sur github: https://github.com/mono/mono/blob/master/mcs/tools/security/makecert.cs

  1. Il y a aussi quelqu'un d'autre qui a posté un problème avec cela. BouncyCastle n'est pas mentionné explicitement: http://lists.ximian.com/pipermail/mono-bugs/2010-October/104908.html

Sa solution à la fin du poste:
[Une fois que vous avez le PKCS correct # 12] Citation:

Write the byte[] PKCS#12 into a temporary file and load it with string constructor.


Mise à jour source fournie dans les commentaires

Espérons que mon système a fonctionné comme il a fallu des heures pour le faire fonctionner. Mais ensuite j'ai eu le travail suivant.

La solution consiste à remplacer StoreBuilder par UseDEREncoding par true.

Petit bugfix à l'avant
Trouver: vous mettre dans un String.Empty comme mot de passe mais protégé le cert avec un mot de passe. Je pense que ce n'est pas correct. Si je mets le mot de passe, je reçois à nouveau la première erreur CryptographicException Certificate ne peut pas être codé pour un certificat valide.

Alors d'abord je changé ceci:

certificate = new X509Certificate2(pkcsPath, string.Empty); 

à

certificate = new X509Certificate2(pkcsPath, certPassword); 

Fix
Et maintenant, je ne sais pas si c'est ce que vous voulez, mais après l'avoir changé, je n » ai pas t obtient une exception mais un objet de certificat.

Les changements complets du « utilisant flux de mémoire » bloc finally ressemblait à ceci:

using (MemoryStream pfxData = new MemoryStream()) 
{ 
    // **Change 1**: The DER Encoding is enabled on the 
    // store builder 
    Pkcs12StoreBuilder builder = new Pkcs12StoreBuilder(); 
    builder.SetUseDerEncoding(true); 
    Pkcs12Store pkcsStore = builder.Build(); 
    // change - end 

    X509CertificateEntry[] chain = new X509CertificateEntry[1]; 
    string certPassword = Guid.NewGuid().ToString(); 
    chain[0] = new X509CertificateEntry(x509); 
    pkcsStore.SetKeyEntry(applicationName, new AsymmetricKeyEntry(subjectKeyPair.Private), chain); 
    pkcsStore.Save(pfxData, certPassword.ToCharArray(), random); 

    var pkcsPath = pkcsStorePath + "/pkcs.p12"; 

    File.WriteAllBytes(pkcsPath, pfxData.ToArray()); 

    // **Change 2**: Use certificate password 
    certificate = new X509Certificate2(pkcsPath, certPassword); 
    // **Change 3**: Possible to use array instead of filename 
    // works as well. Just uncomment 
    //certificate = new X509Certificate2(pfxData.ToArray(), certPassword); 

} 
+0

Merci pour votre réponse. 1. J'ai essayé d'utiliser du code de makecert.cs, mais je ne peux pas le compiler. Le problème est que X509CertificateBuilder a des propriétés qui ne sont pas disponibles. Par exemple: X509CertificateBuilder.SubjectPublicKey (Erreur: La référence au type 'AsymmetricAlgorithm' indique qu'il est défini dans 'mscorlib', mais il n'a pas pu être trouvé) 2. Cela ne fonctionne pas pour moi. Peut-être que le PKCS # 12 n'est pas correct !? J'ai mis à jour ma question avec le code pour enregistrer le fichier et j'ai créé un projet de test: http://1drv.ms/u/s!Aq2x4hOwAC2nl5J9ZzkHXyB-2-DObw –

+0

Le code est dans le PCL dans le MyClass.cs –

+0

I J'ai mis à jour ma question –

0

Une partie du problème semble être que X509Certificate2 l'octet de Mono [] constructeurs ne se comportent pas la même chose que .NET Constructeurs X509Certificate2 byte [] de Framework.

En parcourant le mono source il semble que X509Certificate2(byte[]) va essayer de charger un certificat X.509 (individuel), puis comme PFX avec un mot de passe null (vs vide).

Ce qui m'a le plus confondu au sujet de votre callstack, et j'espérais reproduire, c'est qu'il a essayé un décodeur PEM ...ce qui ne devrait arriver que lorsque le premier octet n'est pas 0x30 (per the source), mais 0x30 devrait être le premier octet du PFX. (Ensuite, il y a leur mauvaise manipulation de ne pas trouver -----BEGIN CERTIFICATE----- entraînant la ArgumentOutOfRangeException qui m'a envoyé un mauvais chemin Oh, bien..)

La mise en œuvre .NET Framework de new X509Certificate2(byte[]) est plus souple:

  • X.509 DER
  • X.509 PEM
  • PFX de passe null
  • PFX mot de passe vide
  • PKCS # 7 SignedCms certificat signataire
  • authenticode certificat signataire

(donc Mono essaie seulement la moitié des choses .NET Framework/.NET Core ne)

D'après les commentaires, il semble que vous utilisez un PFX avec un mot de passe vide, donc changer votre appel de normalisation post-DER de

new X509Certificate2(asn1ByteArray) 

à

new X509Certificate2(asn1ByteArray, string.Empty) 

devrait résoudre cet aspect particulier du problème.

+0

Merci pour votre réponse. J'utilise le paramètre password avec un vrai mot de passe et je l'ai essayé avec string.Empty, mais l'exception existe toujours. J'ai créé un projet de test avec le code. Le code est dans le PCL dans le MyClass.cs: https://1drv.ms/u/s!Aq2x4hOwAC2nl5J9ZzkHXyB-2-DObw –

+0

J'ai mis à jour ma question. –