Ejemplo n.º 1
0
        public virtual unsafe void ImportRSAPrivateKey(ReadOnlySpan <byte> source, out int bytesRead)
        {
            fixed(byte *ptr = &MemoryMarshal.GetReference(source))
            {
                using (MemoryManager <byte> manager = new PointerMemoryManager <byte>(ptr, source.Length))
                {
                    AsnReader             reader     = new AsnReader(manager.Memory, AsnEncodingRules.BER);
                    ReadOnlyMemory <byte> firstValue = reader.PeekEncodedValue();
                    int localRead = firstValue.Length;

                    AlgorithmIdentifierAsn ignored = default;
                    RSAKeyFormatHelper.FromPkcs1PrivateKey(firstValue, ignored, out RSAParameters rsaParameters);

                    fixed(byte *dPin = rsaParameters.D)
                    fixed(byte *pPin    = rsaParameters.P)
                    fixed(byte *qPin    = rsaParameters.Q)
                    fixed(byte *dpPin   = rsaParameters.DP)
                    fixed(byte *dqPin   = rsaParameters.DQ)
                    fixed(byte *qInvPin = rsaParameters.InverseQ)
                    {
                        try
                        {
                            ImportParameters(rsaParameters);
                        }
                        finally
                        {
                            ClearPrivateParameters(rsaParameters);
                        }
                    }

                    bytesRead = localRead;
                }
            }
        }
Ejemplo n.º 2
0
        internal static unsafe byte[] ExportPkcs8(SafeSecKeyRefHandle key, ReadOnlySpan <char> password)
        {
            using (SafeCFDataHandle data = Interop.AppleCrypto.SecKeyExportData(key, exportPrivate: true, password))
            {
                ReadOnlySpan <byte> systemExport = Interop.CoreFoundation.CFDataDangerousGetSpan(data);

                fixed(byte *ptr = systemExport)
                {
                    using (PointerMemoryManager <byte> manager = new PointerMemoryManager <byte>(ptr, systemExport.Length))
                    {
                        // Apple's PKCS8 export exports using PBES2, which Win7, Win8.1, and Apple all fail to
                        // understand in their PKCS12 readers, so re-encrypt using the Win7 PKCS12-PBE parameters.
                        //
                        // Since Apple only reliably exports keys with encrypted PKCS#8 there's not a
                        // "so export it plaintext and only encrypt it once" option.
                        AsnWriter writer = KeyFormatHelper.ReencryptPkcs8(
                            password,
                            manager.Memory,
                            password,
                            UnixExportProvider.s_windowsPbe);

                        return(writer.Encode());
                    }
                }
            }
        }
Ejemplo n.º 3
0
        private static unsafe AsnWriter?RewritePkcs8ECPrivateKeyWithZeroPublicKey(ReadOnlySpan <byte> source)
        {
            fixed(byte *ptr = &MemoryMarshal.GetReference(source))
            {
                using (MemoryManager <byte> manager = new PointerMemoryManager <byte>(ptr, source.Length))
                {
                    PrivateKeyInfoAsn      privateKeyInfo   = PrivateKeyInfoAsn.Decode(manager.Memory, AsnEncodingRules.BER);
                    AlgorithmIdentifierAsn privateAlgorithm = privateKeyInfo.PrivateKeyAlgorithm;

                    if (privateAlgorithm.Algorithm.Value != Oids.EcPublicKey)
                    {
                        return(null);
                    }

                    ECPrivateKey privateKey = ECPrivateKey.Decode(privateKeyInfo.PrivateKey, AsnEncodingRules.BER);
                    EccKeyFormatHelper.FromECPrivateKey(privateKey, privateAlgorithm, out ECParameters ecParameters);

                    fixed(byte *pD = ecParameters.D)
                    {
                        try
                        {
                            if (!ecParameters.Curve.IsExplicit || ecParameters.Q.X != null || ecParameters.Q.Y != null)
                            {
                                return(null);
                            }

                            byte[] zero = new byte[ecParameters.D !.Length];
Ejemplo n.º 4
0
        public virtual unsafe void ImportRSAPublicKey(ReadOnlySpan <byte> source, out int bytesRead)
        {
            try
            {
                AsnDecoder.ReadEncodedValue(
                    source,
                    AsnEncodingRules.BER,
                    out _,
                    out _,
                    out int localRead);

                fixed(byte *ptr = &MemoryMarshal.GetReference(source))
                {
                    using (MemoryManager <byte> manager = new PointerMemoryManager <byte>(ptr, localRead))
                    {
                        AlgorithmIdentifierAsn ignored = default;
                        RSAKeyFormatHelper.ReadRsaPublicKey(manager.Memory, ignored, out RSAParameters rsaParameters);

                        ImportParameters(rsaParameters);

                        bytesRead = localRead;
                    }
                }
            }
            catch (AsnContentException e)
            {
                throw new CryptographicException(SR.Cryptography_Der_Invalid_Encoding, e);
            }
        }
Ejemplo n.º 5
0
        internal unsafe int ImportSubjectPublicKeyInfo(
            ReadOnlySpan <byte> source,
            out int bytesRead)
        {
            ThrowIfDisposed();

            fixed(byte *ptr = &MemoryMarshal.GetReference(source))
            {
                using (MemoryManager <byte> manager = new PointerMemoryManager <byte>(ptr, source.Length))
                {
                    // Validate the DER value and get the number of bytes.
                    EccKeyFormatHelper.ReadSubjectPublicKeyInfo(
                        manager.Memory,
                        out int localRead);

                    SafeSecKeyRefHandle publicKey = Interop.AppleCrypto.ImportEphemeralKey(source.Slice(0, localRead), false);
                    SecKeyPair          newKeys   = SecKeyPair.PublicOnly(publicKey);
                    int size = GetKeySize(newKeys);
                    SetKey(newKeys);

                    bytesRead = localRead;
                    return(size);
                }
            }
        }
Ejemplo n.º 6
0
        internal static unsafe Pkcs8Response ImportEncryptedPkcs8PrivateKey(
            ReadOnlySpan <byte> passwordBytes,
            ReadOnlySpan <byte> source,
            out int bytesRead)
        {
            fixed(byte *ptr = &MemoryMarshal.GetReference(source))
            {
                using (MemoryManager <byte> manager = new PointerMemoryManager <byte>(ptr, source.Length))
                {
                    // Since there's no bytes-based-password PKCS8 import in CNG, just do the decryption
                    // here and call the unencrypted PKCS8 import.
                    ArraySegment <byte> decrypted = KeyFormatHelper.DecryptPkcs8(
                        passwordBytes,
                        manager.Memory,
                        out bytesRead);

                    Span <byte> decryptedSpan = decrypted;

                    try
                    {
                        return(ImportPkcs8(decryptedSpan));
                    }
                    catch (CryptographicException e)
                    {
                        throw new CryptographicException(SR.Cryptography_Pkcs8_EncryptedReadFailed, e);
                    }
                    finally
                    {
                        CryptographicOperations.ZeroMemory(decryptedSpan);
                        CryptoPool.Return(decrypted.Array !);
                    }
                }
            }
        }
Ejemplo n.º 7
0
        protected void ParsePkcs12(ReadOnlySpan <byte> data)
        {
            try
            {
                // RFC7292 specifies BER instead of DER
                AsnValueReader reader = new AsnValueReader(data, AsnEncodingRules.BER);

                // Windows compatibility: Ignore trailing data.
                ReadOnlySpan <byte> encodedData = reader.PeekEncodedValue();

                unsafe
                {
                    IntPtr      tmpPtr  = Marshal.AllocHGlobal(encodedData.Length);
                    Span <byte> tmpSpan = new Span <byte>((byte *)tmpPtr, encodedData.Length);
                    encodedData.CopyTo(tmpSpan);
                    _tmpManager = new PointerMemoryManager <byte>((void *)tmpPtr, encodedData.Length);
                }

                ReadOnlyMemory <byte> tmpMemory = _tmpManager.Memory;
                reader = new AsnValueReader(tmpMemory.Span, AsnEncodingRules.BER);

                PfxAsn.Decode(ref reader, tmpMemory, out PfxAsn pfxAsn);

                if (pfxAsn.AuthSafe.ContentType != Oids.Pkcs7Data)
                {
                    throw new CryptographicException(SR.Cryptography_Der_Invalid_Encoding);
                }

                _pfxAsn = pfxAsn;
            }
            catch (AsnContentException e)
            {
                throw new CryptographicException(SR.Cryptography_Der_Invalid_Encoding, e);
            }
        }
Ejemplo n.º 8
0
        private static byte[] CopyContent(ReadOnlySpan <byte> encodedMessage)
        {
            unsafe
            {
                fixed(byte *pin = encodedMessage)
                {
                    using (var manager = new PointerMemoryManager <byte>(pin, encodedMessage.Length))
                    {
                        AsnValueReader reader = new AsnValueReader(encodedMessage, AsnEncodingRules.BER);

                        ContentInfoAsn.Decode(
                            ref reader,
                            manager.Memory,
                            out ContentInfoAsn parsedContentInfo);

                        if (parsedContentInfo.ContentType != Oids.Pkcs7Enveloped)
                        {
                            throw new CryptographicException(SR.Cryptography_Cms_InvalidMessageType);
                        }

                        return(parsedContentInfo.Content.ToArray());
                    }
                }
            }
        }
Ejemplo n.º 9
0
            public override unsafe void ImportRSAPublicKey(ReadOnlySpan <byte> source, out int bytesRead)
            {
                ThrowIfDisposed();

                fixed(byte *ptr = &MemoryMarshal.GetReference(source))
                {
                    using (MemoryManager <byte> manager = new PointerMemoryManager <byte>(ptr, source.Length))
                    {
                        AsnReader             reader       = new AsnReader(manager.Memory, AsnEncodingRules.BER);
                        ReadOnlyMemory <byte> firstElement = reader.PeekEncodedValue();

                        SubjectPublicKeyInfoAsn spki = new SubjectPublicKeyInfoAsn
                        {
                            Algorithm = new AlgorithmIdentifierAsn
                            {
                                Algorithm  = new Oid(Oids.Rsa),
                                Parameters = AlgorithmIdentifierAsn.ExplicitDerNull,
                            },
                            SubjectPublicKey = firstElement,
                        };

                        using (AsnWriter writer = new AsnWriter(AsnEncodingRules.DER))
                        {
                            spki.Encode(writer);
                            ImportSubjectPublicKeyInfo(writer.EncodeAsSpan(), out _);
                        }

                        bytesRead = firstElement.Length;
                    }
                }
            }
Ejemplo n.º 10
0
            static byte[] CopyContent(ReadOnlySpan <byte> encodedMessage)
            {
                unsafe
                {
                    fixed(byte *pin = encodedMessage)
                    {
                        using (var manager = new PointerMemoryManager <byte>(pin, encodedMessage.Length))
                        {
                            AsnValueReader reader = new AsnValueReader(encodedMessage, AsnEncodingRules.BER);

                            // Windows (and thus NetFx) reads the leading data and ignores extra.
                            // So use the Decode overload which doesn't throw on extra data.
                            ContentInfoAsn.Decode(
                                ref reader,
                                manager.Memory,
                                out ContentInfoAsn contentInfo);

                            if (contentInfo.ContentType != Oids.Pkcs7Signed)
                            {
                                throw new CryptographicException(SR.Cryptography_Cms_InvalidMessageType);
                            }

                            return(contentInfo.Content.ToArray());
                        }
                    }
                }
            }
Ejemplo n.º 11
0
        public unsafe override Oid GetEncodedMessageType(ReadOnlySpan <byte> encodedMessage)
        {
            fixed(byte *pin = encodedMessage)
            {
                using (var manager = new PointerMemoryManager <byte>(pin, encodedMessage.Length))
                {
                    AsnValueReader reader = new AsnValueReader(encodedMessage, AsnEncodingRules.BER);

                    ContentInfoAsn.Decode(ref reader, manager.Memory, out ContentInfoAsn contentInfo);

                    switch (contentInfo.ContentType)
                    {
                    case Oids.Pkcs7Data:
                    case Oids.Pkcs7Signed:
                    case Oids.Pkcs7Enveloped:
                    case Oids.Pkcs7SignedEnveloped:
                    case Oids.Pkcs7Hashed:
                    case Oids.Pkcs7Encrypted:
                        return(new Oid(contentInfo.ContentType));
                    }

                    throw new CryptographicException(SR.Cryptography_Cms_InvalidMessageType);
                }
            }
        }
Ejemplo n.º 12
0
        public override unsafe void ImportRSAPublicKey(ReadOnlySpan <byte> source, out int bytesRead)
        {
            ThrowIfDisposed();

            fixed(byte *ptr = &MemoryMarshal.GetReference(source))
            {
                using (MemoryManager <byte> manager = new PointerMemoryManager <byte>(ptr, source.Length))
                {
                    AsnReader             reader       = new AsnReader(manager.Memory, AsnEncodingRules.BER);
                    ReadOnlyMemory <byte> firstElement = reader.PeekEncodedValue();

                    SafeRsaHandle key = Interop.Crypto.DecodeRsaPublicKey(firstElement.Span);

                    Interop.Crypto.CheckValidOpenSslHandle(key);

                    FreeKey();
                    _key = new Lazy <SafeRsaHandle>(key);

                    // Use ForceSet instead of the property setter to ensure that LegalKeySizes doesn't interfere
                    // with the already loaded key.
                    ForceSetKeySize(BitsPerByte * Interop.Crypto.RsaSize(key));

                    bytesRead = firstElement.Length;
                }
            }
        }
Ejemplo n.º 13
0
        internal static unsafe Pkcs8Response ImportPkcs8PrivateKey(ReadOnlySpan <byte> source, out int bytesRead)
        {
            int len;

            fixed(byte *ptr = &MemoryMarshal.GetReference(source))
            {
                using (MemoryManager <byte> manager = new PointerMemoryManager <byte>(ptr, source.Length))
                {
                    AsnReader reader = new AsnReader(manager.Memory, AsnEncodingRules.BER);
                    len = reader.ReadEncodedValue().Length;
                }
            }

            bytesRead = len;
            ReadOnlySpan <byte> pkcs8Source = source.Slice(0, len);

            try
            {
                return(ImportPkcs8(pkcs8Source));
            }
            catch (CryptographicException)
            {
                AsnWriter?pkcs8ZeroPublicKey = RewritePkcs8ECPrivateKeyWithZeroPublicKey(pkcs8Source);

                if (pkcs8ZeroPublicKey == null)
                {
                    throw;
                }

                return(ImportPkcs8(pkcs8ZeroPublicKey.EncodeAsSpan()));
            }
        }
Ejemplo n.º 14
0
        internal static unsafe ECParameters FromECPrivateKey(ReadOnlySpan <byte> key, out int bytesRead)
        {
            try
            {
                AsnDecoder.ReadEncodedValue(
                    key,
                    AsnEncodingRules.BER,
                    out _,
                    out _,
                    out int firstValueLength);

                fixed(byte *ptr = &MemoryMarshal.GetReference(key))
                {
                    using (MemoryManager <byte> manager = new PointerMemoryManager <byte>(ptr, firstValueLength))
                    {
                        AlgorithmIdentifierAsn algId = default;
                        FromECPrivateKey(manager.Memory, algId, out ECParameters ret);
                        bytesRead = firstValueLength;
                        return(ret);
                    }
                }
            }
            catch (AsnContentException e)
            {
                throw new CryptographicException(SR.Cryptography_Der_Invalid_Encoding, e);
            }
        }
Ejemplo n.º 15
0
        private static bool IsPkcs7Signed(ReadOnlySpan <byte> rawData)
        {
            try
            {
                unsafe
                {
                    fixed(byte *pin = rawData)
                    {
                        using (var manager = new PointerMemoryManager <byte>(pin, rawData.Length))
                        {
                            AsnValueReader reader = new AsnValueReader(rawData, AsnEncodingRules.BER);

                            ContentInfoAsn.Decode(ref reader, manager.Memory, out ContentInfoAsn contentInfo);

                            switch (contentInfo.ContentType)
                            {
                            case Oids.Pkcs7Signed:
                            case Oids.Pkcs7SignedEnveloped:
                                return(true);
                            }
                        }
                    }
                }
            }
            catch (CryptographicException)
            {
            }

            return(false);
        }
Ejemplo n.º 16
0
        private static unsafe int DecodeSubjectPublicKeyInfo(
            ReadOnlySpan <byte> source,
            out Oid oid,
            out AsnEncodedData parameters,
            out AsnEncodedData keyValue)
        {
            fixed(byte *ptr = &MemoryMarshal.GetReference(source))
            using (MemoryManager <byte> manager = new PointerMemoryManager <byte>(ptr, source.Length))
            {
                AsnValueReader reader = new AsnValueReader(source, AsnEncodingRules.DER);

                int read;
                SubjectPublicKeyInfoAsn spki;

                try
                {
                    read = reader.PeekEncodedValue().Length;
                    SubjectPublicKeyInfoAsn.Decode(ref reader, manager.Memory, out spki);
                }
                catch (AsnContentException e)
                {
                    throw new CryptographicException(SR.Cryptography_Der_Invalid_Encoding, e);
                }

                oid        = new Oid(spki.Algorithm.Algorithm, null);
                parameters = new AsnEncodedData(spki.Algorithm.Parameters?.ToArray() ?? Array.Empty <byte>());
                keyValue   = new AsnEncodedData(spki.SubjectPublicKey.ToArray());
                return(read);
            }
        }
Ejemplo n.º 17
0
 public static CoseSign1Message DecodeSign1(ReadOnlySpan <byte> cborPayload)
 {
     unsafe
     {
         fixed(byte *ptr = &MemoryMarshal.GetReference(cborPayload))
         {
             using (MemoryManager <byte> manager = new PointerMemoryManager <byte>(ptr, cborPayload.Length))
             {
                 return(DecodeCoseSign1Core(new CborReader(manager.Memory)));
             }
         }
     }
 }
Ejemplo n.º 18
0
        internal static unsafe Pkcs8Response ImportEncryptedPkcs8PrivateKey(
            ReadOnlySpan <char> password,
            ReadOnlySpan <byte> source,
            out int bytesRead)
        {
            fixed(byte *ptr = &MemoryMarshal.GetReference(source))
            {
                using (MemoryManager <byte> manager = new PointerMemoryManager <byte>(ptr, source.Length))
                {
                    AsnReader reader = new AsnReader(manager.Memory, AsnEncodingRules.BER);
                    int       len    = reader.ReadEncodedValue().Length;
                    source = source.Slice(0, len);

                    try
                    {
                        bytesRead = len;
                        return(ImportPkcs8(source, password));
                    }
                    catch (CryptographicException)
                    {
                    }

                    ArraySegment <byte> decrypted = KeyFormatHelper.DecryptPkcs8(
                        password,
                        manager.Memory.Slice(0, len),
                        out int innerRead);

                    Span <byte> decryptedSpan = decrypted;

                    try
                    {
                        if (innerRead != len)
                        {
                            throw new CryptographicException(SR.Cryptography_Der_Invalid_Encoding);
                        }

                        bytesRead = len;
                        return(ImportPkcs8(decryptedSpan));
                    }
                    catch (CryptographicException e)
                    {
                        throw new CryptographicException(SR.Cryptography_Pkcs8_EncryptedReadFailed, e);
                    }
                    finally
                    {
                        CryptographicOperations.ZeroMemory(decryptedSpan);
                        CryptoPool.Return(decrypted.Array !, clearSize: 0);
                    }
                }
            }
        }
Ejemplo n.º 19
0
            public override unsafe void ImportRSAPublicKey(ReadOnlySpan <byte> source, out int bytesRead)
            {
                ThrowIfDisposed();

                fixed(byte *ptr = &MemoryMarshal.GetReference(source))
                {
                    using (MemoryManager <byte> manager = new PointerMemoryManager <byte>(ptr, source.Length))
                    {
                        ReadOnlyMemory <byte> subjectPublicKey;
                        try
                        {
                            AsnReader reader = new AsnReader(manager.Memory, AsnEncodingRules.BER);
                            subjectPublicKey = reader.PeekEncodedValue();
                        }
                        catch (AsnContentException e)
                        {
                            throw new CryptographicException(SR.Cryptography_Der_Invalid_Encoding, e);
                        }

                        // Decoding the key on Android requires the encoded SubjectPublicKeyInfo,
                        // not just the SubjectPublicKey, so we construct one.
                        SubjectPublicKeyInfoAsn spki = new SubjectPublicKeyInfoAsn
                        {
                            Algorithm = new AlgorithmIdentifierAsn
                            {
                                Algorithm  = Oids.Rsa,
                                Parameters = AlgorithmIdentifierAsn.ExplicitDerNull,
                            },
                            SubjectPublicKey = subjectPublicKey,
                        };

                        AsnWriter writer = new AsnWriter(AsnEncodingRules.DER);
                        spki.Encode(writer);

                        SafeRsaHandle key = Interop.AndroidCrypto.DecodeRsaSubjectPublicKeyInfo(writer.Encode());
                        if (key is null || key.IsInvalid)
                        {
                            key?.Dispose();
                            throw new CryptographicException();
                        }

                        FreeKey();
                        _key = new Lazy <SafeRsaHandle>(key);
                        SetKeySizeFromHandle(key);

                        bytesRead = subjectPublicKey.Length;
                    }
                }
            }
Ejemplo n.º 20
0
        public override unsafe void ImportPkcs8PrivateKey(ReadOnlySpan <byte> source, out int bytesRead)
        {
            fixed(byte *ptr = &MemoryMarshal.GetReference(source))
            {
                using (MemoryManager <byte> manager = new PointerMemoryManager <byte>(ptr, source.Length))
                {
                    ReadOnlyMemory <byte> pkcs1 = RSAKeyFormatHelper.ReadPkcs8(
                        manager.Memory,
                        out int localRead);

                    ImportRSAPrivateKey(pkcs1.Span, out _);
                    bytesRead = localRead;
                }
            }
        }
Ejemplo n.º 21
0
 internal static unsafe ECParameters FromECPrivateKey(ReadOnlySpan <byte> key, out int bytesRead)
 {
     fixed(byte *ptr = &MemoryMarshal.GetReference(key))
     {
         using (MemoryManager <byte> manager = new PointerMemoryManager <byte>(ptr, key.Length))
         {
             AsnReader reader                  = new AsnReader(manager.Memory, AsnEncodingRules.BER);
             AlgorithmIdentifierAsn algId      = default;
             ReadOnlyMemory <byte>  firstValue = reader.PeekEncodedValue();
             FromECPrivateKey(firstValue, algId, out ECParameters ret);
             bytesRead = firstValue.Length;
             return(ret);
         }
     }
 }
Ejemplo n.º 22
0
        internal static unsafe Pkcs8Response ImportPkcs8PrivateKey(ReadOnlySpan <byte> source, out int bytesRead)
        {
            int len;

            fixed(byte *ptr = &MemoryMarshal.GetReference(source))
            {
                using (MemoryManager <byte> manager = new PointerMemoryManager <byte>(ptr, source.Length))
                {
                    AsnReader reader = new AsnReader(manager.Memory, AsnEncodingRules.BER);
                    len = reader.ReadEncodedValue().Length;
                }
            }

            bytesRead = len;
            return(ImportPkcs8(source.Slice(0, len)));
        }
Ejemplo n.º 23
0
 internal static unsafe void ReadEncryptedPkcs8 <TRet>(
     string[] validOids,
     ReadOnlySpan <byte> source,
     ReadOnlySpan <char> password,
     KeyReader <TRet> keyReader,
     out int bytesRead,
     out TRet ret)
 {
     fixed(byte *ptr = &MemoryMarshal.GetReference(source))
     {
         using (MemoryManager <byte> manager = new PointerMemoryManager <byte>(ptr, source.Length))
         {
             ReadEncryptedPkcs8(validOids, manager.Memory, password, keyReader, out bytesRead, out ret);
         }
     }
 }
Ejemplo n.º 24
0
        public override unsafe void ImportSubjectPublicKeyInfo(ReadOnlySpan <byte> source, out int bytesRead)
        {
            fixed(byte *ptr = &MemoryMarshal.GetReference(source))
            {
                using (MemoryManager <byte> manager = new PointerMemoryManager <byte>(ptr, source.Length))
                {
                    ReadOnlyMemory <byte> pkcs1 = KeyFormatHelper.ReadSubjectPublicKeyInfo(
                        s_validOids,
                        manager.Memory,
                        out int localRead);

                    ImportRSAPublicKey(pkcs1.Span, out _);
                    bytesRead = localRead;
                }
            }
        }
Ejemplo n.º 25
0
        internal static unsafe ECParameters FromECPrivateKey(ReadOnlySpan <byte> key, out int bytesRead)
        {
            fixed(byte *ptr = &MemoryMarshal.GetReference(key))
            {
                using (MemoryManager <byte> manager = new PointerMemoryManager <byte>(ptr, key.Length))
                {
                    ECPrivateKey parsedKey =
                        AsnSerializer.Deserialize <ECPrivateKey>(manager.Memory, AsnEncodingRules.BER, out bytesRead);

                    ECParameters           ret;
                    AlgorithmIdentifierAsn algId = default;
                    FromECPrivateKey(parsedKey, algId, out ret);
                    return(ret);
                }
            }
        }
Ejemplo n.º 26
0
        public virtual unsafe void ImportRSAPrivateKey(ReadOnlySpan <byte> source, out int bytesRead)
        {
            try
            {
                AsnDecoder.ReadEncodedValue(
                    source,
                    AsnEncodingRules.BER,
                    out _,
                    out _,
                    out int firstValueLength);

                fixed(byte *ptr = &MemoryMarshal.GetReference(source))
                {
                    using (MemoryManager <byte> manager = new PointerMemoryManager <byte>(ptr, firstValueLength))
                    {
                        ReadOnlyMemory <byte> firstValue = manager.Memory;
                        int localRead = firstValue.Length;

                        AlgorithmIdentifierAsn ignored = default;
                        RSAKeyFormatHelper.FromPkcs1PrivateKey(firstValue, ignored, out RSAParameters rsaParameters);

                        fixed(byte *dPin = rsaParameters.D)
                        fixed(byte *pPin    = rsaParameters.P)
                        fixed(byte *qPin    = rsaParameters.Q)
                        fixed(byte *dpPin   = rsaParameters.DP)
                        fixed(byte *dqPin   = rsaParameters.DQ)
                        fixed(byte *qInvPin = rsaParameters.InverseQ)
                        {
                            try
                            {
                                ImportParameters(rsaParameters);
                            }
                            finally
                            {
                                ClearPrivateParameters(rsaParameters);
                            }
                        }

                        bytesRead = localRead;
                    }
                }
            }
            catch (AsnContentException e)
            {
                throw new CryptographicException(SR.Cryptography_Der_Invalid_Encoding, e);
            }
        }
Ejemplo n.º 27
0
            public X509ContentType GetCertContentType(ReadOnlySpan <byte> rawData)
            {
                const int errSecUnknownFormat = -25257;

                if (rawData == null || rawData.Length == 0)
                {
                    // Throw to match Windows and Unix behavior.
                    throw Interop.AppleCrypto.CreateExceptionForOSStatus(errSecUnknownFormat);
                }

                X509ContentType contentType = Interop.AppleCrypto.X509GetContentType(rawData);

                // Apple doesn't seem to recognize PFX files with no MAC, so try a quick maybe-it's-a-PFX test
                if (contentType == X509ContentType.Unknown)
                {
                    try
                    {
                        unsafe
                        {
                            fixed(byte *pin = rawData)
                            {
                                using (var manager = new PointerMemoryManager <byte>(pin, rawData.Length))
                                {
                                    PfxAsn.Decode(manager.Memory, AsnEncodingRules.BER);
                                }

                                contentType = X509ContentType.Pkcs12;
                            }
                        }
                    }
                    catch (CryptographicException)
                    {
                    }
                }

                if (contentType == X509ContentType.Unknown)
                {
                    // Throw to match Windows and Unix behavior.
                    throw Interop.AppleCrypto.CreateExceptionForOSStatus(errSecUnknownFormat);
                }

                return(contentType);
            }
Ejemplo n.º 28
0
        public virtual unsafe void ImportRSAPublicKey(ReadOnlySpan <byte> source, out int bytesRead)
        {
            fixed(byte *ptr = &MemoryMarshal.GetReference(source))
            {
                using (MemoryManager <byte> manager = new PointerMemoryManager <byte>(ptr, source.Length))
                {
                    AsnReader             reader     = new AsnReader(manager.Memory, AsnEncodingRules.BER);
                    ReadOnlyMemory <byte> firstValue = reader.PeekEncodedValue();
                    int localRead = firstValue.Length;

                    AlgorithmIdentifierAsn ignored = default;
                    RSAKeyFormatHelper.ReadRsaPublicKey(firstValue, ignored, out RSAParameters rsaParameters);

                    ImportParameters(rsaParameters);

                    bytesRead = localRead;
                }
            }
        }
Ejemplo n.º 29
0
            public override unsafe void ImportSubjectPublicKeyInfo(
                ReadOnlySpan <byte> source,
                out int bytesRead)
            {
                fixed(byte *ptr = &MemoryMarshal.GetReference(source))
                {
                    using (MemoryManager <byte> manager = new PointerMemoryManager <byte>(ptr, source.Length))
                    {
                        // Validate the DER value and get the number of bytes.
                        DSAKeyFormatHelper.ReadSubjectPublicKeyInfo(
                            manager.Memory,
                            out int localRead);

                        SafeSecKeyRefHandle publicKey = Interop.AppleCrypto.ImportEphemeralKey(source.Slice(0, localRead), false);
                        SetKey(SecKeyPair.PublicOnly(publicKey));

                        bytesRead = localRead;
                    }
                }
            }
Ejemplo n.º 30
0
        public virtual unsafe void ImportRSAPublicKey(ReadOnlySpan <byte> source, out int bytesRead)
        {
            fixed(byte *ptr = &MemoryMarshal.GetReference(source))
            {
                using (MemoryManager <byte> manager = new PointerMemoryManager <byte>(ptr, source.Length))
                {
                    RSAPublicKey key = AsnSerializer.Deserialize <RSAPublicKey>(
                        manager.Memory,
                        AsnEncodingRules.BER,
                        out int localRead);

                    RSAParameters rsaParameters = new RSAParameters
                    {
                        Modulus  = key.Modulus.ToByteArray(isUnsigned: true, isBigEndian: true),
                        Exponent = key.PublicExponent.ToByteArray(isUnsigned: true, isBigEndian: true),
                    };

                    ImportParameters(rsaParameters);
                    bytesRead = localRead;
                }
            }
        }