Esempio n. 1
0
        private static string Hash(string key)
        {
            switch (FileNameStyle)
            {
            case KeyStyle.Hashed:
            {
                var         hash  = XXHash64.Hash(key);
                Span <byte> bytes = stackalloc byte[10];
                Utf8Formatter.TryFormat(hash, bytes, out var bytesWritten);
                // This requires netcoreapp3.1 or net5
                // return MemoryMarshal.AsRef<char>(bytes.Slice(0, bytesWritten)).ToString();
                return(DefaultEncoding.GetString(bytes.Slice(0, bytesWritten).ToArray()));
            }

            case KeyStyle.Base64:
            {
                var bytes = DefaultEncoding.GetBytes(key);
                return(UrlBase64.Encode(bytes));
            }

            case KeyStyle.PlainText:
            {
                if (key.ToCharArray().Any(c => Array.BinarySearch(IllegalCharacters, c) >= 0))
                {
                    throw new IllegalKeyException();
                }
                return(key);
            }
            }

            throw new Exception("Invalid key hashing style set!");
        }
        public static string encrypt(string input)
        {
            byte[] encryptedString = encrypt(System.Text.Encoding.UTF8.GetBytes(input));
            string returnString    = UrlBase64.Encode(encryptedString);

            return(returnString);
        }
        public static string decrypt(string input)
        {
            byte[] decryptedString = decrypt(UrlBase64.Decode(input));
            string returnString    = System.Text.Encoding.UTF8.GetString(decryptedString);

            return(returnString);
        }
Esempio n. 4
0
        public void TestGetVapidHeadersSubjectNotAUrlOrMailTo()
        {
            var publicKey  = UrlBase64.Encode(new byte[65]);
            var privatekey = UrlBase64.Encode(new byte[32]);

            Assert.Throws(typeof(ArgumentException),
                          delegate { VapidHelper.GetVapidHeaders(ValidAudience, @"invalid subject", publicKey, privatekey); });
        }
Esempio n. 5
0
        public void TestGetVapidHeadersAudienceNotAUrl()
        {
            var publicKey  = UrlBase64.Encode(new byte[65]);
            var privatekey = UrlBase64.Encode(new byte[32]);

            Assert.Throws(typeof(ArgumentException),
                          delegate { VapidHelper.GetVapidHeaders(@"invalid audience", ValidSubject, publicKey, privatekey); });
        }
Esempio n. 6
0
 static string HashCode(string challenge_code)
 {
     using (var hash = SHA256.Create())
     {
         byte[] data = Encoding.ASCII.GetBytes(challenge_code);
         return(UrlBase64.Encode(hash.ComputeHash(data)));
     }
 }
Esempio n. 7
0
 public void TestBase64UrlDecode()
 {
     byte[] expected = new byte[3] {
         181, 235, 45
     };
     byte[] actual = UrlBase64.Decode(@"test");
     Assert.IsTrue(actual.SequenceEqual(expected));
 }
Esempio n. 8
0
        public void BasicTest()
        {
            var foo     = Encoding.UTF8.GetBytes("foo");
            var encoded = UrlBase64.Encode(foo);
            var decoded = UrlBase64.Decode(encoded);

            Assert.IsTrue(decoded.SequenceEqual(foo), "Decoded value mismatch!");
        }
Esempio n. 9
0
        public void TestGetVapidHeadersInvalidPublicKey()
        {
            var publicKey  = UrlBase64.Encode(new byte[1]);
            var privateKey = UrlBase64.Encode(new byte[32]);

            Assert.ThrowsException <ArgumentException>(
                delegate { VapidHelper.GetVapidHeaders(ValidAudience, ValidSubject, publicKey, privateKey); });
        }
Esempio n. 10
0
        public static EncryptionResult Encrypt(string userKey, string userSecret, string payload)
        {
            byte[] userKeyBytes    = UrlBase64.Decode(userKey);
            byte[] userSecretBytes = UrlBase64.Decode(userSecret);
            byte[] payloadBytes    = Encoding.UTF8.GetBytes(payload);

            return(Encrypt(userKeyBytes, userSecretBytes, payloadBytes));
        }
Esempio n. 11
0
        public void TestGenerateVapidKeys()
        {
            var keys       = VapidHelper.GenerateVapidKeys();
            var publicKey  = UrlBase64.Decode(keys.PublicKey);
            var privateKey = UrlBase64.Decode(keys.PrivateKey);

            Assert.AreEqual(32, privateKey.Length);
            Assert.AreEqual(65, publicKey.Length);
        }
Esempio n. 12
0
        public void TestGetVapidHeaders()
        {
            var publicKey  = UrlBase64.Encode(new byte[65]);
            var privatekey = UrlBase64.Encode(new byte[32]);
            var headers    = VapidHelper.GetVapidHeaders(ValidAudience, ValidSubject, publicKey, privatekey);

            Assert.True(headers.ContainsKey(@"Authorization"));
            Assert.True(headers.ContainsKey(@"Crypto-Key"));
        }
Esempio n. 13
0
        public void TestGetPublicKey()
        {
            var publicKey       = UrlBase64.Decode(TestPublicKey);
            var publicKeyParams = ECKeyHelper.GetPublicKey(publicKey);

            var importedPublicKey = UrlBase64.Encode(publicKeyParams.Q.GetEncoded(false));

            Assert.Equal(TestPublicKey, importedPublicKey);
        }
Esempio n. 14
0
        public void TestGetPrivateKey()
        {
            byte[] privateKey = UrlBase64.Decode(TEST_PRIVATE_KEY);
            ECPrivateKeyParameters privateKeyParams = ECKeyHelper.GetPrivateKey(privateKey);

            string importedPrivateKey = UrlBase64.Encode(privateKeyParams.D.ToByteArrayUnsigned());

            Assert.AreEqual(TEST_PRIVATE_KEY, importedPrivateKey);
        }
Esempio n. 15
0
        /// <summary>
        ///     Converts a hex-encoded string to a byte array.
        /// </summary>
        /// <param name="b64Src">Base64-encoded data</param>
        /// <param name="urlEncoded"></param>
        public static byte[] Base64ToBinary(this string b64Src, bool urlEncoded)
        {
            if (b64Src == null)
            {
                return(null);
            }

            return(urlEncoded ? UrlBase64.Decode(b64Src) : Base64.Decode(b64Src));
        }
Esempio n. 16
0
        /// <summary>
        /// Gets the data from the given dht name.
        /// </summary>
        /// <param name="nameSpace">The name space.</param>
        /// <param name="name">The name.</param>
        /// <param name="waitHandle">The wait handle.</param>
        /// <param name="downloadPath">The download path.</param>
        /// <returns>Torrent bytes</returns>
        /// <exception cref="DictionaryKeyNotFoundException">Torrent at the given key is
        /// invalid.</exception>
        /// <remarks>MonoTorrent library provides easy conversion from bytes to
        /// Torrent object but not vise versa so we return bytes.</remarks>
        byte[] GetData(string nameSpace, string name, out string downloadPath, bool peek)
        {
            ManualResetEvent waitHandle = new ManualResetEvent(false);

            byte[] torrentDhtKey = ServiceUtil.GetDictKeyBytes(nameSpace, name);
            downloadPath =
                _bittorrentCache.GetPathOfItemInDownloads(nameSpace, name);
            // @TODO Check integrity of the data -- How do we know the download is complete?
            // A possbile solution. Use the name <name.part> and change it to <name> after
            // download completes.
            byte[] torrentBytes;
            if (!CacheRegistry.IsInCacheRegistry(nameSpace, name))
            {
                try {
                    var torrentSavePath = _bittorrentCache.GetTorrentFilePath(nameSpace, name);
                    torrentBytes = _torrentHelper.ReadOrDownloadTorrent(nameSpace,
                                                                        name, _dictProxy);
                    var torrent = Torrent.Load(torrentBytes);
                    if (!peek)
                    {
                        GetDataInternal(torrentDhtKey, torrent, downloadPath,
                                        waitHandle);

                        // Wait until downloading finishes
                        waitHandle.WaitOne();
                        // Download completed.
                        CacheRegistry.AddPathToRegistry(downloadPath, true);
                    }
                    else
                    {
                        // If we are only peeking, we don't add it to the registry.
                    }
                } catch (TorrentException ex) {
                    throw new DictionaryKeyNotFoundException(string.Format(
                                                                 "Torrent at key {0} (UrlBase64) is invalid.",
                                                                 UrlBase64.Encode(torrentDhtKey)), ex);
                }
            }
            else
            {
                torrentBytes = _torrentHelper.ReadOrDownloadTorrent(nameSpace,
                                                                    name, _dictProxy);
                var torrent = Torrent.Load(torrentBytes);
                if (!_clientEngine.Contains(torrent))
                {
                    // This is the case where the manager start seeding data when it boots up.
                    GetDataInternal(torrentDhtKey, torrent, downloadPath, null);
                }
                else
                {
                    // If the data is already there and the client engine is busily downloading or
                    // seeding, we don't need to do it again.
                    return(torrentBytes);
                }
            }
            return(torrentBytes);
        }
Esempio n. 17
0
 static string GenerateCode(int size)
 {
     using (var rng = RandomNumberGenerator.Create())
     {
         byte[] data = new byte[size];
         rng.GetBytes(data);
         return(UrlBase64.Encode(data));
     }
 }
Esempio n. 18
0
        public void TestGetVapidHeaders()
        {
            string publicKey  = UrlBase64.Encode(new byte[65]);
            string privatekey = UrlBase64.Encode(new byte[32]);
            Dictionary <string, string> headers = VapidHelper.GetVapidHeaders(VALID_AUDIENCE, VALID_SUBJECT, publicKey, privatekey);

            Assert.IsTrue(headers.ContainsKey("Authorization"));
            Assert.IsTrue(headers.ContainsKey("Crypto-Key"));
        }
Esempio n. 19
0
        public void TestBase64UrlEncode()
        {
            var expected = @"test";
            var actual   = UrlBase64.Encode(new byte[3] {
                181, 235, 45
            });

            Assert.Equal(expected, actual);
        }
 public static string GenerateAuthToken()
 {
     using (var rng = new RNGCryptoServiceProvider())
     {
         var bytes = new byte[256];
         rng.GetBytes(bytes);
         return(UrlBase64.Encode(bytes));
     }
 }
Esempio n. 21
0
        public void TestGetPrivateKey()
        {
            var privateKey       = UrlBase64.Decode(TestPrivateKey);
            var privateKeyParams = ECKeyHelper.GetPrivateKey(privateKey);

            var importedPrivateKey = UrlBase64.Encode(privateKeyParams.D.ToByteArrayUnsigned());

            Assert.Equal(TestPrivateKey, importedPrivateKey);
        }
Esempio n. 22
0
        public void TestBase64UrlEncode()
        {
            string expected = @"test";
            string actual   = UrlBase64.Encode(new byte[3] {
                181, 235, 45
            });

            Assert.AreEqual(expected, actual);
        }
Esempio n. 23
0
        public void TestGetPublicKey()
        {
            byte[] publicKey = UrlBase64.Decode(TEST_PUBLIC_KEY);
            ECPublicKeyParameters publicKeyParams = ECKeyHelper.GetPublicKey(publicKey);

            string importedPublicKey = UrlBase64.Encode(publicKeyParams.Q.GetEncoded(false));

            Assert.AreEqual(TEST_PUBLIC_KEY, importedPublicKey);
        }
        public void EncodingFromBase64UrlToBase64()
        {
            // 4.1 Aufbereitung des maschinenlesbaren Codes (Basis-Code), Seite 47
            string base64UrlEncoded = "J7YC28zquHfHzMpx02TqElbXOTSgXQu5JAA9Xu1Xzzu5p8eUYT-sgmyhzRps5nYyEp5Yh8ATIa9130zmuiACHw";
            var    decoded          = UrlBase64.Decode(base64UrlEncoded);
            string base64Encoded    = Convert.ToBase64String(decoded);

            Assert.Equal("J7YC28zquHfHzMpx02TqElbXOTSgXQu5JAA9Xu1Xzzu5p8eUYT+sgmyhzRps5nYyEp5Yh8ATIa9130zmuiACHw==",
                         base64Encoded);
        }
Esempio n. 25
0
        public void TestGenerateVapidKeys()
        {
            VapidDetails keys = VapidHelper.GenerateVapidKeys();

            byte[] publicKey  = UrlBase64.Decode(keys.PublicKey);
            byte[] privateKey = UrlBase64.Decode(keys.PrivateKey);

            Assert.AreEqual(32, privateKey.Length);
            Assert.AreEqual(65, publicKey.Length);
        }
Esempio n. 26
0
        public static string CreateToken(string token, string dsId)
        {
            if (string.IsNullOrEmpty(token))
            {
                throw new ArgumentException("Invalid token");
            }
            string tokenHash = dsId + token;

            tokenHash = UrlBase64.Encode(_sha256.ComputeHash(Encoding.UTF8.GetBytes(tokenHash)));
            return(token.Substring(0, 16) + tokenHash);
        }
Esempio n. 27
0
        public void TestGetVapidHeadersInvalidPublicKey()
        {
            string publicKey  = UrlBase64.Encode(new byte[1]);
            string privatekey = UrlBase64.Encode(new byte[32]);

            Assert.Throws(typeof(ArgumentException),
                          delegate
            {
                VapidHelper.GetVapidHeaders(VALID_AUDIENCE, VALID_SUBJECT, publicKey, privatekey);
            });
        }
Esempio n. 28
0
        public void TestGetVapidHeadersSubjectNotAUrlOrMailTo()
        {
            string publicKey  = UrlBase64.Encode(new byte[65]);
            string privatekey = UrlBase64.Encode(new byte[32]);

            Assert.Throws(typeof(ArgumentException),
                          delegate
            {
                VapidHelper.GetVapidHeaders(VALID_AUDIENCE, "invalid subject", publicKey, privatekey);
            });
        }
Esempio n. 29
0
        public void TestGetVapidHeadersAudienceNotAUrl()
        {
            string publicKey  = UrlBase64.Encode(new byte[65]);
            string privatekey = UrlBase64.Encode(new byte[32]);

            Assert.Throws(typeof(ArgumentException),
                          delegate
            {
                VapidHelper.GetVapidHeaders("invalid audience", VALID_SUBJECT, publicKey, privatekey);
            });
        }
Esempio n. 30
0
        public void TestEncode(string testData)
        {
            var data = UrlBase64.Encode(Encoding.UTF8.GetBytes(testData));

            Assert.DoesNotContain("/", data);
            Assert.DoesNotContain("=", data);
            Assert.DoesNotContain("+", data);

            var result = Encoding.UTF8.GetString(UrlBase64.Decode(data));

            Assert.Equal(testData, result);
        }