Пример #1
0
        public static void CreateSignature(System.Security.Cryptography.X509Certificates.X509Certificate2 mycert)
        {
            // https://www.programcreek.com/java-api-examples/?api=org.bouncycastle.x509.X509V3CertificateGenerator
            // https://forums.asp.net/t/2154987.aspx?Create+Self+Signed+Certificate+programatically+uisng+C+

            // System.Security.Cryptography.X509Certificates.X509Certificate2.CreateFromCertFile()


            // https://overcoder.net/q/429916/bouncycastle-privatekey-to-x509%D1%81%D0%B5%D1%80%D1%82%D0%B8%D1%84%D0%B8%D0%BA%D0%B0%D1%822-privatekey
            // https://www.csharpcodi.com/csharp-examples/Org.BouncyCastle.X509.X509Certificate.GetPublicKey()/

            Org.BouncyCastle.Crypto.AsymmetricKeyParameter Akp = Org.BouncyCastle.Security.DotNetUtilities.GetKeyPair(mycert.PrivateKey).Private;


            // if(mycert.HasPrivateKey)
            Org.BouncyCastle.Crypto.AsymmetricKeyParameter bouncyCastlePrivateKey = TransformRSAPrivateKey(mycert.PrivateKey);



            Org.BouncyCastle.X509.X509CertificateParser    certParser        = new Org.BouncyCastle.X509.X509CertificateParser();
            Org.BouncyCastle.X509.X509Certificate          bouncyCertificate = certParser.ReadCertificate(mycert.GetRawCertData());
            Org.BouncyCastle.Crypto.AsymmetricKeyParameter pubKey            = bouncyCertificate.GetPublicKey();

            Org.BouncyCastle.Crypto.IDigest algorithm = Org.BouncyCastle.Security.DigestUtilities.GetDigest(bouncyCertificate.SigAlgOid);
            // X509Certificate2Signature signature = new X509Certificate2Signature(mycert, algorithm);
            // https://github.com/kusl/itextsharp/blob/master/tags/iTextSharp_5_4_5/src/core/iTextSharp/text/pdf/security/X509Certificate2Signature.cs
            // Sign

            // PemReader pem = new PemReader();
            // pem.ReadPemObject().Headers
            // RSACryptoServiceProvider rsa = pem.ReadPrivateKeyFromFile("PrivateKey.pem");
        }
Пример #2
0
        public WindowsPrng()
        {
            // this.m_rnd = new Org.BouncyCastle.Crypto.Prng.CryptoApiRandomGenerator();

            const string digestName = "SHA256";

            Org.BouncyCastle.Crypto.IDigest digest = Org.BouncyCastle.Security.DigestUtilities.GetDigest(digestName);
            if (digest == null)
            {
                return;
            }

            Org.BouncyCastle.Crypto.Prng.DigestRandomGenerator prng =
                new Org.BouncyCastle.Crypto.Prng.DigestRandomGenerator(digest);

            const bool autoSeed = true;

            if (autoSeed)
            {
                // prng.AddSeedMaterial(NextCounterValue());
                // prng.AddSeedMaterial(GetNextBytes(Master, digest.GetDigestSize()));
            }

            this.m_rnd = prng;
        }
Пример #3
0
 public static byte[] Digest(Org.BouncyCastle.Crypto.IDigest d, byte[] b, int offset, int len)
 {
     d.BlockUpdate(b, offset, len);
     byte[] r = new byte[d.GetDigestSize()];
     d.DoFinal(r, 0);
     return(r);
 }
Пример #4
0
        private byte[] SignHashInternal(
            byte[] hash
            , Org.BouncyCastle.Crypto.IDigest digest
            , bool asOaep
            )
        {
            byte[] derEncoded = this.DerEncode(hash, digest);

            Org.BouncyCastle.Crypto.IAsymmetricBlockCipher rsaEngine = null;

            if (asOaep) // PSS:
            {
                rsaEngine =
                    new Org.BouncyCastle.Crypto.Encodings.OaepEncoding(
                        new Org.BouncyCastle.Crypto.Engines.RsaBlindedEngine()
                        );
            }
            else // Pkcs1
            {
                rsaEngine =
                    new Org.BouncyCastle.Crypto.Encodings.Pkcs1Encoding(
                        new Org.BouncyCastle.Crypto.Engines.RsaBlindedEngine()
                        );
            }

            rsaEngine.Init(true, this.m_keyPair.Private);

            byte[] encoded = rsaEngine.ProcessBlock(derEncoded, 0, derEncoded.Length);
            return(encoded);
        } // End Function SignHashInternal
Пример #5
0
        } // End Function Decrypt

        // Ignored
        //public override byte[] DecryptValue(byte[] rgb)
        //{
        //    System.Security.Cryptography.RSACryptoServiceProvider rs;
        //    return null;
        //}


        // call this.SignHash in effect
        // public virtual byte[] SignData(byte[] data, int offset, int count, HashAlgorithmName hashAlgorithm, RSASignaturePadding padding);
        // public virtual byte[] SignData(Stream data, HashAlgorithmName hashAlgorithm, RSASignaturePadding padding);
        // public byte[] SignData(byte[] data, HashAlgorithmName hashAlgorithm, RSASignaturePadding padding);



        public override byte[] SignHash(byte[] hash
                                        , System.Security.Cryptography.HashAlgorithmName hashAlgorithm
                                        , System.Security.Cryptography.RSASignaturePadding padding)
        {
            if (hash == null)
            {
                throw new System.ArgumentNullException(nameof(hash));
            }

            if (hashAlgorithm == null)
            {
                throw new System.ArgumentNullException(nameof(hashAlgorithm));
            }

            if (padding == null)
            {
                throw new System.ArgumentNullException(nameof(padding));
            }

            Org.BouncyCastle.Crypto.IDigest digest = GetBouncyAlgorithm(hashAlgorithm);

            if (padding == System.Security.Cryptography.RSASignaturePadding.Pkcs1)
            {
                return(SignHashInternal(hash, digest, false));
            }

            if (padding == System.Security.Cryptography.RSASignaturePadding.Pss)
            {
                return(SignHashInternal(hash, digest, true));
            }

            throw new System.Security.Cryptography.CryptographicException($"Unknown padding mode \"{padding}\".");
        } // End Function SignHash
Пример #6
0
        } // End Function GetBouncyAlgorithm

        protected override byte[] HashData(byte[] data, int offset, int count,
                                           System.Security.Cryptography.HashAlgorithmName hashAlgorithm)
        {
            Org.BouncyCastle.Crypto.IDigest digest = GetBouncyAlgorithm(hashAlgorithm);

            byte[] retValue = new byte[digest.GetDigestSize()];
            digest.BlockUpdate(data, offset, count);
            digest.DoFinal(retValue, 0);
            return(retValue);
        } // End Function HashData
Пример #7
0
        public static byte[] Digest(System.IO.Stream data, Org.BouncyCastle.Crypto.IDigest messageDigest)
        {
            byte[] buf = new byte[8192];
            int    n;

            while ((n = data.Read(buf, 0, buf.Length)) > 0)
            {
                messageDigest.BlockUpdate(buf, 0, n);
            }
            byte[] r = new byte[messageDigest.GetDigestSize()];
            messageDigest.DoFinal(r, 0);
            return(r);
        }
Пример #8
0
        } // End Function SignHashInternal

        private byte[] DerEncode(byte[] hash,
                                 Org.BouncyCastle.Crypto.IDigest digest
                                 )
        {
            Org.BouncyCastle.Asn1.DerObjectIdentifier      digestOid = this.m_oidMap[digest.AlgorithmName];
            Org.BouncyCastle.Asn1.X509.AlgorithmIdentifier algid     =
                new Org.BouncyCastle.Asn1.X509.AlgorithmIdentifier(
                    digestOid, Org.BouncyCastle.Asn1.DerNull.Instance
                    );

            Org.BouncyCastle.Asn1.X509.DigestInfo di =
                new Org.BouncyCastle.Asn1.X509.DigestInfo(algid, hash);

            return(di.GetDerEncoded());
        } // End Function DerEncode
Пример #9
0
        } // End Function HashData

        protected override byte[] HashData(System.IO.Stream data,
                                           System.Security.Cryptography.HashAlgorithmName hashAlgorithm)
        {
            Org.BouncyCastle.Crypto.IDigest digest = GetBouncyAlgorithm(hashAlgorithm);

            byte[] buffer = new byte[4096];
            int    cbSize;

            while ((cbSize = data.Read(buffer, 0, buffer.Length)) > 0)
            {
                digest.BlockUpdate(buffer, 0, cbSize);
            }

            byte[] hash = new byte[digest.GetDigestSize()];
            digest.DoFinal(hash, 0);
            return(hash);
        } // End Function HashData
 public BouncyCastlePaddingHash(int keyBits)
 {
     if (keyBits >= 2048)
     {
         _digest = new Org.BouncyCastle.Crypto.Digests.Sha512Digest();
         return;
     }
     if (keyBits < 1024)
     {
         _digest = new Org.BouncyCastle.Crypto.Digests.MD5Digest();
         return;
     }
     if (keyBits < 2048)
     {
         _digest = new Org.BouncyCastle.Crypto.Digests.Sha256Digest();
         return;
     }
 }
Пример #11
0
        public WindowsPrng()
        {
            // Don't use the bugged CryptoAPI
            // this.m_rnd = new Org.BouncyCastle.Crypto.Prng.CryptoApiRandomGenerator();

            Org.BouncyCastle.Crypto.IDigest digest = Org.BouncyCastle.Security.DigestUtilities.GetDigest("SHA256");
            if (digest == null)
            {
                return;
            }

            Org.BouncyCastle.Crypto.Prng.DigestRandomGenerator prng =
                new Org.BouncyCastle.Crypto.Prng.DigestRandomGenerator(digest);

            prng.AddSeedMaterial(NextCounterValue());
            prng.AddSeedMaterial(GetNextBytes(digest.GetDigestSize()));

            this.m_rnd = prng;
        }
Пример #12
0
        private static byte[] GetByteRangeDigest(PdfDocument document, PdfPKCS7 pkcs7, PdfSignature signature, string digestAlg)
        {
            Org.BouncyCastle.Crypto.IDigest         digest = Org.BouncyCastle.Security.DigestUtilities.GetDigest(digestAlg);
            iText.Kernel.Pdf.PdfArray               b      = signature.GetByteRange();
            iText.IO.Source.RandomAccessFileOrArray rf     = document.GetReader().GetSafeFile();
            Stream rg = null;

            try
            {
                rg = new iText.IO.Source.RASInputStream(new iText.IO.Source.RandomAccessSourceFactory().CreateRanged(rf.CreateSourceView(), b.ToLongArray(
                                                                                                                         )));
                byte[] buf = new byte[8192];
                int    rd;
                while ((rd = rg.Read(buf, 0, buf.Length)) > 0)
                {
                    digest.BlockUpdate(buf, 0, rd);
                }

                byte[] dig = new byte[digest.GetDigestSize()];
                digest.DoFinal(dig, 0);
                return(dig);
            }
            catch (Exception e)
            {
                throw new iText.Kernel.PdfException(e);
            }
            finally
            {
                try
                {
                    if (rg != null)
                    {
                        rg.Dispose();
                    }
                }
                catch (System.IO.IOException e)
                {
                    // this really shouldn't ever happen - the source view we use is based on a Safe view, which is a no-op anyway
                    throw new iText.Kernel.PdfException(e);
                }
            }
        }
Пример #13
0
 /// <summary>
 ///   Wrap the bouncy castle digest.
 /// </summary>
 public BouncyDigest(Org.BouncyCastle.Crypto.IDigest digest)
 {
     this.digest = digest;
 }
Пример #14
0
 public static byte[] Digest(Org.BouncyCastle.Crypto.IDigest d, byte[] b)
 {
     return(Digest(d, b, 0, b.Length));
 }
Пример #15
0
 /**
  * Creates a hash using a specific digest algorithm and a provider.
  * @param data  the message of which you want to create a hash
  * @param hashAlgorithm the algorithm used to create the hash
  * @param provider  the provider used to create the hash
  * @return  the hash
  * @throws GeneralSecurityException
  * @throws IOException
  */
 public static byte[] Digest(System.IO.Stream data, string hashAlgorithm)
 {
     Org.BouncyCastle.Crypto.IDigest messageDigest = GetMessageDigest(hashAlgorithm);
     return(Digest(data, messageDigest));
 }
Пример #16
0
        private bool VerifyHashInternal(
            byte[] hash
            , byte[] signature
            , Org.BouncyCastle.Crypto.IDigest digest
            , bool asOaep)
        {
            Org.BouncyCastle.Crypto.IAsymmetricBlockCipher rsaEngine = null;

            if (asOaep) // PSS:
            {
                rsaEngine =
                    new Org.BouncyCastle.Crypto.Encodings.OaepEncoding(
                        new Org.BouncyCastle.Crypto.Engines.RsaBlindedEngine()
                        );
            }
            else // Pkcs1
            {
                rsaEngine =
                    new Org.BouncyCastle.Crypto.Encodings.Pkcs1Encoding(
                        new Org.BouncyCastle.Crypto.Engines.RsaBlindedEngine()
                        );
            }
            rsaEngine.Init(false, this.m_keyPair.Public);
            byte[] a = null;
            byte[] b = null;

            try
            {
                a = rsaEngine.ProcessBlock(signature, 0, signature.Length);
                b = this.DerEncode(hash, digest);
            }
            catch
            {
                return(false);
            }

            if (a.Length == b.Length)
            {
                return(Org.BouncyCastle.Utilities.Arrays.ConstantTimeAreEqual(a, b));
            }
            if (a.Length != b.Length - 2)
            {
                return(false);
            }

            int num1 = a.Length - hash.Length - 2;
            int num2 = b.Length - hash.Length - 2;

            b[1] -= (byte)2;
            b[3] -= (byte)2;

            int num3 = 0;

            for (int index = 0; index < hash.Length; ++index)
            {
                num3 |= (int)a[num1 + index] ^ (int)b[num2 + index];
            }

            for (int index = 0; index < num1; ++index)
            {
                num3 |= (int)a[index] ^ (int)b[index];
            }

            return(num3 == 0);
        } // End Function VerifyHashInternal