Ejemplo n.º 1
0
        public static unsafe bool TryExportToEncryptedPem <T>(
            T arg,
            ReadOnlySpan <char> password,
            PbeParameters pbeParameters,
            TryExportEncryptedKeyAction <T> exporter,
            Span <char> destination,
            out int charsWritten)
        {
            int bufferSize = 4096;

            while (true)
            {
                byte[] buffer       = CryptoPool.Rent(bufferSize);
                int    bytesWritten = 0;
                bufferSize = buffer.Length;

                // Fixed to prevent GC moves.
                fixed(byte *bufferPtr = buffer)
                {
                    try
                    {
                        if (exporter(arg, password, pbeParameters, buffer, out bytesWritten))
                        {
                            Span <byte> writtenSpan = new Span <byte>(buffer, 0, bytesWritten);
                            return(PemEncoding.TryWrite(PemLabels.EncryptedPkcs8PrivateKey, writtenSpan, destination, out charsWritten));
                        }
                    }
                    finally
                    {
                        CryptoPool.Return(buffer, bytesWritten);
                    }

                    bufferSize = checked (bufferSize * 2);
                }
            }
        }
 public CertificatePrivateKeyBytesLoader()
 {
     _pbeParameters = new PbeParameters(PbeEncryptionAlgorithm.Aes256Cbc, HashAlgorithmName.SHA512, 1);
 }
Ejemplo n.º 3
0
 public virtual bool TryExportEncryptedPkcs8PrivateKey(ReadOnlySpan <char> password, PbeParameters pbeParameters, Span <byte> destination, out int bytesWritten) => throw null;
Ejemplo n.º 4
0
 public virtual byte[] ExportEncryptedPkcs8PrivateKey(ReadOnlySpan <char> password, PbeParameters pbeParameters) => throw null;
        /// <summary>
        /// Exports the current key in the PKCS#8 EncryptedPrivateKeyInfo format with a char-based password.
        /// </summary>
        /// <param name="csp"></param>
        /// <param name="password">The password to use when encrypting the key material.</param>
        /// <param name="pbeParameters">The password-based encryption (PBE) parameters to use when encrypting the key material.</param>
        /// <returns cref="String">A PEMBase64 string containing the PKCS#8 EncryptedPrivateKeyInfo representation of this key.</returns>
        /// <remarks>
        /// When pbeParameters indicates an algorithm that uses PBKDF2 (Password-
        /// Based Key Derivation Function 2), the password is converted to bytes via the
        /// UTF-8 encoding.
        /// </remarks>
        /// <exception cref="CryptographicException">The key could not be exported.</exception>
        public static string ExportEncryptedPkcs8PrivateKeyAsPEM(this RSACryptoServiceProvider csp, ReadOnlySpan <char> password, PbeParameters pbeParameters)
        {
            var result = csp.ExportEncryptedPkcs8PrivateKey(password, pbeParameters);
            var base64 = Convert.ToBase64String(result).ToCharArray();

            using (var sw = new StringWriter())
            {
                sw.Write("-----BEGIN ENCRYPTED PRIVATE KEY-----\n");
                for (var i = 0; i < base64.Length; i += 64)
                {
                    sw.Write(base64, i, Math.Min(64, base64.Length - i));
                    sw.Write('\n');
                }
                sw.Write("-----END ENCRYPTED PRIVATE KEY-----");
                return(sw.ToString());
            }
        }
Ejemplo n.º 6
0
 /// <summary>Add contents to the PFX in an bundle encrypted with a char-based password from a string.</summary>
 /// <param name="safeContents">The contents to add to the PFX.</param>
 /// <param name="password">The string to use as a password when encrypting the contents.</param>
 /// <param name="pbeParameters">The password-based encryption (PBE) parameters to use when encrypting the contents.</param>
 /// <exception cref="T:System.ArgumentNullException">The <paramref name="safeContents" /> or <paramref name="pbeParameters" /> parameter is <see langword="null" />.</exception>
 /// <exception cref="T:System.ArgumentException">The <paramref name="safeContents" /> parameter value is already encrypted.</exception>
 /// <exception cref="T:System.InvalidOperationException">The PFX is already sealed (<see cref="P:System.Security.Cryptography.Pkcs.Pkcs12Builder.IsSealed" /> is <see langword="true" />).</exception>
 public void AddSafeContentsEncrypted(Pkcs12SafeContents safeContents, string password, PbeParameters pbeParameters)
 {
     throw new PlatformNotSupportedException();
 }
Ejemplo n.º 7
0
 /// <summary>Add contents to the PFX in an bundle encrypted with a char-based password from a span.</summary>
 /// <param name="safeContents">The contents to add to the PFX.</param>
 /// <param name="password">The span to use as a password when encrypting the contents.</param>
 /// <param name="pbeParameters">The password-based encryption (PBE) parameters to use when encrypting the contents.</param>
 /// <exception cref="T:System.ArgumentNullException">The <paramref name="safeContents" /> or <paramref name="pbeParameters" /> parameter is <see langword="null" />.</exception>
 /// <exception cref="T:System.ArgumentException">The <paramref name="safeContents" /> parameter value is already encrypted.</exception>
 /// <exception cref="T:System.InvalidOperationException">The PFX is already sealed (<see cref="P:System.Security.Cryptography.Pkcs.Pkcs12Builder.IsSealed" /> is <see langword="true" />).</exception>
 public void AddSafeContentsEncrypted(Pkcs12SafeContents safeContents, ReadOnlySpan <char> password, PbeParameters pbeParameters)
 {
     throw new PlatformNotSupportedException();
 }
 public byte[] Encrypt(ReadOnlySpan <char> password, PbeParameters pbeParameters) => throw null;
Ejemplo n.º 9
0
 /// <summary>Adds an encrypted asymmetric private key to the SafeContents via a new <see cref="T:System.Security.Cryptography.Pkcs.Pkcs12ShroudedKeyBag" /> from a byte-based password in an array and returns the newly created bag instance.</summary>
 /// <param name="key">The asymmetric private key to add.</param>
 /// <param name="passwordBytes">The bytes to use as a password when encrypting the key material.</param>
 /// <param name="pbeParameters">The password-based encryption (PBE) parameters to use when encrypting the key material.</param>
 /// <returns>The bag instance which was added to the SafeContents.</returns>
 /// <exception cref="T:System.ArgumentNullException">The <paramref name="key" /> parameter is <see langword="null" />.</exception>
 /// <exception cref="T:System.InvalidOperationException">This instance is read-only.</exception>
 /// <exception cref="T:System.Security.Cryptography.CryptographicException">The key export failed.</exception>
 public Pkcs12ShroudedKeyBag AddShroudedKey(AsymmetricAlgorithm key, byte[] passwordBytes, PbeParameters pbeParameters)
 {
     throw new PlatformNotSupportedException();
 }
Ejemplo n.º 10
0
 /// <summary>Adds an encrypted asymmetric private key to the SafeContents via a new <see cref="T:System.Security.Cryptography.Pkcs.Pkcs12ShroudedKeyBag" /> from a character-based password in a span and returns the newly created bag instance.</summary>
 /// <param name="key">The asymmetric private key to add.</param>
 /// <param name="password">The password to use when encrypting the key material.</param>
 /// <param name="pbeParameters">The password-based encryption (PBE) parameters to use when encrypting the key material.</param>
 /// <returns>The bag instance which was added to the SafeContents.</returns>
 /// <exception cref="T:System.ArgumentNullException">The <paramref name="key" /> parameter is <see langword="null" />.</exception>
 /// <exception cref="T:System.InvalidOperationException">This instance is read-only.</exception>
 /// <exception cref="T:System.Security.Cryptography.CryptographicException">The key export failed.</exception>
 public Pkcs12ShroudedKeyBag AddShroudedKey(AsymmetricAlgorithm key, ReadOnlySpan <char> password, PbeParameters pbeParameters)
 {
     throw new PlatformNotSupportedException();
 }
 /// <summary>Attempts to produce a PKCS#8 EncryptedPrivateKeyInfo from the property contents of this object after encrypting with the specified character-based password and encryption parameters, writing the result into a provided buffer.</summary>
 /// <param name="password">The password to use when encrypting the key material.</param>
 /// <param name="pbeParameters">The password-based encryption (PBE) parameters to use when encrypting the key material.</param>
 /// <param name="destination">The byte span to receive the PKCS#8 EncryptedPrivateKeyInfo data.</param>
 /// <param name="bytesWritten">When this method returns, contains a value that indicates the number of bytes written to <paramref name="destination" />. This parameter is treated as uninitialized.</param>
 /// <returns>
 ///   <see langword="true" /> if <paramref name="destination" /> is big enough to receive the output; otherwise, <see langword="false" />.</returns>
 public bool TryEncrypt(ReadOnlySpan <char> password, PbeParameters pbeParameters, Span <byte> destination, out int bytesWritten)
 {
     throw new PlatformNotSupportedException();
 }
 /// <summary>Produces a PKCS#8 EncryptedPrivateKeyInfo from the property contents of this object after encrypting with the specified character-based password and encryption parameters.</summary>
 /// <param name="password">The password to use when encrypting the key material.</param>
 /// <param name="pbeParameters">The password-based encryption (PBE) parameters to use when encrypting the key material.</param>
 /// <returns>A byte array containing the encoded form of the PKCS#8 EncryptedPrivateKeyInfo.</returns>
 public byte[] Encrypt(ReadOnlySpan <char> password, PbeParameters pbeParameters)
 {
     throw new PlatformNotSupportedException();
 }
 public bool TryEncrypt(ReadOnlySpan <byte> passwordBytes, PbeParameters pbeParameters, Span <byte> destination, out int bytesWritten) => throw null;
 public byte[] Encrypt(ReadOnlySpan <byte> passwordBytes, PbeParameters pbeParameters) => throw null;
Ejemplo n.º 15
0
 private static void ReadBase64EncryptedPkcs8(
     string base64EncPkcs8,
     string password,
     PbeParameters pbeParameters,
     in DSAParameters expected)
Ejemplo n.º 16
0
        internal byte[] Encrypt(
            ReadOnlySpan <char> password,
            ReadOnlySpan <byte> passwordBytes,
            PbeParameters pbeParameters)
        {
            Debug.Assert(pbeParameters != null);
            Debug.Assert(pbeParameters.IterationCount >= 1);

            AsnWriter writer = null;

            using (AsnWriter contentsWriter = Encode())
            {
                ReadOnlySpan <byte> contentsSpan = contentsWriter.EncodeAsSpan();

                PasswordBasedEncryption.InitiateEncryption(
                    pbeParameters,
                    out SymmetricAlgorithm cipher,
                    out string hmacOid,
                    out string encryptionAlgorithmOid,
                    out bool isPkcs12);

                int         cipherBlockBytes = cipher.BlockSize / 8;
                byte[]      encryptedRent    = CryptoPool.Rent(contentsSpan.Length + cipherBlockBytes);
                Span <byte> encryptedSpan    = Span <byte> .Empty;
                Span <byte> iv   = stackalloc byte[cipherBlockBytes];
                Span <byte> salt = stackalloc byte[16];
                RandomNumberGenerator.Fill(salt);

                try
                {
                    int written = PasswordBasedEncryption.Encrypt(
                        password,
                        passwordBytes,
                        cipher,
                        isPkcs12,
                        contentsSpan,
                        pbeParameters,
                        salt,
                        encryptedRent,
                        iv);

                    encryptedSpan = encryptedRent.AsSpan(0, written);

                    writer = new AsnWriter(AsnEncodingRules.DER);

                    // EncryptedData
                    writer.PushSequence();

                    // version
                    // Since we're not writing unprotected attributes, version=0
                    writer.WriteInteger(0);

                    // encryptedContentInfo
                    {
                        writer.PushSequence();
                        writer.WriteObjectIdentifier(Oids.Pkcs7Data);

                        PasswordBasedEncryption.WritePbeAlgorithmIdentifier(
                            writer,
                            isPkcs12,
                            encryptionAlgorithmOid,
                            salt,
                            pbeParameters.IterationCount,
                            hmacOid,
                            iv);

                        writer.WriteOctetString(
                            new Asn1Tag(TagClass.ContextSpecific, 0),
                            encryptedSpan);

                        writer.PopSequence();
                    }

                    writer.PopSequence();

                    return(writer.Encode());
                }
                finally
                {
                    CryptographicOperations.ZeroMemory(encryptedSpan);
                    CryptoPool.Return(encryptedRent, clearSize: 0);
                    writer?.Dispose();
                }
            }
        }
Ejemplo n.º 17
0
 private void ReadWriteBase64EncryptedPkcs8(
     string base64EncryptedPkcs8,
     string password,
     PbeParameters pbe,
     in ECParameters expected,