﻿using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;
using UnityEngine;

namespace RsaEncrypt
{
    #region RsaHelper
    public class RsaHelper
    {
        private readonly RSA _privateKeyRsaProvider;
        private readonly RSA _publicKeyRsaProvider;
        private readonly HashAlgorithmName _hashAlgorithmName;
        private readonly Encoding _encoding;

        // 私钥生成方式：openssl genrsa -out private.key 2048
        private const string defaultprivateKey = @"MIIEpAIBAAKCAQEA5uSHRBXy0koOpNbUC4zR/ZA6GDhyHyYBoiDnYIOjcOdRRXMD
Eb8Kd61mMj2dU5ptCv3JEL1GneCDLSslF7sSl+nGlmXPkfPSpwrGb+ZWxWzwn/7j
cc5dKt8LIvuHqNPVH+4PDFgZ4akmE4itv2vaF2n9PhheQIsP+FH/ev5/EsEWWXJx
kQUI8BFSU42rWSUKt+p5Yi8cu1IjjMfIMqKWfJ34d6yEI7qmeIybbIEcQdY1/koE
CPvhvUeFgm4PQRIVOpLRfpqbpuJSpK+E3BV2n2F755JFY/VZG6HutndYUfurn/Qt
ykIyp1XD6nIBZYXXT8PYBhDbC6sCuq5fw8s1wQIDAQABAoIBAGpR3T+q46+Vznx1
OBtBcwjRuw6gH1zcgXAIusKkm0RIIBJczZMEZ2uIe0CzQpjWyVOAXW/J2JSmZ4EL
Fv+AcyVkzr8+joBkyCGHQq0QYfBzI7JpCo7DOf+dyWEIdgV11fPoCSHkB7bzzsa7
71Xv8fNKKQTI783Eu0vbZktamWUmiI/dt+755teeHnW3NbvJ8dHjlBW+kNYtz3Nt
j43r2sAbk4Eo+3qX9NEgirkEwvwyQpl5PpgGwbOHp9McGTURe2w7328GVZ11U4wp
cpgp/Fu/kw+4RZ81SkMYGiqeaircsgAjCzAob+6IDRQZBFAI7O0R9wZJnuk19djc
lQOMyWECgYEA+JziBHyfPC7dpwlrlj6e6jeBH/nD8LHiGUqggRxo0rzrIcZQn4QM
gO6q78ZzgvlElNgZFSlpHB0gOGkc7yAFSjU441w41bzuKbFOEYn/GDzs49x8KX6R
3OQmlNXmKuXzD+1NnUMWy3WfN+pQ7bO7csaEFcnJb0GHId689y9WhxUCgYEA7cDa
q8e2dS4mOzsE7CxS8aA+rhLwOz/B3sfwUQQtx+w7SFMo2pm2iGhCpkHW3c0QEgJg
krQG8MSIubVwTmtfRw/O7jp+GdRZGWFYiXKW3WCbUgfVpMyTmvSzWFxyqney7C1x
E5SGZBkhJcdx6pxizp/kH+K6Gd7mLlX+Jqp2Xv0CgYBadoOLjGlItejzier7Dag3
o6C5qOGSaLfT6iLDODowTIvmi0n08VC3baEHhJetldRNsOBXoezcTQDXZfAgVu91
1C3yFTGdHJUw2JKGsUcAY9LzCtynIKYk0WP0jmylOW0bY4b1bV8TA6a+6uUtyVOw
7OlNIFLKx/ZK7cimzTPYDQKBgQC1Y31xsVyy6hKg/dYzmV1umyM3C5vcmDgBD+l4
5gdHkCNqeoegv8VTLLgsv+5+KgUouEeVpWPmLQtjI9oa+jAmtxjZCCdM7YVMp8g0
lQgkvZ/CZdfJc4rpned2cpHJHKmVJtYuahJeLA3uFMwEgmuf2Lzi1sfFFRnoIBNW
zJaiwQKBgQDOnG0mXl0pNOqTJc76eXORzYwiqaZHESqt4+apepsNtD+shtP0dxQU
RX5++ilcmZTwDyKvJSPPI1Fi6fWGOBjm7GQLvMuF/Ex+tXHJUP7nPUETokqtdGEz
AI8wYmpxTm5t5W9VqKXi4OH2GzcQ3DLe95vH5lD9GKFDnP15mAoiZA==";

        // 公钥生成方式：openssl rsa -in private.key -pubout -out public.key
        private const string defaultpublicKey = @"MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA5uSHRBXy0koOpNbUC4zR
/ZA6GDhyHyYBoiDnYIOjcOdRRXMDEb8Kd61mMj2dU5ptCv3JEL1GneCDLSslF7sS
l+nGlmXPkfPSpwrGb+ZWxWzwn/7jcc5dKt8LIvuHqNPVH+4PDFgZ4akmE4itv2va
F2n9PhheQIsP+FH/ev5/EsEWWXJxkQUI8BFSU42rWSUKt+p5Yi8cu1IjjMfIMqKW
fJ34d6yEI7qmeIybbIEcQdY1/koECPvhvUeFgm4PQRIVOpLRfpqbpuJSpK+E3BV2
n2F755JFY/VZG6HutndYUfurn/QtykIyp1XD6nIBZYXXT8PYBhDbC6sCuq5fw8s1
wQIDAQAB";

        /// <summary>
        /// 实例化RSAHelper 调用方式 RSAHelper RSA = new RSAHelper(RSAType.RSA, Encoding.UTF8);
        /// </summary>
        /// <param name="rsaType">加密算法类型 RSA SHA1;RSA2 SHA256 密钥长度至少为2048</param>
        /// <param name="encoding">编码类型</param>
        /// <param name="privateKey">私钥</param>
        /// <param name="publicKey">公钥</param>
        public RsaHelper(RsaType rsaType, Encoding encoding, string privateKey = "", string publicKey = "")
        {
            if (string.IsNullOrEmpty(privateKey))
            {
                privateKey = defaultprivateKey;
            }
            if (string.IsNullOrEmpty(publicKey))
            {
                publicKey = defaultpublicKey;
            }

            _encoding = encoding;
            if (!string.IsNullOrEmpty(privateKey))
            {
                _privateKeyRsaProvider = CreateRsaProviderFromPrivateKey(privateKey);
            }

            if (!string.IsNullOrEmpty(publicKey))
            {
                _publicKeyRsaProvider = CreateRsaProviderFromPublicKey(publicKey);
            }

            _hashAlgorithmName = rsaType == RsaType.RSA ? HashAlgorithmName.SHA1 : HashAlgorithmName.SHA256;
        }

        #region 使用私钥签名

        /// <summary>
        /// 使用私钥签名
        /// </summary>
        /// <param name="data">原始数据</param>
        /// <returns></returns>
        public string Sign(string data)
        {
            byte[] dataBytes = _encoding.GetBytes(data);

            var signatureBytes = _privateKeyRsaProvider.SignData(dataBytes, _hashAlgorithmName, RSASignaturePadding.Pkcs1);

            return Convert.ToBase64String(signatureBytes);
        }

        #endregion

        #region 使用公钥验证签名

        /// <summary>
        /// 使用公钥验证签名
        /// </summary>
        /// <param name="data">原始数据</param>
        /// <param name="sign">签名</param>
        /// <returns></returns>
        public bool Verify(string data, string sign)
        {
            byte[] dataBytes = _encoding.GetBytes(data);
            byte[] signBytes = Convert.FromBase64String(sign);

            var verify = _publicKeyRsaProvider.VerifyData(dataBytes, signBytes, _hashAlgorithmName, RSASignaturePadding.Pkcs1);

            return verify;
        }

        #endregion

        #region 解密

        public string Decrypt(string cipherText)
        {
            if (_privateKeyRsaProvider == null)
            {
                Debug.Log("NULL");
                return null;
            }

            return Encoding.UTF8.GetString(_privateKeyRsaProvider.Decrypt(Convert.FromBase64String(cipherText), RSAEncryptionPadding.Pkcs1));
        }

        #endregion

        #region 加密

        public string Encrypt(string text)
        {
            if (_publicKeyRsaProvider == null)
            {
                return null;
            }
            var t1 = Encoding.UTF8.GetBytes(text);
            // 此处加密已经写死，不能再换成其他安全加密方式等
#pragma warning disable S5542 // Encryption algorithms should be used with secure mode and padding scheme
            var tmp = _publicKeyRsaProvider.Encrypt(t1, RSAEncryptionPadding.Pkcs1);
#pragma warning restore S5542 // Encryption algorithms should be used with secure mode and padding scheme
            return Convert.ToBase64String(tmp);
        }

        #endregion

        #region 使用私钥创建RSA实例

        public RSA CreateRsaProviderFromPrivateKey(string privateKey)
        {
            var privateKeyBits = Convert.FromBase64String(privateKey);

            var rsa = RSA.Create();
            var rsaParameters = new RSAParameters();

            using (BinaryReader binr = new BinaryReader(new MemoryStream(privateKeyBits)))
            {
                byte bt = 0;
                ushort twobytes = 0;
                twobytes = binr.ReadUInt16();
                if (twobytes == 0x8130)
                    binr.ReadByte();
                else if (twobytes == 0x8230)
                    binr.ReadInt16();
                else
                    throw new InvalidCastException("Unexpected value read binr.ReadUInt16()");

                twobytes = binr.ReadUInt16();
                if (twobytes != 0x0102)
                    throw new InvalidCastException("Unexpected version");

                bt = binr.ReadByte();
                if (bt != 0x00)
                    throw new InvalidCastException("Unexpected value read binr.ReadByte()");

                rsaParameters.Modulus = binr.ReadBytes(GetIntegerSize(binr));
                rsaParameters.Exponent = binr.ReadBytes(GetIntegerSize(binr));
                rsaParameters.D = binr.ReadBytes(GetIntegerSize(binr));
                rsaParameters.P = binr.ReadBytes(GetIntegerSize(binr));
                rsaParameters.Q = binr.ReadBytes(GetIntegerSize(binr));
                rsaParameters.DP = binr.ReadBytes(GetIntegerSize(binr));
                rsaParameters.DQ = binr.ReadBytes(GetIntegerSize(binr));
                rsaParameters.InverseQ = binr.ReadBytes(GetIntegerSize(binr));
            }

            rsa.ImportParameters(rsaParameters);
            return rsa;
        }

        #endregion

        #region 使用公钥创建RSA实例

        public RSA CreateRsaProviderFromPublicKey(string publicKeyString)
        {
            // encoded OID sequence for  PKCS #1 rsaEncryption szOID_RSA_RSA = "1.2.840.113549.1.1.1"
            byte[] seqOid = { 0x30, 0x0D, 0x06, 0x09, 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x01, 0x01, 0x05, 0x00 };
            byte[] seq;

            var x509Key = Convert.FromBase64String(publicKeyString);

            // ---------  Set up stream to read the asn.1 encoded SubjectPublicKeyInfo blob  ------
            using (MemoryStream mem = new MemoryStream(x509Key))
            {
                using (BinaryReader binr = new BinaryReader(mem))  //wrap Memory Stream with BinaryReader for easy reading
                {
                    byte bt = 0;
                    ushort twobytes = 0;

                    twobytes = binr.ReadUInt16();
                    switch (twobytes)
                    {
                        case 0x8130:
                            binr.ReadByte();break;
                        case 0x8230:
                            binr.ReadInt16();break;
                        default: return null;
                    }

                    seq = binr.ReadBytes(15);       //read the Sequence OID
                    if (!CompareBytearrays(seq, seqOid))    //make sure Sequence for OID is correct
                        return null;

                    twobytes = binr.ReadUInt16();
                    if (twobytes == 0x8103) //data read as little endian order (actual data order for Bit String is 03 81)
                        binr.ReadByte();    //advance 1 byte
                    else if (twobytes == 0x8203)
                        binr.ReadInt16();   //advance 2 bytes
                    else
                        return null;

                    bt = binr.ReadByte();
                    if (bt != 0x00)     //expect null byte next
                        return null;

                    twobytes = binr.ReadUInt16();
                    if (twobytes == 0x8130) //data read as little endian order (actual data order for Sequence is 30 81)
                        binr.ReadByte();    //advance 1 byte
                    else if (twobytes == 0x8230)
                        binr.ReadInt16();   //advance 2 bytes
                    else
                        return null;

                    twobytes = binr.ReadUInt16();
                    byte lowbyte = 0x00;
                    byte highbyte = 0x00;

                    if (twobytes == 0x8102) //data read as little endian order (actual data order for Integer is 02 81)
                        lowbyte = binr.ReadByte();  // read next bytes which is bytes in modulus
                    else if (twobytes == 0x8202)
                    {
                        highbyte = binr.ReadByte(); //advance 2 bytes
                        lowbyte = binr.ReadByte();
                    }
                    else
                        return null;
                    byte[] modint = { lowbyte, highbyte, 0x00, 0x00 };   //reverse byte order since asn.1 key uses big endian order
                    int modsize = BitConverter.ToInt32(modint, 0);

                    int firstbyte = binr.PeekChar();
                    if (firstbyte == 0x00)
                    {   //if first byte (highest order) of modulus is zero, don't include it
                        binr.ReadByte();    //skip this null byte
                        modsize -= 1;   //reduce modulus buffer size by 1
                    }

                    byte[] modulus = binr.ReadBytes(modsize);   //read the modulus bytes

                    if (binr.ReadByte() != 0x02)            //expect an Integer for the exponent data
                        return null;
                    int expbytes = (int)binr.ReadByte();        // should only need one byte for actual exponent data (for all useful values)
                    byte[] exponent = binr.ReadBytes(expbytes);

                    // ------- create RSACryptoServiceProvider instance and initialize with public key -----
                    var rsa = RSA.Create();
                    RSAParameters rsaKeyInfo = new RSAParameters
                    {
                        Modulus = modulus,
                        Exponent = exponent
                    };
                    rsa.ImportParameters(rsaKeyInfo);

                    return rsa;
                }

            }
        }

        #endregion

        #region 导入密钥算法

        private int GetIntegerSize(BinaryReader binr)
        {
            byte bt = 0;
            int count = 0;
            bt = binr.ReadByte();
            if (bt != 0x02)
                return 0;
            bt = binr.ReadByte();

            if (bt == 0x81)
                count = binr.ReadByte();
            else if (bt == 0x82)
            {
                var highbyte = binr.ReadByte();
                var lowbyte = binr.ReadByte();
                byte[] modint = { lowbyte, highbyte, 0x00, 0x00 };
                count = BitConverter.ToInt32(modint, 0);
            }
            else
            {
                count = bt;
            }

            while (binr.ReadByte() == 0x00)
            {
                count -= 1;
            }
            binr.BaseStream.Seek(-1, SeekOrigin.Current);
            return count;
        }

        private bool CompareBytearrays(byte[] a, byte[] b)
        {
            if (a.Length != b.Length)
                return false;
            int i = 0;
            foreach (byte c in a)
            {
                if (c != b[i])
                    return false;
                i++;
            }
            return true;
        }

        #endregion

    }

    /// <summary>
    /// RSA算法类型
    /// </summary>
    public enum RsaType
    {
        /// <summary>
        /// SHA1
        /// </summary>
        RSA = 0,
        /// <summary>
        /// RSA2 密钥长度至少为2048
        /// SHA256
        /// </summary>
        RSA2
    }
    #endregion
}