Exemple #1
0
        private byte[] Pkcs1pad(byte[] src, int n, Pkcs1PadType type)
        {
            var bytes = new byte[n];

            var i = src.Length - 1;

            while (i >= 0 && n > 11)
            {
                bytes[--n] = src[i--];
            }

            bytes[--n] = 0;
            while (n > 2)
            {
                byte x = 0;
                switch (type)
                {
                case Pkcs1PadType.FullByte: x = 0xFF; break;

                case Pkcs1PadType.RandomByte: x = EncryptionUtilities.NextByte(1, 255); break;
                }
                bytes[--n] = x;
            }

            bytes[--n] = (byte)type;
            bytes[--n] = 0;
            return(bytes);
        }
Exemple #2
0
 public async Task <bool> PermissionValidator(ActionExecutingContext context)
 {
     if (context.HttpContext.User.Claims.FirstOrDefault() != null)
     {
         string oId = context.HttpContext.User.Claims.FirstOrDefault(c => c.Type == azureOptions.UserClaimsUrl).Value;
         if (!(string.IsNullOrEmpty(oId)))
         {
             oId = EncryptionUtilities.GenerateSHA512String(oId);
             string requestPath = context.HttpContext.Request.Path.ToString();
             if (requestPath.Contains("get-user-profile"))
             {
                 if (context.ActionArguments.Count > 0)
                 {
                     Dictionary <string, object> parameters = new Dictionary <string, object>();
                     foreach (var param in context.ActionArguments)
                     {
                         parameters.Add(param.Key, param.Value);
                         if (param.Value.ToString() == oId)
                         {
                             return(await CheckPermissions(oId));
                         }
                     }
                 }
                 return(false);
             }
             return(await CheckPermissions(oId));
         }
     }
     return(false);
 }
Exemple #3
0
        private void Initialize(bool ignoreBaseKeys = false)
        {
            PublicKey = 0;

            var rand = new Random();

            while (PublicKey == 0)
            {
                if (!ignoreBaseKeys)
                {
                    Prime     = BigInteger.genPseudoPrime(BITLENGTH, 10, rand);
                    Generator = BigInteger.genPseudoPrime(BITLENGTH, 10, rand);
                }

                var bytes = new byte[BITLENGTH / 8];
                EncryptionUtilities.NextBytes(bytes);
                PrivateKey = new BigInteger(bytes);

                if (Generator > Prime)
                {
                    var temp = Prime;
                    Prime     = Generator;
                    Generator = temp;
                }

                PublicKey = Generator.modPow(PrivateKey, Prime);

                if (!ignoreBaseKeys)
                {
                    break;
                }
            }
        }
        private string GetOId()
        {
            string oId = string.Empty;

            if (httpContextAccessor.HttpContext.User.Claims.FirstOrDefault() != null)
            {
                oId = httpContextAccessor.HttpContext.User.Claims.FirstOrDefault(c => c.Type == azureOptions.UserClaimsUrl).Value;
                oId = EncryptionUtilities.GenerateSHA512String(oId);
            }
            return(oId);
        }
        private static string GetRsaStringEncrypted(string message)
        {
            try
            {
                var m = Encoding.Default.GetBytes(message);
                var c = Rsa.Sign(m);

                return(EncryptionUtilities.BytesToHexString(c));
            }
            catch
            {
                return("0");
            }
        }
 public static BigInteger CalculateDiffieHellmanSharedKey(string publicKey)
 {
     try
     {
         var cbytes          = EncryptionUtilities.HexStringToBytes(publicKey);
         var publicKeyBytes  = Rsa.Verify(cbytes);
         var publicKeyString = Encoding.Default.GetString(publicKeyBytes);
         return(DiffieHellman.CalculateSharedKey(new BigInteger(publicKeyString, 10)));
     }
     catch
     {
         return(0);
     }
 }
Exemple #7
0
        public int PopInt()
        {
            if (RemainingLength < 1)
            {
                return(0);
            }

            var data = PlainReadBytes(4);

            var i = EncryptionUtilities.DecodeInt32(data);

            _pointer += 4;

            return(i);
        }
Exemple #8
0
        private static byte[] GenerateSecretValue(string secretValue, bool generatePassword,
                                                  bool generateSymmetricKey, int passwordLength)
        {
            if (generatePassword)
            {
                try
                {
                    return(PasswordUtilities.GenerateSecuredPassword(passwordLength));
                }
                catch (Exception e)
                {
                    Console.WriteLine($"Cannot generate password - {e.Message}");
                    return(null);
                }
            }

            if (generateSymmetricKey)
            {
                try
                {
                    return(EncryptionUtilities.GenerateEncodedSymmetricKey());
                }
                catch (Exception e)
                {
                    Console.WriteLine($"Cannot generate symmetric key - {e.Message}");
                    return(null);
                }
            }

            if (!File.Exists(secretValue))
            {
                Console.WriteLine("Argument \"--secret-value\" must refer to a valid filepath");
            }
            else
            {
                byte[] secretValueInBytes = File.ReadAllBytes(secretValue);
                if (secretValueInBytes != null && secretValueInBytes.Length != 0)
                {
                    return(secretValueInBytes);
                }
                Console.WriteLine("Argument \"--secret-value\" has file without content");
            }
            return(null);
        }
Exemple #9
0
        public void EnableEncryption(string protector, object parms = null)
        {
            if (Key != null)
            {
                // If the key's protector is the same, no reason to change it
                //if (protectedKey.ProtectorType == protectorType)
                //   return;

                // Set the new protector on the key
                Key.PrimaryProtector = new CryptoKeyProtector(protector, Key.PrimaryProtector.GetKey(), parms);
            }
            else
            {
                // Create a new encryption key with 4096 bits and the specified provider
                Key = new CryptoKey(new CryptoKeyProtector(protector, EncryptionUtilities.GenerateRandomBytes(), parms));
            }

            Encrypted = true;
        }
        public async Task <UserProfileViewModel> UpsertUserProfileAsync(UserProfile userProfile)
        {
            if (userProfile == null || string.IsNullOrEmpty(userProfile?.OId))
            {
                throw new Exception("Please login into Application");
            }

            userProfile.OId = EncryptionUtilities.GenerateSHA512String(userProfile?.OId);
            UserProfileViewModel resultUP = await GetUserProfileDataAsync(userProfile?.OId, true);

            if (string.IsNullOrEmpty(resultUP?.OId))
            {
                userProfile.RoleInformationId.Add(await GetDefaultUserRole());
                List <dynamic> profile = new List <dynamic>();
                var            result  = await dbService.CreateItemAsync(userProfile, dbSettings.ProfilesCollectionId);

                profile.Add(result);
                resultUP = ConvertUserProfileViewModel(profile);
                resultUP.RoleInformation.Add(new RoleViewModel {
                    RoleName = Permissions.Role.Authenticated.ToString(), OrganizationalUnit = string.Empty
                });
            }
            else
            {
                List <Role> userRoles = await GetRoleDetailsAsync(resultUP.RoleInformationId);

                if (userRoles?.Count() > 0)
                {
                    List <RoleViewModel> roleViewModels = new List <RoleViewModel>();
                    foreach (var userRole in userRoles)
                    {
                        roleViewModels.Add(new RoleViewModel {
                            RoleName = userRole.RoleName, OrganizationalUnit = userRole.OrganizationalUnit
                        });
                    }
                    resultUP.RoleInformation = roleViewModels;
                }
            }
            resultUP.RoleInformationId = null;
            return(resultUP);
        }
Exemple #11
0
        public async Task <string> Compare(byte[] imageBytes)
        {
            try
            {
                String collectionId = "PiscoMarketFaces";

                //Decrypt Keys
                var key = "E546C8DF278CD5931069B522E695D4F2";

                var rekognitionClient = new AmazonRekognitionClient(EncryptionUtilities.DecryptString(configuration.awsAccessKey, key), EncryptionUtilities.DecryptString(configuration.awsAccessSecret, key), Amazon.RegionEndpoint.USEast2);

                var image = new Image()
                {
                    Bytes = new MemoryStream(imageBytes)
                };

                var searchFacesByImageRequest = new SearchFacesByImageRequest()
                {
                    CollectionId       = collectionId,
                    Image              = image,
                    FaceMatchThreshold = 70F,
                    MaxFaces           = 1
                };

                SearchFacesByImageResponse searchFacesByImageResponse =
                    await rekognitionClient.SearchFacesByImageAsync(searchFacesByImageRequest);

                if (searchFacesByImageResponse.FaceMatches.Any())
                {
                    var faceMatch = searchFacesByImageResponse.FaceMatches.First();
                    return(faceMatch.Face.ExternalImageId);
                }

                return(null);
            }
            catch (Exception ex)
            {
                return(null);
            }
        }
Exemple #12
0
        public async Task <Secret> PutSecretAsync(string secretName, byte[] secretValue, Dictionary <string, string> p2)
        {
            var objectKey = GetObjectKey(secretName);

            var ikek = EncryptionUtilities.GenerateSecretKey();

            var s3Client = GetS3EncryptionClient(new EncryptionMaterials(ikek), new AmazonS3CryptoConfiguration {
                RegionEndpoint = AwsRegion
            });

            logger.Info("check if s3 bucket versioning enabled");
            var versioned = await s3Client.GetBucketVersioningAsync(new GetBucketVersioningRequest { BucketName = BucketName });

            if (string.Compare("enabled", versioned.VersioningConfig.Status, true) != 0)
            {
                throw new SecretsSdkException($"s3 Bucket versioning is not enabled, {BucketName}");
            }

            var ikekVersionId = await UploadIkek(GetIkekObjectKey(secretName), ikek.GetEncoded());

            logger.Info($"encrypt and upload secret to {secretName}");

            var putRequest = new PutObjectRequest()
            {
                BucketName  = BucketName,
                Key         = objectKey,
                InputStream = new MemoryStream(secretValue)
            };

            putRequest.Metadata.Add(IKEK_METADATA_KEY, ikekVersionId);

            var result = await s3Client.PutObjectAsync(putRequest);

            logger.Info($"uploaded secret to {secretName}");
            return(new Secret(secretName)
            {
                Version = result.VersionId
            });
        }
Exemple #13
0
        /// <summary>
        /// Encrypts the body from the <see cref="PlainTextBody"/> property.
        /// This only needs to be called if the body is being saved back.
        /// </summary>
        public void EncryptBodyBytes()
        {
            // No encryption, nothing to do
            if (!Header.Encrypted || Store.Key == null)
            {
                Body = PlainTextBody;
                return;
            }

            // If no crypto key or master key has changed, create a new one
            if (Header.Key == null)
            {
                Header.Key = new CryptoKey(new CryptoKeyProtector("AES", EncryptionUtilities.GenerateRandomBytes(), Store.Key));
            }

            // Initialise the document's key.
            var keyInit = (IInitiableProvider)Header.Key.PrimaryProtector.Provider;

            keyInit.Initialise(Store.Key);

            // Encrypt the document with its key
            Body = new AesCryptoProvider(Header.Key).Encrypt(PlainTextBody);
        }
Exemple #14
0
        public async Task <QueryResult <UserModel> > Login(LoginModel input)
        {
            try
            {
                var result = await DbConnection.QueryFirstAsync <SecretDataModel>(GetUserData, new { input.UserName });

                var isPasswordValid = EncryptionUtilities.IsPasswordValid(input.Password, $"{result.PasswordSalt.Trim()}:{result.PasswordHash.Trim()}");

                if (isPasswordValid)
                {
                    return(new QueryResult <UserModel>
                    {
                        IsSuccessfult = true,
                        Result = new UserModel
                        {
                            UserName = result.UserName,
                            Email = result.Email,
                            Id = result.Id
                        }
                    });
                }

                return(new QueryResult <UserModel>
                {
                    IsSuccessfult = false,
                    ErrorMessage = "User is not exist or incorrect password"
                });
            }
            catch (Exception ex)
            {
                return(new QueryResult <UserModel>
                {
                    IsSuccessfult = false,
                    ErrorMessage = $"An internal error has been occured. Error message: {ex.Message}"
                });
            }
        }
Exemple #15
0
        public async Task <QueryResult> Register(RegistrationModel input)
        {
            try
            {
                using (DbConnection)
                {
                    DbConnection.Open();

                    var hashSalt = EncryptionUtilities.CreatePasswordSalt(input.Password).Split(':');
                    var salt     = hashSalt[0];
                    var hash     = hashSalt[1];

                    var result = await DbConnection.ExecuteAsync(RegisterQuery, new
                    {
                        UserName     = input.UserName,
                        Email        = input.Email,
                        PasswordHash = hash,
                        PasswordSalt = salt
                    });

                    return(new QueryResult
                    {
                        RowAffected = result,
                        IsSuccessfult = result > 0
                    });
                }
            }
            catch (Exception ex)
            {
                return(new QueryResult
                {
                    IsSuccessfult = false,
                    ErrorMessage = $"An error has been occured. Error message: {ex.Message}"
                });
            }
        }
        public async Task <ShareViewModel> ShareResourceDataAsync(ShareInput shareInput)
        {
            dynamic response = null;

            if (shareInput.Url == null || shareInput.UserId == null || shareInput.ResourceId == null)
            {
                return(null);
            }
            UserProfile userProfile = await dbUserProfile.GetUserProfileDataAsync(shareInput.UserId);

            shareInput.UniqueId   = shareInput.UniqueId != Guid.Empty ? shareInput.UniqueId : Guid.NewGuid();
            shareInput.ResourceId = shareInput.ResourceId != Guid.Empty ? shareInput.ResourceId : Guid.NewGuid();

            var permaLink = EncryptionUtilities.GenerateSHA256String(shareInput.UniqueId + shareInput.UserId +
                                                                     shareInput.ResourceId);
            var sharedResource = new SharedResource
            {
                ExpirationDate = DateTime.UtcNow.AddYears(Constants.ExpirationDateDurationInYears),
                IsShared       = true,
                Url            = new Uri(shareInput.Url.OriginalString, UriKind.RelativeOrAbsolute),
                PermaLink      = permaLink
            };

            response = await UpsertSharedResource(userProfile, sharedResource);

            if (shareInput.Url.OriginalString.Contains("plan"))
            {
                string planId = shareInput.Url.OriginalString.Substring(6);
                await UpdatePlanIsSharedStatus(planId, true);
            }

            return(response == null ? null : new ShareViewModel
            {
                PermaLink = dbShareSettings.PermaLinkMaxLength > 0 ? GetPermaLink(permaLink) : permaLink
            });
        }
Exemple #17
0
        public byte[] ReadFixedValue()
        {
            var len = EncryptionUtilities.DecodeInt16(ReadBytes(2));

            return(ReadBytes(len));
        }
        public void HandlePacketData(byte[] data)
        {
            try
            {
                if (_client.Rc4Client != null && !_deciphered)
                {
                    _client.Rc4Client.Decrypt(ref data);
                    _deciphered = true;
                }

                if (_halfDataRecieved)
                {
                    var fullDataRcv = new byte[_halfData.Length + data.Length];
                    Buffer.BlockCopy(_halfData, 0, fullDataRcv, 0, _halfData.Length);
                    Buffer.BlockCopy(data, 0, fullDataRcv, _halfData.Length, data.Length);

                    _halfDataRecieved = false;     // mark done this round
                    HandlePacketData(fullDataRcv); // repeat now we have the combined array
                    return;
                }

                using (var reader = new BinaryReader(new MemoryStream(data)))
                {
                    if (data.Length < 4)
                    {
                        return;
                    }

                    var msgLen = EncryptionUtilities.DecodeInt32(reader.ReadBytes(4));
                    if (reader.BaseStream.Length - 4 < msgLen)
                    {
                        _halfData         = data;
                        _halfDataRecieved = true;
                        return;
                    }

                    if (msgLen < 0 || msgLen > 5120)//TODO: Const somewhere.
                    {
                        return;
                    }

                    var packet = reader.ReadBytes(msgLen);

                    using (var r = new BinaryReader(new MemoryStream(packet)))
                    {
                        var header = EncryptionUtilities.DecodeInt16(r.ReadBytes(2));

                        var content = new byte[packet.Length - 2];
                        Buffer.BlockCopy(packet, 2, content, 0, packet.Length - 2);

                        var message = new ClientPacket(header, content);
                        OnNewPacket.Invoke(message);

                        _deciphered = false;
                    }

                    if (reader.BaseStream.Length - 4 > msgLen)
                    {
                        var extra = new byte[reader.BaseStream.Length - reader.BaseStream.Position];
                        Buffer.BlockCopy(data, (int)reader.BaseStream.Position, extra, 0, (int)(reader.BaseStream.Length - reader.BaseStream.Position));

                        _deciphered = true;
                        HandlePacketData(extra);
                    }
                }
            }
#pragma warning disable CS0168 // The variable 'e' is declared but never used
            catch (Exception e)
#pragma warning restore CS0168 // The variable 'e' is declared but never used
            {
                //Logger.Error("Packet Error!", e);
            }
        }