C# encrypts the middle part of the certificate number and changes it to * number

foreword

Usage scenario: In my project, I need to provide an interface for the front end, so I need to encrypt the ID number. For example: 411421199510225612, this is an ID number, 18, then after my encryption is completed, it will be
411421********5612, and a message like this is sent to the front end. Of course, if this is the case, I can use a regularization to complete it, but the problem is that the length of the encrypted ID number is uncertain. It may be an ID number (18 digits), or a driver's license number (12 digits). digits), it may also be a mobile phone number (11 digits), and so on. It is possible, so how can we achieve the encryption effect.

1. Problem solving ideas

Take the ID card as an example:
string card="411421199510225612"
int length = card.length;
int start = length / 4
int end = length *3 / 4
The above ID card is 18 digits, and then start is equal to 4.5, because it is int type, so 4.5 is rounded down to 4.
end is equal to 13.5, because it is an int type, so 13.5 is rounded down to 13.
So now we have obtained two subscript indexes: 4 and 13, so we can use substring to change the numbers between 4 and 13 into ※ numbers.
In the same way, it can be done even if it is 12 or 11 digits, as long as it is not less than four digits.

2. Use steps

The following is a public method I wrote according to my project requirements, which can be changed according to my own needs.

   /// <summary>
        /// 加密字符串
        /// 加密规则:字符长度/4 到 字符长度*3/4 进行加密
        /// </summary>
        /// <returns></returns>
        public static string EncryptionNum(string nums)
        {
    
    
            if (nums.Length > 4)
            {
    
    
                string hideNum = nums.Substring(nums.Length / 4, (nums.Length * 3 / 4) - (nums.Length / 4) + 1);
                string Asterisk = "";
                for (int i = 0; i < hideNum.Length; i++)
                {
    
    
                    Asterisk += "*";
                }
                nums = nums.Substring(0, nums.Length / 4) + Asterisk + nums.Substring((nums.Length * 3 / 4) + 1, nums.Length - (nums.Length * 3 / 4) - 1);
                return nums;
            }
            else
            {
    
    
                return nums;
            }
        }

Summarize

The above method is to pass in a certificate number, and it will judge whether it is greater than four digits, and if it is less than four digits, it will be returned as it is, and if it is greater than four digits, it will be encrypted into asterisks using the method mentioned above and returned.

Guess you like

Origin blog.csdn.net/qq_37213281/article/details/124126010