Exemple #1
0
        public static void NegativeVerify_BadKeysize()
        {
            byte[] signature;

            using (RSA rsa = RSAFactory.Create())
            {
                rsa.ImportParameters(TestData.RSA2048Params);
                signature = rsa.SignData(TestData.HelloBytes, HashAlgorithmName.SHA1, RSASignaturePadding.Pkcs1);
            }

            using (RSA rsa = RSAFactory.Create())
            {
                rsa.ImportParameters(TestData.RSA1024Params);
                bool signatureMatched = rsa.VerifyData(TestData.HelloBytes, signature, HashAlgorithmName.SHA1, RSASignaturePadding.Pkcs1);

                Assert.False(signatureMatched);
            }
        }
Exemple #2
0
        public static void ExportAfterDispose(bool importKey)
        {
            RSA rsa = importKey ? RSAFactory.Create(TestData.RSA2048Params) : RSAFactory.Create(1024);

            // Ensure that the key got created, and then Dispose it.
            using (rsa)
            {
                rsa.Encrypt(TestData.HelloBytes, RSAEncryptionPadding.Pkcs1);
            }

            Assert.Throws <ObjectDisposedException>(() => rsa.ExportParameters(false));
            Assert.Throws <ObjectDisposedException>(() => rsa.ExportParameters(true));

            if (!(PlatformDetection.IsFullFramework && rsa.GetType().Name.EndsWith("Cng")))
            {
                Assert.Throws <ObjectDisposedException>(() => rsa.ImportParameters(TestData.RSA1024Params));
            }
        }
        public static void InvalidHashAlgorithm()
        {
            using (RSA rsa = RSAFactory.Create())
            {
                var formatter   = new RSAPKCS1SignatureFormatter(rsa);
                var deformatter = new RSAPKCS1SignatureDeformatter(rsa);

                // Exception is deferred until VerifySignature
                formatter.SetHashAlgorithm("INVALIDVALUE");
                deformatter.SetHashAlgorithm("INVALIDVALUE");

                using (SHA1 alg = SHA1.Create())
                {
                    Assert.Throws <CryptographicUnexpectedOperationException>(() =>
                                                                              VerifySignature(formatter, deformatter, alg, "INVALIDVALUE"));
                }
            }
        }
Exemple #4
0
        public static void ImportFromPem_Pkcs8AlgorithmMismatch_Throws()
        {
            using (RSA rsa = RSAFactory.Create())
            {
                string pem = @"
The below PEM is a 1024-bit DSA key.
-----BEGIN PRIVATE KEY-----
MIIBSgIBADCCASsGByqGSM44BAEwggEeAoGBAL5KGXEaazCA+k1pMcCBc/+bodFh
0P4U2QDLyDtnmytusGPaHcFp69pVdJZWMBycwJdaFQkraQNmqQsjAmBHtpqMeJpE
VLgjzve83oMAw5aysmaQC4Wy35vnBZnshvdzgbPRHZD2dWmFvWxToqBnxh74rb/H
Nkpt8JrirFOdNuyvAhUA9+LZ6XHLZZKeFhDxYl+a9lYabdsCgYACRi+pc9joLRah
A9ushrXVItFyOsq45hOB9hT37nyTEmane/YAjmoR28XyDYdF/Ql97iSVm3cY3OYT
eDr38gQ/Hk0CgW3/RFrNWdbIpfMifs80vqCUNqDggcQixEmDVZ0gwq4+wz8EVyYG
42+vM7ajN4O2VGvCA99Vl6zv69hOpAQWAhQtFFLZyKAUOQwUQh4hNw+oBgPhFw==
-----END PRIVATE KEY-----";
                Assert.Throws <CryptographicException>(() => rsa.ImportFromPem(pem));
            }
        }
Exemple #5
0
        public static void ImportNoModulus()
        {
            RSAParameters imported = new RSAParameters
            {
                Exponent = TestData.RSA1024Params.Exponent,
            };

            using (RSA rsa = RSAFactory.Create())
            {
                if (rsa is RSACng && PlatformDetection.IsFullFramework)
                {
                    AssertExtensions.Throws <ArgumentException>(null, () => rsa.ImportParameters(imported));
                }
                else
                {
                    Assert.ThrowsAny <CryptographicException>(() => rsa.ImportParameters(imported));
                }
            }
        }
Exemple #6
0
        public static void ImportExport1032()
        {
            RSAParameters imported = TestData.RSA1032Parameters;
            RSAParameters exported;
            RSAParameters exportedPublic;

            using (RSA rsa = RSAFactory.Create())
            {
                rsa.ImportParameters(imported);
                exported       = rsa.ExportParameters(true);
                exportedPublic = rsa.ExportParameters(false);
            }

            AssertKeyEquals(imported, exported);

            Assert.Equal(exportedPublic.Modulus, imported.Modulus);
            Assert.Equal(exportedPublic.Exponent, imported.Exponent);
            Assert.Null(exportedPublic.D);
        }
Exemple #7
0
        public static void ImportFromEncryptedPem_NoEncryptedPem()
        {
            using (RSA rsa = RSAFactory.Create())
            {
                string            pem = @"
-----BEGIN PRIVATE KEY-----
MIIBVQIBADANBgkqhkiG9w0BAQEFAASCAT8wggE7AgEAAkEAtz9Z9e6L1V4kt/8C
mtFqhUPJbSU+VDGbk1MsQcPBR3uJ2y0vM9e5qHRYSOBqjmg7UERRHhvKNiUn4Xz0
KzgGFQIDAQABAkEAr+byNi+cr17FpJH4MCEiPXaKnmkH4c4U52EJtL9yg2gijBrp
Ykat3c2nWb0EGGi5aWgXxQHoi7z97/ACD4X3KQIhAPNyex6GdiBVlNPHOgInTU8a
mARKKVHIXM0SxvxXrRl7AiEAwLI66OpSqftDTv1KUfNe6+hyoh23ggzUSYiWuVT0
Ya8CHwiO/cUU9RIt8A2B84gf2ZfuV2nPMaSuZpTPFC/K5UsCIQCsJMzx1JuilQAN
acPiMCuFTnRSFYAhozpmsqoLyTREqwIhAMLJlZTGjEB2N+sEazH5ToEczQzKqp7t
9juGNbOPhoEL
-----END PRIVATE KEY-----";
                ArgumentException ae  = AssertExtensions.Throws <ArgumentException>("input", () =>
                                                                                    rsa.ImportFromEncryptedPem(pem, "test" u8));
                Assert.Contains(NoPemExceptionMarker, ae.Message);
            }
        }
Exemple #8
0
        private void ExpectHashSignature(
            byte[] expectedSignature,
            byte[] dataHash,
            string hashAlgorithmName,
            RSAParameters rsaParameters)
        {
            // RSA signatures use PKCS 1.5 EMSA encoding (encoding method, signature algorithm).
            // EMSA specifies a fixed filler type of { 0x01, 0xFF, 0xFF ... 0xFF, 0x00 } whose length
            // is as long as it needs to be to match the block size.  Since the filler is deterministic,
            // the signature is deterministic, so we can safely verify it here.
            byte[] signature;

            using (RSA rsa = RSAFactory.Create())
            {
                rsa.ImportParameters(rsaParameters);
                signature = SignHash(rsa, dataHash, new HashAlgorithmName(hashAlgorithmName), RSASignaturePadding.Pkcs1);
            }

            Assert.Equal(expectedSignature, signature);
        }
Exemple #9
0
        public void RsaDecryptPkcs1LeadingZero()
        {
            // The first search for an encrypted value with a leading 0x00 turned up one with
            // two leading zeros.  How fortuitous.
            byte[] encrypted = (
                "0000B81E93CB9BA2B096DAC80ADC0C053D15CAD79A09D3DC154E3E75E0F59AF0" +
                "D0816C0946946A56FEAEDB951A49C3854966C01C47A9F54DE2A050C1625869FE" +
                "02BAD7AA427C42FE79D31267AE8713504CBBBBFA28EED0DF3E9F5BFC12C8A701" +
                "382E92BC50D7E9E9897AEBDDA8005B7906AE1ABAFFD30CF5A8733CAB7264445A" +
                "333730EA31F5F9F120B4B59F689BA529E106DA78340678C3BA2CE46427375A84" +
                "9E86950FC18BD1D6C33508596BAEF0D916F0E29D647C037022753B1E8E44ABCF" +
                "0079CEFA8972F02D05C4204078BD9ADF98571CE5374AB94BF01918F0EA31A815" +
                "59F065A4C3FA0DD0E3086530608CA54387F86F25ED77D46C7576376B64BE3C91").HexToByteArray();

            using (RSA rsa = RSAFactory.Create(TestData.RSA2048Params))
            {
                byte[] decrypted = Decrypt(rsa, encrypted, RSAEncryptionPadding.Pkcs1);
                Assert.Equal(TestData.HelloBytes, decrypted);
            }
        }
Exemple #10
0
        public void RsaDecryptOaep_ExpectFailure()
        {
            // This particular byte pattern, when decrypting under OAEP-SHA-2-384 has
            // an 0x01 in the correct range, and y=0, but lHash and lHashPrime do not agree
            byte[] encrypted = (
                "2A1914D11E2F6B9E286DAC9D76F32A008EC31457522CEA058D7C48C85085899F" +
                "E9C2DBD4FCA5FAD936F2B747E0BEF131217F8521FA921DF807A83C1B34DB1547" +
                "8D637EDFED222B6411C80D465332B2EE5208F87D4F8D1736FEBC291E14E77C4B" +
                "75A1F06B5124F225F310BFFA83BCA9F11101BA67A64109C37F52BF00B84FFD9A" +
                "D39282AD2BA9EEADADA0FE38998755B556B152EE8974F2C8158ACFA5F509DD4A" +
                "BFE72218C0DF596DFF02C332F45ECC04280455F5D2666E93A3522BB8B41FC92E" +
                "0176AFB1D3A5AE474B708B882ACA88447046E13D44E5EA8D66421DFC177A683B" +
                "7B395F18886AAFD9CED072079739ED1D390354976D188C50A29AAD58784886E6").HexToByteArray();

            using (RSA rsa = RSAFactory.Create(TestData.RSA2048Params))
            {
                Assert.ThrowsAny <CryptographicException>(
                    () => Decrypt(rsa, encrypted, RSAEncryptionPadding.OaepSHA384));
            }
        }
        public static void ImportFromPem_SubjectPublicKeyInfo_IgnoresUnrelatedAlgorithm()
        {
            using (RSA rsa = RSAFactory.Create())
            {
                string pem = @"
-----BEGIN EC PRIVATE KEY-----
MHcCAQEEIHChLC2xaEXtVv9oz8IaRys/BNfWhRv2NJ8tfVs0UrOKoAoGCCqGSM49
AwEHoUQDQgAEgQHs5HRkpurXDPaabivT2IaRoyYtIsuk92Ner/JmgKjYoSumHVmS
NfZ9nLTVjxeD08pD548KWrqmJAeZNsDDqQ==
-----END EC PRIVATE KEY-----
-----BEGIN PUBLIC KEY-----
MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBALc/WfXui9VeJLf/AprRaoVDyW0lPlQx
m5NTLEHDwUd7idstLzPXuah0WEjgao5oO1BEUR4byjYlJ+F89Cs4BhUCAwEAAQ==
-----END PUBLIC KEY-----";
                rsa.ImportFromPem(pem);
                RSAParameters rsaParameters = rsa.ExportParameters(false);

                ImportExport.AssertKeyEquals(TestData.DiminishedDPParameters.ToPublic(), rsaParameters);
            }
        }
        public static void ImportFromPem_RSAPrivateKey_Simple()
        {
            using (RSA rsa = RSAFactory.Create())
            {
                string pem = @"
-----BEGIN RSA PRIVATE KEY-----
MIIBOwIBAAJBALc/WfXui9VeJLf/AprRaoVDyW0lPlQxm5NTLEHDwUd7idstLzPX
uah0WEjgao5oO1BEUR4byjYlJ+F89Cs4BhUCAwEAAQJBAK/m8jYvnK9exaSR+DAh
Ij12ip5pB+HOFOdhCbS/coNoIowa6WJGrd3Np1m9BBhouWloF8UB6Iu8/e/wAg+F
9ykCIQDzcnsehnYgVZTTxzoCJ01PGpgESilRyFzNEsb8V60ZewIhAMCyOujqUqn7
Q079SlHzXuvocqIdt4IM1EmIlrlU9GGvAh8Ijv3FFPUSLfANgfOIH9mX7ldpzzGk
rmaUzxQvyuVLAiEArCTM8dSbopUADWnD4jArhU50UhWAIaM6ZrKqC8k0RKsCIQDC
yZWUxoxAdjfrBGsx+U6BHM0Myqqe7fY7hjWzj4aBCw==
-----END RSA PRIVATE KEY-----";

                rsa.ImportFromPem(pem);
                RSAParameters rsaParameters = rsa.ExportParameters(true);

                ImportExport.AssertKeyEquals(TestData.DiminishedDPParameters, rsaParameters);
            }
        }
Exemple #13
0
        public void RsaDecryptOaepWrongData()
        {
            using (RSA rsa = RSAFactory.Create(TestData.RSA2048Params))
            {
                byte[] data      = TestData.HelloBytes;
                byte[] encrypted = Encrypt(rsa, data, RSAEncryptionPadding.OaepSHA1);
                encrypted[1] ^= 0xFF;

                Assert.ThrowsAny <CryptographicException>(
                    () => Decrypt(rsa, encrypted, RSAEncryptionPadding.OaepSHA1));

                if (RSAFactory.SupportsSha2Oaep)
                {
                    encrypted     = Encrypt(rsa, data, RSAEncryptionPadding.OaepSHA256);
                    encrypted[1] ^= 0xFF;

                    Assert.ThrowsAny <CryptographicException>(
                        () => Decrypt(rsa, encrypted, RSAEncryptionPadding.OaepSHA256));
                }
            }
        }
        public static void ImportFromPem_EncryptedPrivateKeyFails()
        {
            using (RSA rsa = RSAFactory.Create())
            {
                string            pem = @"
-----BEGIN ENCRYPTED PRIVATE KEY-----
MIIBsTBLBgkqhkiG9w0BBQ0wPjApBgkqhkiG9w0BBQwwHAQIioaQaFwlfasCAggA
MAwGCCqGSIb3DQIJBQAwEQYFKw4DAgcECJLGzSuIgnSkBIIBYHofFpp5AsrkNc9w
s0uebkLBgMXbmhu+t6XQYXhnZXguT4KF4g49vIE3XwtZkXzEeSrNRIWZcPH1UWp2
qbv2d+ub3wBpMdFDzv5Zty6e6gACWwyMRy/oX8gZqWDfDnQwm7BV21yLANEFnRuT
K3c9EmQ9IAT2MLLRUeijyg6KUL0dZ5VmXbtQdDoovuhzU20HjSyQLXNbX8NzUhWy
VMuNHs8NhiIgOuFKMoqlN42LBA1+iOA4MGR5XDXXmGyKPLCs0USbD9Dm4/Q1h7Fs
x2yC94Mej7kgAusuNZk9GafsIQbM7jZT1PLxIKyMXAxIpS9sIYbegxK774npiy8/
LiBC1SQXJ3sJdAeUE0QPJEci937f8SteWUmF5mUqznb/0nYjvSZh/GcZ4GWEAO8j
RkMxT/C7OZVMOlb3HV3fJj7kDmOMqfc6aKEQjLdWtuYRB8CgaudldIpK4jP2+0b5
pBORBb0=
-----END ENCRYPTED PRIVATE KEY-----";
                ArgumentException ae  = AssertExtensions.Throws <ArgumentException>("input", () => rsa.ImportFromPem(pem));
                Assert.Contains(EncryptedExceptionMarker, ae.Message);
            }
        }
        public static void ImportFromPem_RSAPrivateKey_AmbiguousKey_EncryptedPkcs8()
        {
            using (RSA rsa = RSAFactory.Create())
            {
                string            pem = @"
-----BEGIN ENCRYPTED PRIVATE KEY-----
MII=
-----END ENCRYPTED PRIVATE KEY-----
-----BEGIN RSA PRIVATE KEY-----
MIIBOwIBAAJBALc/WfXui9VeJLf/AprRaoVDyW0lPlQxm5NTLEHDwUd7idstLzPX
uah0WEjgao5oO1BEUR4byjYlJ+F89Cs4BhUCAwEAAQJBAK/m8jYvnK9exaSR+DAh
Ij12ip5pB+HOFOdhCbS/coNoIowa6WJGrd3Np1m9BBhouWloF8UB6Iu8/e/wAg+F
9ykCIQDzcnsehnYgVZTTxzoCJ01PGpgESilRyFzNEsb8V60ZewIhAMCyOujqUqn7
Q079SlHzXuvocqIdt4IM1EmIlrlU9GGvAh8Ijv3FFPUSLfANgfOIH9mX7ldpzzGk
rmaUzxQvyuVLAiEArCTM8dSbopUADWnD4jArhU50UhWAIaM6ZrKqC8k0RKsCIQDC
yZWUxoxAdjfrBGsx+U6BHM0Myqqe7fY7hjWzj4aBCw==
-----END RSA PRIVATE KEY-----";
                ArgumentException ae  = AssertExtensions.Throws <ArgumentException>("input", () => rsa.ImportFromPem(pem));
                Assert.Contains(AmbiguousExceptionMarker, ae.Message);
            }
        }
        public static void ImportFromPem_Pkcs8UnEncrypted_Simple()
        {
            using (RSA rsa = RSAFactory.Create())
            {
                string pem = @"
-----BEGIN PRIVATE KEY-----
MIIBVQIBADANBgkqhkiG9w0BAQEFAASCAT8wggE7AgEAAkEAtz9Z9e6L1V4kt/8C
mtFqhUPJbSU+VDGbk1MsQcPBR3uJ2y0vM9e5qHRYSOBqjmg7UERRHhvKNiUn4Xz0
KzgGFQIDAQABAkEAr+byNi+cr17FpJH4MCEiPXaKnmkH4c4U52EJtL9yg2gijBrp
Ykat3c2nWb0EGGi5aWgXxQHoi7z97/ACD4X3KQIhAPNyex6GdiBVlNPHOgInTU8a
mARKKVHIXM0SxvxXrRl7AiEAwLI66OpSqftDTv1KUfNe6+hyoh23ggzUSYiWuVT0
Ya8CHwiO/cUU9RIt8A2B84gf2ZfuV2nPMaSuZpTPFC/K5UsCIQCsJMzx1JuilQAN
acPiMCuFTnRSFYAhozpmsqoLyTREqwIhAMLJlZTGjEB2N+sEazH5ToEczQzKqp7t
9juGNbOPhoEL
-----END PRIVATE KEY-----";

                rsa.ImportFromPem(pem);
                RSAParameters rsaParameters = rsa.ExportParameters(true);

                ImportExport.AssertKeyEquals(TestData.DiminishedDPParameters, rsaParameters);
            }
        }
Exemple #17
0
        private void VerifyHashSignature(
            byte[] signature,
            byte[] dataHash,
            string hashAlgorithmName,
            RSAParameters rsaParameters)
        {
            RSAParameters publicOnly = new RSAParameters
            {
                Modulus  = rsaParameters.Modulus,
                Exponent = rsaParameters.Exponent,
            };

            bool signatureMatched;

            using (RSA rsa = RSAFactory.Create())
            {
                rsa.ImportParameters(publicOnly);
                signatureMatched = VerifyHash(rsa, dataHash, signature, new HashAlgorithmName(hashAlgorithmName), RSASignaturePadding.Pkcs1);
            }

            Assert.True(signatureMatched);
        }
Exemple #18
0
        public static void UnusualExponentImportExport()
        {
            // Most choices for the Exponent value in an RSA key use a Fermat prime.
            // Since a Fermat prime is 2^(2^m) + 1, it always only has two bits set, and
            // frequently has the form { 0x01, [some number of 0x00s], 0x01 }, which has the same
            // representation in both big- and little-endian.
            //
            // The only real requirement for an Exponent value is that it be coprime to (p-1)(q-1).
            // So here we'll use the (non-Fermat) prime value 433 (0x01B1) to ensure big-endian export.
            RSAParameters unusualExponentParameters = TestData.UnusualExponentParameters;
            RSAParameters exported;

            using (RSA rsa = RSAFactory.Create())
            {
                rsa.ImportParameters(unusualExponentParameters);
                exported = rsa.ExportParameters(true);
            }

            // Exponent is the most likely to fail, the rest just otherwise ensure that Export
            // isn't losing data.
            AssertKeyEquals(unusualExponentParameters, exported);
        }
Exemple #19
0
        private void RsaCryptRoundtrip(RSAEncryptionPadding paddingMode, bool expectSuccess = true)
        {
            byte[] crypt;
            byte[] output;

            using (RSA rsa = RSAFactory.Create(2048))
            {
                if (!expectSuccess)
                {
                    Assert.ThrowsAny <CryptographicException>(
                        () => Encrypt(rsa, TestData.HelloBytes, paddingMode));

                    return;
                }

                crypt  = Encrypt(rsa, TestData.HelloBytes, paddingMode);
                output = Decrypt(rsa, crypt, paddingMode);
            }

            Assert.NotEqual(crypt, output);
            Assert.Equal(TestData.HelloBytes, output);
        }
Exemple #20
0
        public void RsaDecryptOaepWrongDataLength()
        {
            using (RSA rsa = RSAFactory.Create(TestData.RSA2048Params))
            {
                byte[] data = TestData.HelloBytes;

                byte[] encrypted = Encrypt(rsa, data, RSAEncryptionPadding.OaepSHA1);
                Array.Resize(ref encrypted, encrypted.Length + 1);

                if (!PlatformDetection.IsNetFramework)
                {
                    Assert.ThrowsAny <CryptographicException>(
                        () => Decrypt(rsa, encrypted, RSAEncryptionPadding.OaepSHA1));
                }

                Array.Resize(ref encrypted, encrypted.Length - 2);

                Assert.ThrowsAny <CryptographicException>(
                    () => Decrypt(rsa, encrypted, RSAEncryptionPadding.OaepSHA1));

                if (RSAFactory.SupportsSha2Oaep)
                {
                    encrypted = Encrypt(rsa, data, RSAEncryptionPadding.OaepSHA256);
                    Array.Resize(ref encrypted, encrypted.Length + 1);

                    if (!PlatformDetection.IsNetFramework)
                    {
                        Assert.ThrowsAny <CryptographicException>(
                            () => Decrypt(rsa, encrypted, RSAEncryptionPadding.OaepSHA256));
                    }

                    Array.Resize(ref encrypted, encrypted.Length - 2);

                    Assert.ThrowsAny <CryptographicException>(
                        () => Decrypt(rsa, encrypted, RSAEncryptionPadding.OaepSHA256));
                }
            }
        }
        public static void ImportFromEncryptedPem_Pkcs8Encrypted_Char_Simple()
        {
            using (RSA rsa = RSAFactory.Create())
            {
                string pem = @"
-----BEGIN ENCRYPTED PRIVATE KEY-----
MIIBsTBLBgkqhkiG9w0BBQ0wPjApBgkqhkiG9w0BBQwwHAQIcvgI1lw9LqYCAggA
MAwGCCqGSIb3DQIJBQAwEQYFKw4DAgcECFDpLREQXt5pBIIBYOKuM5ljAvCViDL+
nTFq7A/fI9rqdL20TMdf0wy7s43oXmsw5gCStoNEaoVToFCQWYYBRU99mK8YNFA8
1ZJT53SDS7buJ0zX9oDltf2ByXRPI4mn2Il2HZvN2hi9ir1w8M3XoSFSurN9tC8r
IOiGkVfK9Ll54knONewNiCNefFZFctRfVMbac5SwHokCkBMHukl0oPrpVuBE8kRo
p7XtjM8ILtzLVz0iLqKXiNIf6kRdouCBmCn8VIQgIvPPIHD8vheMXWjN7g69P5n4
1YI4c/acljcofmq1BBPTwvxaETrg2NHW0XMIgAxoaVP8lIIGlNk1glWTYpuMd69L
AWvBUt33Sozc+dF0l7NGLAWL2tqkkpyDQuKn6UgYz/vxkFeQAVfSuaJVR+fUlHg0
N4lD7/hJq7b+yYPhlN3Fvvt8M9MtRg1TLAve67CA2v4TITHB06M/ELe3y42bZuLW
CA7ffFk=
-----END ENCRYPTED PRIVATE KEY-----";
                rsa.ImportFromEncryptedPem(pem, "test");
                RSAParameters rsaParameters = rsa.ExportParameters(true);

                ImportExport.AssertKeyEquals(TestData.DiminishedDPParameters, rsaParameters);
            }
        }
Exemple #22
0
        public void RsaDecryptPkcs1WrongDataLength()
        {
            using (RSA rsa = RSAFactory.Create(TestData.RSA2048Params))
            {
                byte[] data = TestData.HelloBytes;

                byte[] encrypted = Encrypt(rsa, data, RSAEncryptionPadding.Pkcs1);
                Array.Resize(ref encrypted, encrypted.Length + 1);

                // Baseline/exempt a .NET Framework difference for RSACng
                if (!PlatformDetection.IsNetFramework ||
                    rsa.GetType().Assembly.GetName().Name != "System.Core")
                {
                    Assert.ThrowsAny <CryptographicException>(
                        () => Decrypt(rsa, encrypted, RSAEncryptionPadding.Pkcs1));
                }

                Array.Resize(ref encrypted, encrypted.Length - 2);

                Assert.ThrowsAny <CryptographicException>(
                    () => Decrypt(rsa, encrypted, RSAEncryptionPadding.Pkcs1));
            }
        }
        public static void ImportFromEncryptedPem_Pkcs8Encrypted_Byte_Simple()
        {
            using (RSA rsa = RSAFactory.Create())
            {
                string pem = @"
-----BEGIN ENCRYPTED PRIVATE KEY-----
MIIBvTBXBgkqhkiG9w0BBQ0wSjApBgkqhkiG9w0BBQwwHAQIciLWmWb33X0CAggA
MAwGCCqGSIb3DQIJBQAwHQYJYIZIAWUDBAECBBBVEmHhJdbi+HKzPttNjXm4BIIB
YFejknurbot2VDXwc671A0mfA0cw/u7K44gsYXcZwAARC8j6f3lSzB0tN2kMEx/L
TB+kpMBbfAoIPKoEc9Y4w9m3NXkQYrLRONh9AFiAnOjULHwkstQfN2ofFlolDfbH
hAE6ga6aQJTQ8rDKTL4QkCg+s+qWlicPqs5ikSQfUz2Qiy8FKe7zZlJ0OWpT+zk7
EYRrUSKQcEAjfNS7anlMps2ZXRc1LkLJNHZSl6h2BuFPfIKEV9REpy3Y7sH7vNZZ
PWPa9/xM4CX/c/ommy6LqvZikUuUGc56/Hbz65SwG3voivIhOTmM28LiA6z0YXmY
E+nr7hyinl51raM1RSHojJB22oOW+GwV7GgWYIjUgIEMDOhN10FcGNfTeC65PCXx
5QSEe7EKVF0aHXBYB5SzMGVuxR/BqydDa26jlhVzO3LNvy9FYuqLKUslCrBCmPrt
raZNyk8KAsLs+FJq9T2tda0=
-----END ENCRYPTED PRIVATE KEY-----";
                rsa.ImportFromEncryptedPem(pem, Encoding.UTF8.GetBytes("test"));
                RSAParameters rsaParameters = rsa.ExportParameters(true);

                ImportExport.AssertKeyEquals(TestData.DiminishedDPParameters, rsaParameters);
            }
        }
Exemple #24
0
        public void RoundtripEmptyArray()
        {
            using (RSA rsa = RSAFactory.Create(TestData.RSA2048Params))
            {
                void RoundtripEmpty(RSAEncryptionPadding paddingMode)
                {
                    byte[] encrypted = Encrypt(rsa, Array.Empty <byte>(), paddingMode);
                    byte[] decrypted = Decrypt(rsa, encrypted, paddingMode);

                    Assert.Equal(Array.Empty <byte>(), decrypted);
                }

                RoundtripEmpty(RSAEncryptionPadding.Pkcs1);
                RoundtripEmpty(RSAEncryptionPadding.OaepSHA1);

                if (RSAFactory.SupportsSha2Oaep)
                {
                    RoundtripEmpty(RSAEncryptionPadding.OaepSHA256);
                    RoundtripEmpty(RSAEncryptionPadding.OaepSHA384);
                    RoundtripEmpty(RSAEncryptionPadding.OaepSHA512);
                }
            }
        }
Exemple #25
0
        public void DecryptWithPublicKey_Fails()
        {
            byte[] cipherBytes =
            {
                0x35, 0x6F, 0x8F, 0x2C, 0x4D, 0x1A, 0xAC, 0x6D,
                0xE7, 0x52, 0xA5, 0xDF, 0x26, 0x54, 0xA6, 0x34,
                0xF5, 0xBB, 0x14, 0x26, 0x1C, 0xE4, 0xDC, 0xA2,
                0xD8, 0x4D, 0x8F, 0x1C, 0x55, 0xD4, 0xC7, 0xA7,
                0xF2, 0x3C, 0x99, 0x77, 0x9F, 0xE4, 0xB7, 0x34,
                0xA6, 0x28, 0xB2, 0xC4, 0xFB, 0x6F, 0x85, 0xCA,
                0x19, 0x21, 0xCA, 0xC1, 0xA7, 0x8D, 0xAE, 0x95,
                0xAB, 0x9B, 0xA9, 0x88, 0x5B, 0x44, 0xC6, 0x9B,
                0x44, 0x26, 0x71, 0x5D, 0x02, 0x3F, 0x43, 0x42,
                0xEF, 0x4E, 0xEE, 0x09, 0x87, 0xEF, 0xCD, 0xCF,
                0xF9, 0x88, 0x99, 0xE8, 0x49, 0xF7, 0x8F, 0x9B,
                0x59, 0x68, 0x20, 0xF3, 0xA7, 0xB2, 0x94, 0xA4,
                0x23, 0x70, 0x83, 0xD9, 0xAC, 0xE7, 0x5E, 0xEE,
                0xE9, 0x7B, 0xE4, 0x4F, 0x73, 0x2E, 0x9B, 0xD8,
                0x2A, 0x75, 0xFB, 0x6C, 0xB9, 0x39, 0x6D, 0x72,
                0x8A, 0x9C, 0xCD, 0x58, 0x1A, 0x27, 0x79, 0x97,
            };

            using (RSA rsa = RSAFactory.Create())
            {
                RSAParameters parameters    = TestData.RSA1024Params;
                RSAParameters pubParameters = new RSAParameters
                {
                    Modulus  = parameters.Modulus,
                    Exponent = parameters.Exponent,
                };

                rsa.ImportParameters(pubParameters);

                Assert.ThrowsAny <CryptographicException>(
                    () => Decrypt(rsa, cipherBytes, RSAEncryptionPadding.OaepSHA1));
            }
        }
Exemple #26
0
        public void RsaPkcsEncryptMaxSize()
        {
            RSAParameters rsaParameters = TestData.RSA2048Params;

            using (RSA rsa = RSAFactory.Create(rsaParameters))
            {
                RSAEncryptionPadding paddingMode1 = RSAEncryptionPadding.Pkcs1;
                // The overhead required is 8 + 3 => 11.

                const int Pkcs1Overhead = 11;
                int       maxSize       = rsaParameters.Modulus.Length - Pkcs1Overhead;

                byte[] data      = new byte[maxSize];
                byte[] encrypted = Encrypt(rsa, data, paddingMode1);
                byte[] decrypted = Decrypt(rsa, encrypted, paddingMode1);

                Assert.Equal(data.ByteArrayToHex(), decrypted.ByteArrayToHex());

                data = new byte[maxSize + 1];

                Assert.ThrowsAny <CryptographicException>(
                    () => Encrypt(rsa, data, paddingMode1));
            }
        }