public void TestLoggerEncryption()
        {
            var     result          = LoggerHelper.CreateLogger("Deim Vadder sein Service", null, null);
            var     logger          = result.logger;
            dynamic logResult       = new ExpandoObject();
            bool    exceptionThrown = false;

            try
            {
                LoggerHelper.CreateTraceObject("das ist ein verschlüsselter test", true, "Köaäasdaspfe");
            }
            catch (FormatException)
            {
                exceptionThrown = true;
            }
            Assert.True(exceptionThrown);
            var keyPair     = PublicKeyBox.GenerateKeyPair();
            var traceObject = LoggerHelper.CreateTraceObject("das ist ein verschlüsselter test", true, Convert.ToBase64String(keyPair.PublicKey));

            logger.LogTrace(traceObject);
            var message = result.loggerProvider.Messages[0].Message;

            Encrypter       dec     = new AsymmetricEncrypter(keyPair.PrivateKey);
            JToken          content = JObject.Parse(message).GetValue("Content");
            EncryptedObject eo      = JsonConvert.DeserializeObject <EncryptedObjectPublicKeyBox>(content.ToString());
            BusinessObject  bo      = dec.Decrypt(eo);

            Assert.NotNull(bo);
            Assert.Equal(1, bo.VersionStruktur);
            LogObject lo = bo as LogObject;

            Assert.Equal("das ist ein verschlüsselter test", lo.LogMessage);
        }
Exemple #2
0
 public void TestLogObjectDecryption()
 {
     //byte[] publicKey = Convert.FromBase64String("C1RpdN5DO86swpkegPxEMB60yVSXYLta6PfSnHuYpxA=");
     byte[] privateKey = Convert.FromBase64String("7BSU9FLrvo8hSk58fs/vHTN4fmRFYbwvI9ZRKmTDt/o=");
     try
     {
         EncryptedObject eo  = JsonConvert.DeserializeObject <EncryptedObjectPublicKeyBox>("{\"versionStruktur\":1,\"boTyp\":\"ENCRYPTEDOBJECTPUBLICKEYBOX\",\"encryptionScheme\":1,\"nonce\":\"YRmjJpSb7irazqWbCwWvNWKlApIjGiRh\",\"cipherText\":\"H315B/1ualMyzg882cXXB2I8Ol19bQQ1RlzohUXIGvbY7xCtkVuZZXmTI3Ff1GLf7NoymoQKqW50k2jmBTsoSmFWhPwKxDlW9vdS71fzuJTXSgfEmXWEhez2cMuNo0CRP/jgWDDUDmu5R5jz0bB+/FxZECOfYR4WFuvTz4jM+G8=\",\"publicKey\":\"enRUmVbcBbnneJCnvaU+ldANIDc/wGfqTUVCtSkVwhU=\"}");
         Encrypter       dec = new AsymmetricEncrypter(privateKey);
         BusinessObject  bo  = dec.Decrypt(eo);
         Assert.IsInstanceOfType(bo, typeof(BO4E.BO.LogObject));
     }
     catch (JsonSerializationException)
     {
         // ToDo: add required attribute ID to json plain text before encryption.
     }
 }
        /// <summary>
        /// Creates log message; allows for encryption/obfuscation of sensitive information.
        /// </summary>
        /// <param name="content">log message itself</param>
        /// <param name="sensitive">set true if log message contains sensitive, privacy relevant or confidential information</param>
        /// <param name="key">base64 encoded public key (using libsodium PublicKeyBox encryption standard)</param>
        /// <returns></returns>
        public static string CreateTraceObject(string content, bool sensitive = false, string publicKey = null, string id = null)
        {
            dynamic obj = new ExpandoObject();

            obj.Sensitive = sensitive;
            if (sensitive)
            {
                if (publicKey == null)
                {
                    throw new ArgumentNullException("To encrypt sensitive data you have to provide a non-null public key");
                }
                byte[] publicKeyBytes;
                try
                {
                    publicKeyBytes = Convert.FromBase64String(publicKey);
                }
                catch (FormatException e)
                {
                    throw new FormatException($"The provided public key string '{publicKey}' is no valid base64 string: {e.Message}");
                }
                if (id == null)
                {
                    id = Guid.NewGuid().ToString();
                }
                KeyPair asykeyPairSender = PublicKeyBox.GenerateKeyPair(); // newly generated every single time???
                using (AsymmetricEncrypter enc = new AsymmetricEncrypter(asykeyPairSender))
                {
                    LogObject logObject = new LogObject
                    {
                        DateTime   = DateTime.UtcNow,
                        Id         = id,
                        LogMessage = content
                    };
                    obj.Content = enc.Encrypt(logObject, publicKey);
                }
            }
            else
            {
                obj.Content = content;
            }
            return(JsonConvert.SerializeObject(obj));
        }
Exemple #4
0
        public void TestBOEncryption()
        {
            //hubnet.StaticLogger.Logger = new Microsoft.Extensions.Logging.Debug.DebugLogger("Testlogger", (log, level) => { return true; });
            string[] files = Directory.GetFiles($"encrypterTests/bo/", "*.json"); //

            foreach (string testFile in files)
            {
                JObject json;
                using (StreamReader r = new StreamReader(testFile))
                {
                    string jsonString = r.ReadToEnd();
                    json = JsonConvert.DeserializeObject <JObject>(jsonString);
                }
                Assert.IsNotNull(json, $"The content of file {testFile} seems to be no valid JSON.");

                string boType = (string)json["boTyp"];
                Assert.IsNotNull(boType, $"The JSON content of file {testFile} is missing the obligatory 'boTyp' attribute.");

                BusinessObject bo = BO4E.BoMapper.MapObject(boType, json);
                Assert.IsNotNull(bo, $"The business object in file {testFile} is not a valid BO4E.");

                /******* symmetric test ******/
                byte[]          symkey       = SecretBox.GenerateKey();
                string          symkeyString = Convert.ToBase64String(symkey);
                EncryptedObject eo;
                using (SymmetricEncrypter se0 = new SymmetricEncrypter(symkey))
                {
                    eo = se0.Encrypt(bo, "Associated");
                }

                BusinessObject boDecrypted;
                using (SymmetricEncrypter se1 = new SymmetricEncrypter(symkeyString))
                {
                    boDecrypted = se1.Decrypt(eo);
                }
                string expectedString = JsonConvert.SerializeObject(bo);
                string actualString   = JsonConvert.SerializeObject(boDecrypted);
                Assert.AreEqual(expectedString, actualString, "Original and encrypted->decrypted object do not match!");

                /******* asymmetric test ******/
                var asykeyPairSender    = PublicKeyBox.GenerateKeyPair();
                var asykeyPairRecipient = PublicKeyBox.GenerateKeyPair();
                using (AsymmetricEncrypter asyenc = new AsymmetricEncrypter(asykeyPairSender))
                {
                    eo = asyenc.Encrypt(bo, Convert.ToBase64String(asykeyPairRecipient.PublicKey));
                }

                using (AsymmetricEncrypter asydec = new AsymmetricEncrypter(asykeyPairRecipient.PrivateKey))
                {
                    boDecrypted = asydec.Decrypt(eo);
                }
                expectedString = JsonConvert.SerializeObject(bo);
                actualString   = JsonConvert.SerializeObject(boDecrypted);
                Assert.AreEqual(expectedString, actualString, "Original and encrypted->decrypted object do not match!");

                /******* X509 + RSA test ******/
                // encrypt (without needing a private key)
                X509Certificate2 x509certPubl = new X509Certificate2(X509Certificate2.CreateFromCertFile("encrypterTests/publickey.cer"));
                using (X509AsymmetricEncrypter xasyEnc = new X509AsymmetricEncrypter(x509certPubl))// encrypter needs no private key!
                {
                    eo = xasyEnc.Encrypt(bo);
                }
                // decrypt (using a private key)
                AsymmetricCipherKeyPair keyPair;
                using (var reader = File.OpenText(@"encrypterTests/privatekey.pem")) // file containing RSA PKCS1 private key
                {
                    keyPair = (AsymmetricCipherKeyPair) new PemReader(reader).ReadObject();
                }

                // openssl genrsa -out privatekey.pem 2048
                // openssl req -new -x509 -key privatekey.pem -out publickey.cer -days 3650

                using (X509AsymmetricEncrypter xasydec = new X509AsymmetricEncrypter(keyPair.Private))
                {
                    boDecrypted = xasydec.Decrypt(eo);
                }
                expectedString = JsonConvert.SerializeObject(bo);
                actualString   = JsonConvert.SerializeObject(boDecrypted);
                Assert.IsTrue(expectedString == actualString, "Original and encrypted->decrypted object do not match!");

                /********** X509 + RSA multiple recipients *******/
                X509Certificate2 x509certPubl2 = new X509Certificate2(X509Certificate2.CreateFromCertFile("encrypterTests/publickey2.cer"));
                EncryptedObject  eoMultiple;
                using (X509AsymmetricEncrypter xasyEncMultiple = new X509AsymmetricEncrypter(new HashSet <X509Certificate2> {
                    x509certPubl, x509certPubl2
                }))                                                                                                                                          // encrypter needs not private key!
                {
                    eoMultiple = xasyEncMultiple.Encrypt(bo);
                }

                // decrypt (using both private keys)
                AsymmetricCipherKeyPair keyPair2;
                using (var reader = File.OpenText(@"encrypterTests/privatekey2.pem")) // file containing RSA PKCS1 private key
                {
                    keyPair2 = (AsymmetricCipherKeyPair) new PemReader(reader).ReadObject();
                }

                using (X509AsymmetricEncrypter xasydecMultiple = new X509AsymmetricEncrypter(keyPair.Private))
                {
                    using X509AsymmetricEncrypter xasydecMultiple2 = new X509AsymmetricEncrypter(keyPair2.Private);
                    boDecrypted = xasydecMultiple.Decrypt(eoMultiple);
                    BusinessObject boDecrypted2  = xasydecMultiple2.Decrypt(eoMultiple);
                    string         actualString2 = JsonConvert.SerializeObject(boDecrypted2);
                    Assert.AreEqual(expectedString, actualString2, "Original and encrypted->decrypted object do not match!");
                }
                expectedString = JsonConvert.SerializeObject(bo);
                actualString   = JsonConvert.SerializeObject(boDecrypted);
                Assert.AreEqual(expectedString, actualString, "Original and encrypted->decrypted object do not match!");
            }
        }
Exemple #5
0
        public void ShowCaseTestAsymmetric()
        {
            Assert.IsTrue(maLo.IsValid()); // as the encryption relies on serializing the BO invalid BOs cannot be encrypted.

            var aliceKeyPair = Sodium.PublicKeyBox.GenerateKeyPair();
            var bobKeyPair   = Sodium.PublicKeyBox.GenerateKeyPair();

            Debug.WriteLine($"Bob: Hey @Alice, this is my public key: {Convert.ToBase64String(bobKeyPair.PublicKey).Substring(10)}...");
            // Bob: Hey @Alice, this is my public key: HsGsYigFqgDouUvUW3uMYpy54DqsAxXxQ=...

            EncryptedObject encryptedBo;

            using (AsymmetricEncrypter aliceEncrypter = new AsymmetricEncrypter(aliceKeyPair))
            {
                encryptedBo = aliceEncrypter.Encrypt(maLo, Convert.ToBase64String(bobKeyPair.PublicKey));
            }
            Debug.WriteLine($"Alice: Hey @Bob: This is my signed and encrypted BusinssObject: ");
            Debug.WriteLine(JsonConvert.SerializeObject(encryptedBo, new StringEnumConverter()));
            //{
            //  "boTyp": "ENCRYPTEDOBJECTPUBLICKEYBOX",
            //  "versionStruktur": 1,
            //  "publicKey": "jpo2D3IK9BgPOLyXPfimfSD3u9VErT3kP5IYDMVY0Bo=",
            //  "encryptionScheme": "SodiumAsymmetricPublicKeyBox",
            //  "nonce": "KdNf7rQlQzOyajX+nMKBROce9odVuJqF",
            //  "cipherText": "VIYM7nZU9yTSj2tT...zWUuGbp4HphTlBlzgK"
            //}
            Debug.WriteLine($"Alice: And by the way, I hope you verified my fingerprint or the key itself.");
            Assert.AreEqual(Convert.ToBase64String(aliceKeyPair.PublicKey), ((EncryptedObjectPublicKeyBox)encryptedBo).PublicKey, "Bob: I did, otherwise this would fail");

            Marktlokation decryptedMaLo;

            using (AsymmetricEncrypter bobsDecrypter = new AsymmetricEncrypter(bobKeyPair.PrivateKey))
            {
                BusinessObject decryptedBo = bobsDecrypter.Decrypt(encryptedBo);    // In case Bob had no idea what alice sent him...
                Assert.IsInstanceOfType(decryptedBo, typeof(Marktlokation));        // ...now he knows.
                decryptedMaLo = bobsDecrypter.Decrypt <Marktlokation>(encryptedBo); // Bob knows at compile time it's a MaLo.
            }
            Assert.AreEqual(maLo, decryptedMaLo);

            var eveKeyPair = Sodium.PublicKeyBox.GenerateKeyPair();
            // Eve entered the chat
            EncryptedObjectPublicKeyBox manipulatedBo;

            using (AsymmetricEncrypter eveEncrypter = new AsymmetricEncrypter(eveKeyPair))
            {
                manipulatedBo = eveEncrypter.Encrypt(maLo, Convert.ToBase64String(bobKeyPair.PublicKey));
            }
            manipulatedBo.PublicKey = Convert.ToBase64String(aliceKeyPair.PublicKey); // Eve: Never will Bob know this message is not from Alice!
            Debug.WriteLine("Eve: Hey @Bob, Alice asked me to give you this BO");

            Assert.AreEqual(Convert.ToBase64String(aliceKeyPair.PublicKey), manipulatedBo.PublicKey, "Bob: Hrm, seems like it's from Alice, indeed...");
            using (AsymmetricEncrypter bobsDecrypter = new AsymmetricEncrypter(bobKeyPair.PrivateKey))
            {
                try
                {
                    bobsDecrypter.Decrypt(manipulatedBo);
                }
                catch (System.Security.Cryptography.CryptographicException ce)
                {
                    Debug.WriteLine($"Bob: @Eve: You tried to fool me! {ce.Message}");
                    // As long as Bob checks that the public key stored in the Encrypted Business Object matches the public key of the expected sender he'll be fine.
                }
            }
        }