示例#1
0
        public static CryptographicKey Load(string pubKeyContent)
        {
            CryptographicPublicKeyBlobType blobType;

            var block = new Pem(pubKeyContent);

            if (block.Type == null) //not pem encoded
            {
                //trying to guess blob type
                blobType = pubKeyContent.StartsWith("MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8A")
                    ? CryptographicPublicKeyBlobType.X509SubjectPublicKeyInfo
                    : CryptographicPublicKeyBlobType.Pkcs1RsaPublicKey;
            }
            else if ("PUBLIC KEY".Equals(block.Type))
            {
                blobType = CryptographicPublicKeyBlobType.X509SubjectPublicKeyInfo;
            }
            else if ("RSA PUBLIC KEY".Equals(block.Type))
            {
                blobType = CryptographicPublicKeyBlobType.Pkcs1RsaPublicKey;
            }
            else
            {
                throw new Exception(string.Format("PublicKey.Load(): Unsupported type in PEM block '{0}'", block.Type));
            }

            return(AsymmetricKeyAlgorithmProvider.OpenAlgorithm(AsymmetricAlgorithmNames.RsaPkcs1)
                   .ImportPublicKey(CryptographicBuffer.CreateFromByteArray(block.Decoded), blobType));
        }
        private CryptographicKey GenerateAsymmetricKey()
        {
            String algName = AlgorithmNames.SelectionBoxItem.ToString();
            UInt32 keySize = UInt32.Parse(KeySizes.SelectionBoxItem.ToString());

            CryptographicKey keyPair;
            // Create an AsymmetricKeyAlgorithmProvider object for the algorithm specified on input.
            AsymmetricKeyAlgorithmProvider Algorithm = AsymmetricKeyAlgorithmProvider.OpenAlgorithm(algName);

            EncryptDecryptText.Text += "*** Sample Encryption Algorithm\n";
            EncryptDecryptText.Text += "    Algorithm Name: " + Algorithm.AlgorithmName + "\n";
            EncryptDecryptText.Text += "    Key Size: " + keySize + "\n";

            // Generate a key pair.
            try
            {
                keyPair = Algorithm.CreateKeyPair(keySize);
            }
            catch (ArgumentException ex)
            {
                EncryptDecryptText.Text += ex.Message + "\n";
                EncryptDecryptText.Text += "An invalid key size was specified for the given algorithm.";
                return(null);
            }
            return(keyPair);
        }
        async public void Decrypt()
        {
            CryptographicKey cryptographicKey = null;
            FileOpenPicker   fileOpenPicker   = new FileOpenPicker();

            fileOpenPicker.SuggestedStartLocation = PickerLocationId.PicturesLibrary;
            fileOpenPicker.FileTypeFilter.Add("*");
            StorageFile file = await fileOpenPicker.PickSingleFileAsync();

            IBuffer bufferPrivateKey = await FileIO.ReadBufferAsync(file);

            AsymmetricKeyAlgorithmProvider provider = AsymmetricKeyAlgorithmProvider.OpenAlgorithm(AsymmetricAlgorithmNames.RsaPkcs1);

            try { cryptographicKey = provider.ImportKeyPair(bufferPrivateKey); }
            catch (Exception er) {
            }


            try { decryptedkey = CryptographicEngine.Decrypt(cryptographicKey, buffEncryptedSessionKey, null); }

            catch (Exception er)
            {
                ContentDialog contentDialog = new ContentDialog();
                contentDialog.Title           = "Wrong private key";
                contentDialog.Content         = "Try another private key";
                contentDialog.CloseButtonText = "Ok";

                await contentDialog.ShowAsync();
            }



            T8.Text = "Decrypted Key Base64: " + CryptographicBuffer.EncodeToBase64String(decryptedkey);
            T9.Text = "Decrypted Key BaseHex: " + CryptographicBuffer.EncodeToHexString(decryptedkey);
        }
示例#4
0
        public byte[] Sign(byte[] securedInput, object key)
        {
            //using (var sha = HashAlgorithm)
            //{
            //var privateKey = Ensure.Type<AsymmetricAlgorithm>(key, "RsaUsingSha alg expects key to be of AsymmetricAlgorithm type.");

            AsymmetricKeyAlgorithmProvider provider =
                AsymmetricKeyAlgorithmProvider.OpenAlgorithm(AsymmetricAlgorithmNames.RsaSignPkcs1Sha256);

            //CryptographicKey cryptographicKey = (CryptographicKey)key;
            CryptographicKey cryptographicKey = provider.ImportKeyPair(((CryptographicKey)key).Export(CryptographicPrivateKeyBlobType.BCryptPrivateKey),
                                                                       CryptographicPrivateKeyBlobType.BCryptPrivateKey);

            //provider.ImportKeyPair(null, CryptographicPrivateKeyBlobType.)

            IBuffer signedData =
                CryptographicEngine.Sign(cryptographicKey, CryptographicBuffer.CreateFromByteArray(securedInput));

            byte[] result;
            CryptographicBuffer.CopyToByteArray(signedData, out result);

            return(result);

            //var pkcs1 = new RSAPKCS1SignatureFormatter(privateKey);
            //pkcs1.SetHashAlgorithm(hashMethod);

            //return pkcs1.CreateSignature(sha.ComputeHash(securedInput));
            //}
        }
示例#5
0
文件: RSAConvert.cs 项目: ViperL/UWP
        /// <summary>
        /// WPRT的RSA私钥解密
        /// </summary>
        /// <param name="rawData"></param>
        /// <returns></returns>
        public static string PrivateDecrypt(string rawData)
        {
            try
            {
                /*将文本转换成IBuffer*/
                IBuffer bufferRawData = CryptographicBuffer.ConvertStringToBinary(rawData, BinaryStringEncoding.Utf8);

                /*加密算法提供程序*/
                AsymmetricKeyAlgorithmProvider provider = AsymmetricKeyAlgorithmProvider.OpenAlgorithm
                                                              (AsymmetricAlgorithmNames.RsaPkcs1);

                /*导入私钥*/
                string           PRIVATE_KEY = "MIICXAIBAAKBgQCJIYvV7IEzHOm4vdgu8RWc9it09ggXCKNAMEtcQM4kXT1mQyEnbEeGVYOyJWTd2jVhpToxMQ4r9p9EKd1bMClAA/KhUjQC/l9YdS3MFAZC65V47Bx6CTad4bZo1E1D6x1rOjQe4lANxWnApwY4QPYGFxEmQD3yNyErh38VlNL2GQIDAQABAoGAFxGmpZFI1uFpTCPbx2HVQfeDrgRprf5NAFJfiyB3zVRGLPrkC+7CRY4DPqfdxRidXFTgakAXYzv05RGp5FpAxf1GBAR6HQxVcntBpNqJUo2UBP+IrXgPFDPdodAl9SWgaHKwc79pCARVdJutm86kRRsy5rjcWpR8HQCYWzk/lmUCQQDcRnenz6CAhMvztS04APlly3uhvLGIVsXkGdsmv7JltRvFmZ/1MqpvAbC6WrzFMlWeFgYz6EyBiqfH6m4CbdJbAkEAn18K40E3r9WzPlbhIAEs2SiY68iZGCmzR/0n6PR48NtFSGsSDRIR632oeftBPfN7W4+kUIehL2gt9RgnRH8bmwJBAJMYK4dQSyoHg/q2nf+sBt9HRsP2sccNyxBLg+EYWhU5H9aQhBTFRLLkOhP3y98TgcETjAjVs2E+KlSB4/yTQckCQH4axVG23CptDQyp0C7z3xnh7sa7DrC45lxzK25Aa6YhyruXxUvEXZuZ7YK/1gsAKz7y9RCnkVoitCK4vvGLJjsCQBbzsW7HwZVe5RMiRsjxX7v0Ng4NnM85tnX0GUmkpuixOpfcq3PsZo7ujcBvJ5IJvbXo4QuuIRKSmxItHI26tkI=";
                CryptographicKey privateKey  = provider.ImportKeyPair(CryptographicBuffer.DecodeFromBase64String(PRIVATE_KEY));

                //解密
                IBuffer result = CryptographicEngine.Decrypt(privateKey, bufferRawData, null);
                byte[]  res;
                CryptographicBuffer.CopyToByteArray(result, out res);
                return(Encoding.UTF8.GetString(res, 0, res.Length));
            }
            catch (Exception)
            {
                return(rawData);
            }
        }
示例#6
0
        public string WinRTEncrypt1(byte[] test, string publicKey)
        {
            string strIn = "))))";

            IBuffer plainBuffer = CryptographicBuffer.ConvertStringToBinary(strIn, BinaryStringEncoding.Utf8);

            strIn = CryptographicBuffer.EncodeToBase64String(plainBuffer);

            plainBuffer = CryptographicBuffer.ConvertStringToBinary(strIn, BinaryStringEncoding.Utf8);


            // <asymmetric>
            AsymmetricKeyAlgorithmProvider asym = AsymmetricKeyAlgorithmProvider.OpenAlgorithm(AsymmetricAlgorithmNames.RsaPkcs1);
            //AsymmetricKeyAlgorithmProvider asym = AsymmetricKeyAlgorithmProvider.OpenAlgorithm(AsymmetricAlgorithmNames.RsaOaepSha256);

            IBuffer          keyBuffer       = CryptographicBuffer.DecodeFromBase64String(publicKey);
            CryptographicKey key             = asym.ImportPublicKey(keyBuffer, CryptographicPublicKeyBlobType.Pkcs1RsaPublicKey);
            IBuffer          encryptedBuffer = CryptographicEngine.Encrypt(key, plainBuffer, null);

            // </asymmetric>

            /*
             * // <symmetric>
             * SymmetricKeyAlgorithmProvider sym = SymmetricKeyAlgorithmProvider.OpenAlgorithm(SymmetricAlgorithmNames.AesCbc);
             *
             * IBuffer temp_key = CryptographicBuffer.ConvertStringToBinary("1234567890", BinaryStringEncoding.Utf8);
             *
             * string keyblyad = CryptographicBuffer.EncodeToBase64String(temp_key);
             *
             * IBuffer key_buffer = CryptographicBuffer.ConvertStringToBinary(keyblyad, BinaryStringEncoding.Utf8);
             *
             * CryptographicKey key1 = sym.CreateSymmetricKey(key_buffer);
             * IBuffer encryptedBuffer = CryptographicEngine.Encrypt(key1, plainBuffer, null);
             * // </symmetric>
             */


            byte[] lole = encryptedBuffer.ToArray();

            string lol = "";

            for (int i = 0; i < lole.Length; i++)
            {
                lol += (char)lole[i];
            }

            textBox3.Text = lol;

            //string result = CryptographicBuffer.EncodeToHexString(encryptedBuffer);

            //string result = CryptographicBuffer.ConvertBinaryToString(BinaryStringEncoding.Utf16LE, encryptedBuffer);

            string result = CryptographicBuffer.EncodeToBase64String(encryptedBuffer);

            //result = CryptographicBuffer.EncodeToBase64String(encryptedSymBuffer);

            //string result = CryptographicBuffer.EncodeToBase64String(buffUTF8);

            return(result);
        }
示例#7
0
        private void AsymmetricImportExport(CryptographicKey keyPair)
        {
            String algName = AlgorithmNames.SelectionBoxItem.ToString();
            AsymmetricKeyAlgorithmProvider Algorithm = AsymmetricKeyAlgorithmProvider.OpenAlgorithm(algName);

            // Export the public key.
            IBuffer blobOfPublicKey = keyPair.ExportPublicKey();
            IBuffer blobOfKeyPair   = keyPair.Export();

            SignVerifyText.Text += "    Key pair was successfully exported.\n";

            // Import the public key.
            CryptographicKey keyPublic = Algorithm.ImportPublicKey(blobOfPublicKey);

            // Check the key size.
            if (keyPublic.KeySize != keyPair.KeySize)
            {
                SignVerifyText.Text += "ImportPublicKey failed!  The imported key's size did not match the original's!";
                return;
            }
            SignVerifyText.Text += "    Public key was successfully imported.\n";

            // Import the key pair.
            keyPair = Algorithm.ImportKeyPair(blobOfKeyPair);

            // Check the key size.
            if (keyPublic.KeySize != keyPair.KeySize)
            {
                SignVerifyText.Text += "ImportKeyPair failed!  The imported key's size did not match the original's!";
                return;
            }
            SignVerifyText.Text += "    Key pair was successfully imported.\n";
        }
示例#8
0
        public static byte[] Decrypt(SecureString privateKey, byte[] data)
        {
            if (privateKey == null)
            {
                throw new ArgumentNullException(nameof(privateKey));
            }

            if (data == null)
            {
                throw new ArgumentNullException(nameof(data));
            }
#if WINDOWS_UWP
            var keyBuffer = CryptographicBuffer.DecodeFromBase64String(privateKey.GetString());

            var asym = AsymmetricKeyAlgorithmProvider.OpenAlgorithm(AsymmetricAlgorithmNames.RsaPkcs1);
            var key  = asym.ImportKeyPair(keyBuffer, CryptographicPrivateKeyBlobType.Capi1PrivateKey);

            var plainBuffer = CryptographicEngine.Decrypt(key, data.AsBuffer(), null);

            byte[] plainBytes;
            CryptographicBuffer.CopyToByteArray(plainBuffer, out plainBytes);

            return(plainBytes);
#else
            var cspParams = new CspParameters {
                ProviderType = 1                                 /* PROV_RSA_FULL */
            };
            var rsaProvider = new RSACryptoServiceProvider(cspParams);
            rsaProvider.ImportCspBlob(Convert.FromBase64String(privateKey.GetString()));
            return(rsaProvider.Decrypt(data, false));
#endif
        }
示例#9
0
        public static void GenerateKey(out byte[] fullKey, out byte[] publicKey)
        {
            var key = AsymmetricKeyAlgorithmProvider.OpenAlgorithm(AsymmetricAlgorithm.RsaSignPssSha512).CreateKeyPair(2048);

            fullKey   = key.Export();
            publicKey = key.ExportPublicKey();
        }
示例#10
0
        /// <summary>
        /// Encrypts data
        /// </summary>
        /// <param name="publicKey">The public key to use to encrypt the data</param>
        /// <param name="data">The data to encrypt</param>
        /// <returns>The ecrypted data</returns>
        /// <exception cref="ArgumentNullException"><paramref name="publicKey"/> is null</exception>
        /// <exception cref="ArgumentNullException"><paramref name="data"/> is null</exception>
        public static byte[] Encrypt(string publicKey, byte[] data)
        {
            if (publicKey == null)
            {
                throw new ArgumentNullException(nameof(publicKey));
            }

            if (data == null)
            {
                throw new ArgumentNullException(nameof(data));
            }
#if WINDOWS_UWP
            var keyBuffer = CryptographicBuffer.DecodeFromBase64String(publicKey);

            var asym = AsymmetricKeyAlgorithmProvider.OpenAlgorithm(AsymmetricAlgorithmNames.RsaPkcs1);
            var key  = asym.ImportPublicKey(keyBuffer, CryptographicPublicKeyBlobType.Capi1PublicKey);

            var plainBuffer     = CryptographicBuffer.CreateFromByteArray(data);
            var encryptedBuffer = CryptographicEngine.Encrypt(key, plainBuffer, null);

            byte[] encryptedBytes;
            CryptographicBuffer.CopyToByteArray(encryptedBuffer, out encryptedBytes);

            return(encryptedBytes);
#else
            var cspParams = new CspParameters {
                ProviderType = 1                                 /* PROV_RSA_FULL */
            };
            var rsaProvider = new RSACryptoServiceProvider(cspParams);

            rsaProvider.ImportCspBlob(Convert.FromBase64String(publicKey));

            return(rsaProvider.Encrypt(data, false));
#endif
        }
示例#11
0
        /// <summary>
        /// Creates a public and private key pair that can be used for asymmethric encryption
        /// </summary>
        /// <param name="keySize">The keysize to generate</param>
        /// <returns>The generated key size</returns>
        public static KeyPair CreateKeyPair(RSAKeySizes keySize)
        {
#if WINDOWS_UWP
            var asym = AsymmetricKeyAlgorithmProvider.OpenAlgorithm(AsymmetricAlgorithmNames.RsaPkcs1);
            var key  = asym.CreateKeyPair((uint)keySize);

            var privateKeyBuffer = key.Export(CryptographicPrivateKeyBlobType.Capi1PrivateKey);
            var publicKeyBuffer  = key.ExportPublicKey(CryptographicPublicKeyBlobType.Capi1PublicKey);

            byte[] privateKeyBytes;
            byte[] publicKeyBytes;

            CryptographicBuffer.CopyToByteArray(privateKeyBuffer, out privateKeyBytes);
            CryptographicBuffer.CopyToByteArray(publicKeyBuffer, out publicKeyBytes);

            string privateKey = Convert.ToBase64String(privateKeyBytes);
            string publicKey  = Convert.ToBase64String(publicKeyBytes);
#else
            var cspParams = new CspParameters {
                ProviderType = 1                                 /* PROV_RSA_FULL */
            };
            var rsaProvider = new RSACryptoServiceProvider((int)keySize, cspParams);

            string publicKey  = Convert.ToBase64String(rsaProvider.ExportCspBlob(false));
            string privateKey = Convert.ToBase64String(rsaProvider.ExportCspBlob(true));
#endif
            return(new KeyPair(privateKey.ToSecureString(), publicKey));
        }
        public async Task <byte[]> Sign(CancellationToken ct, string pairName, byte[] data)
        {
            if (this.Log().IsEnabled(LogLevel.Debug))
            {
                this.Log().Debug($"Signing a key pair (pair name: '{pairName}').");
            }

            pairName.Validation().NotNullOrEmpty(nameof(pairName));
            data.Validation().NotNull(nameof(data));

            await AssertIsEnabled(ct);

            using (await _asyncLock.LockAsync(ct))
            {
                var algorithm = AsymmetricKeyAlgorithmProvider.OpenAlgorithm(AsymmetricAlgorithmNames.EcdsaP256Sha256);

                var rawKeyPair = RetrieveKey(pairName).AsBuffer();

                var keyPair = algorithm.ImportKeyPair(rawKeyPair);

                using (var sha256 = SHA256.Create())
                {
                    var hash = sha256.ComputeHash(data);

                    var signature = await CryptographicEngine.SignHashedDataAsync(keyPair, hash.AsBuffer());

                    if (this.Log().IsEnabled(LogLevel.Information))
                    {
                        this.Log().Info($"Successfully signed a key pair (pair name: '{pairName}').");
                    }

                    return(signature.ToArray());
                }
            }
        }
        public async Task <byte[]> GenerateKeyPair(CancellationToken ct, string name)
        {
            if (this.Log().IsEnabled(LogLevel.Debug))
            {
                this.Log().Debug($"Generating a key pair (name: '{name}').");
            }

            name.Validation().NotNullOrEmpty(nameof(name));

            await AssertIsEnabled(ct);

            using (await _asyncLock.LockAsync(ct))
            {
                var algorithm = AsymmetricKeyAlgorithmProvider.OpenAlgorithm(AsymmetricAlgorithmNames.EcdsaP256Sha256);

                var keyPair = algorithm.CreateKeyPair(256);

                SaveKey(name, keyPair.Export().ToArray());

                if (this.Log().IsEnabled(LogLevel.Information))
                {
                    this.Log().Info($"Return the successfully generated key pair (name: '{name}').");
                }

                return(keyPair.ExportPublicKey().ToArray());
            }
        }
        public static CryptographicKey Load(string privKeyContent)
        {
            CryptographicPrivateKeyBlobType blobType;

            var block = new Pem(privKeyContent);

            if (block.Type == null) //not pem encoded
            {
                throw new Exception("PrivateKey.Load(): Only PEM encoded blocks are supported, but was given not PEM encoded.");
            }
            if ("PRIVATE KEY".Equals(block.Type))
            {
                blobType = CryptographicPrivateKeyBlobType.Pkcs8RawPrivateKeyInfo;
            }
            else if ("RSA PRIVATE KEY".Equals(block.Type))
            {
                blobType = CryptographicPrivateKeyBlobType.Pkcs1RsaPrivateKey;
            }
            else
            {
                throw new Exception(string.Format("PrivateKey.Load(): Unsupported type in PEM block '{0}'", block.Type));
            }

            return(AsymmetricKeyAlgorithmProvider.OpenAlgorithm(AsymmetricAlgorithmNames.RsaPkcs1)
                   .ImportKeyPair(CryptographicBuffer.CreateFromByteArray(block.Decoded), blobType));
        }
示例#15
0
        /// <summary>
        /// Checks directory for keys and returns a boolean
        ///
        /// true = keys exists
        /// false = keys do not exists
        ///
        /// </summary>
        /// <returns></returns>
        private static async System.Threading.Tasks.Task <bool> checkKeysDirectory()
        {
            // read keypair for sender if it exists
            StorageFolder localFolder =
                ApplicationData.Current.LocalFolder;

            try
            {
                StorageFile senderKeyPair =
                    await localFolder.GetFileAsync(DataContainer.User + ".KeyPair");

                if (senderKeyPair != null)
                {
                    string keyPairText = await FileIO.ReadTextAsync(senderKeyPair);

                    // buffer from text
                    DataContainer.senderKeyPair = decode64BaseString(keyPairText);
                    // Open the algorithm provider for the specified asymmetric algorithm.
                    AsymmetricKeyAlgorithmProvider objAlgProv = AsymmetricKeyAlgorithmProvider.OpenAlgorithm(strAsymmetricAlgName);

                    // Import the public key from a buffer.
                    CryptographicKey keyPair = objAlgProv.ImportKeyPair(DataContainer.senderKeyPair);
                    DataContainer.senderPublicKey = keyPair.ExportPublicKey();

                    return(true);
                }
            }
            catch (System.IO.FileNotFoundException ex)
            {
                Debug.WriteLine(ex.ToString());
            }

            return(false);
        }
示例#16
0
 public bool VerifySignature(byte[] key)
 {
     return(CryptographicEngine.VerifySignature(
                AsymmetricKeyAlgorithmProvider.OpenAlgorithm(AsymmetricAlgorithm.RsaSignPssSha512).ImportPublicKey(key),
                Encoding.Unicode.GetBytes(License.ToJson(Formatting.None)),
                Convert.FromBase64String(Signature)));
 }
示例#17
0
        public static string WinRTEncrypt(string publicKey, string data)
        {
            string strIn = "Input String";

            IBuffer buffUTF8 = CryptographicBuffer.ConvertStringToBinary(strIn, BinaryStringEncoding.Utf8);
            String  strUTF8  = CryptographicBuffer.ConvertBinaryToString(BinaryStringEncoding.Utf8, buffUTF8);

            IBuffer keyBuffer = CryptographicBuffer.DecodeFromBase64String(publicKey);

            AsymmetricKeyAlgorithmProvider asym = AsymmetricKeyAlgorithmProvider.OpenAlgorithm(AsymmetricAlgorithmNames.RsaPkcs1);
            //AsymmetricKeyAlgorithmProvider asym = AsymmetricKeyAlgorithmProvider.OpenAlgorithm(AsymmetricAlgorithmNames.RsaOaepSha256);

            CryptographicKey key = asym.ImportPublicKey(keyBuffer, CryptographicPublicKeyBlobType.Pkcs1RsaPublicKey);

            IBuffer plainBuffer     = CryptographicBuffer.ConvertStringToBinary(strIn, BinaryStringEncoding.Utf8);
            IBuffer encryptedBuffer = CryptographicEngine.Encrypt(key, plainBuffer, null);


            //string result = CryptographicBuffer.EncodeToHexString(encryptedBuffer);

            //string result = CryptographicBuffer.ConvertBinaryToString(BinaryStringEncoding.Utf16LE, encryptedBuffer);

            string result = CryptographicBuffer.EncodeToBase64String(encryptedBuffer);

            return(result);
        }
示例#18
0
        //Decrypts Data (Always using private key)
        public static string Decrypt(String strAsymmetricAlgName, IBuffer buffPrivateKeyStorage, string encryptedMessage)
        {
            // Open the algorithm provider for the specified asymmetric algorithm.
            AsymmetricKeyAlgorithmProvider objAsymmAlgProv = AsymmetricKeyAlgorithmProvider.OpenAlgorithm(strAsymmetricAlgName);

            // Import the public key from a buffer. You should keep your private key
            // secure. For the purposes of this example, however, the private key is
            // just stored in a static class variable.
            CryptographicKey keyPair = objAsymmAlgProv.ImportKeyPair(buffPrivateKeyStorage);

            //Convert message String to IBuffer
            IBuffer convertedString = CryptographicBuffer.DecodeFromBase64String(encryptedMessage);
            IBuffer buffDecryptedMessage;

            try {
                // Use the private key embedded in the key pair to decrypt the session key.
                buffDecryptedMessage = CryptographicEngine.Decrypt(keyPair, convertedString, null);
            } catch (System.ArgumentException) {
                string invalidDecryptionMessage = "INVALID DECRYPTION KEY";
                return(invalidDecryptionMessage);
            }

            //Return decrpyted message as a string
            string decryptedMessage = CryptographicBuffer.ConvertBinaryToString(BinaryStringEncoding.Utf8, buffDecryptedMessage);

            return(decryptedMessage);
        }
示例#19
0
        /// <summary>
        /// 加密密码
        /// </summary>
        /// <param name="password">密码</param>
        /// <returns></returns>
        private async Task <string> EncryptedPasswordAsync(string password)
        {
            string base64String;

            try
            {
                string param   = BiliTool.UrlContact("").TrimStart('?');
                string content = await BiliTool.PostContentToWebAsync(Api.PASSPORT_KEY_ENCRYPT, param);

                JObject jobj     = JObject.Parse(content);
                string  str      = jobj["data"]["hash"].ToString();
                string  str1     = jobj["data"]["key"].ToString();
                string  str2     = string.Concat(str, password);
                string  str3     = Regex.Match(str1, "BEGIN PUBLIC KEY-----(?<key>[\\s\\S]+)-----END PUBLIC KEY").Groups["key"].Value.Trim();
                byte[]  numArray = Convert.FromBase64String(str3);
                AsymmetricKeyAlgorithmProvider asymmetricKeyAlgorithmProvider = AsymmetricKeyAlgorithmProvider.OpenAlgorithm(AsymmetricAlgorithmNames.RsaPkcs1);
                CryptographicKey cryptographicKey = asymmetricKeyAlgorithmProvider.ImportPublicKey(WindowsRuntimeBufferExtensions.AsBuffer(numArray), 0);
                IBuffer          buffer           = CryptographicEngine.Encrypt(cryptographicKey, WindowsRuntimeBufferExtensions.AsBuffer(Encoding.UTF8.GetBytes(str2)), null);
                base64String = Convert.ToBase64String(WindowsRuntimeBufferExtensions.ToArray(buffer));
            }
            catch (Exception)
            {
                base64String = password;
            }
            return(base64String);
        }
示例#20
0
        /// <summary>
        /// Проверка лицензии
        /// </summary>
        /// <returns></returns>
        public bool IsLicenseValid()
        {
            bool res = false;

            try
            {
                IBuffer SignatureBuffer       = Signature.AsBuffer();
                IBuffer ServerPublicKeyBuffer = Convert.FromBase64String(GlobalVars.ServerPublicKey).AsBuffer();
                AsymmetricKeyAlgorithmProvider RSAVerifyProv = AsymmetricKeyAlgorithmProvider.OpenAlgorithm(AsymmetricAlgorithmNames.RsaSignPkcs1Sha512);
                CryptographicKey ServerPublicKey             = RSAVerifyProv.ImportPublicKey(ServerPublicKeyBuffer, CryptographicPublicKeyBlobType.Capi1PublicKey);
                byte[]           tmpuseridbytes   = Encoding.UTF8.GetBytes(UserID);
                byte[]           tmpregdtbytes    = BitConverter.GetBytes(RegistrationDateTime);
                byte[]           tmpregdtstrbytes = Encoding.UTF8.GetBytes(RegistrationDateTimeStr);
                byte[]           tmpdevcountbytes = BitConverter.GetBytes(DeviceCountLimit);
                byte[]           tmpendpointbytes = Encoding.UTF8.GetBytes(ServerEndPoint);
                byte[]           tmpbytes         = new byte[tmpuseridbytes.Length + tmpregdtbytes.Length + tmpregdtstrbytes.Length + tmpdevcountbytes.Length + tmpendpointbytes.Length];
                Array.Copy(tmpuseridbytes, tmpbytes, tmpuseridbytes.Length);
                Array.Copy(tmpregdtbytes, 0, tmpbytes, tmpuseridbytes.Length, tmpregdtbytes.Length);
                Array.Copy(tmpregdtstrbytes, 0, tmpbytes, tmpuseridbytes.Length + tmpregdtbytes.Length, tmpregdtstrbytes.Length);
                Array.Copy(tmpdevcountbytes, 0, tmpbytes, tmpuseridbytes.Length + tmpregdtbytes.Length + tmpregdtstrbytes.Length, tmpdevcountbytes.Length);
                Array.Copy(tmpendpointbytes, 0, tmpbytes, tmpuseridbytes.Length + tmpregdtbytes.Length + tmpregdtstrbytes.Length + tmpdevcountbytes.Length, tmpendpointbytes.Length);
                string strAlgName = HashAlgorithmNames.Sha512;
                HashAlgorithmProvider objAlgProv = HashAlgorithmProvider.OpenAlgorithm(strAlgName);
                CryptographicHash     objHash    = objAlgProv.CreateHash();
                objHash.Append(tmpbytes.AsBuffer());
                IBuffer tmpbyteshash = objHash.GetValueAndReset();
                res = CryptographicEngine.VerifySignatureWithHashInput(ServerPublicKey, tmpbyteshash, SignatureBuffer);
            }
            catch /*(Exception ex)*/
            {
            }
            return(res);
        }
示例#21
0
        public void createAsymmetricKeyPair(
            String strAsymmetricAlgName,
            UInt32 keyLength,
            out IBuffer buffPublicKey)
        {
            // Open the algorithm provider for the specified asymmetric algorithm.
            AsymmetricKeyAlgorithmProvider objAlgProv = AsymmetricKeyAlgorithmProvider.OpenAlgorithm(strAsymmetricAlgName);

            // Demonstrate use of the AlgorithmName property (not necessary to create a key pair).
            String strAlgName = objAlgProv.AlgorithmName;

            // Create an asymmetric key pair.
            CryptographicKey keyPair = objAlgProv.CreateKeyPair(keyLength);

            // Export the public key to a buffer for use by others.
            buffPublicKey = keyPair.ExportPublicKey();

            //public key to internal buffer
            DataContainer.senderPublicKey = buffPublicKey;

            // You should keep your private key (embedded in the key pair) secure. For
            // the purposes of this example, however, we're just copying it into a
            // static class variable for later use during decryption.
            DataContainer.senderKeyPair = keyPair.Export();
        }
        public Task <byte[]> RsaDecryptAsync(byte[] data, byte[] privateKey, CryptoHashAlgorithm algorithm)
        {
            var provider  = AsymmetricKeyAlgorithmProvider.OpenAlgorithm(ToAsymmetricAlgorithm(algorithm));
            var cryptoKey = provider.ImportKeyPair(privateKey, CryptographicPrivateKeyBlobType.Pkcs8RawPrivateKeyInfo);

            return(Task.FromResult(CryptographicEngine.Decrypt(cryptoKey, data)));
        }
示例#23
0
        public static async Task <string> GetEncryptedPassword(string passWord)
        {
            string base64String;

            try
            {
                //https://secure.bilibili.com/login?act=getkey&rnd=4928
                //https://passport.bilibili.com/login?act=getkey&rnd=4928
                HttpBaseProtocolFilter httpBaseProtocolFilter = new HttpBaseProtocolFilter();
                httpBaseProtocolFilter.IgnorableServerCertificateErrors.Add(Windows.Security.Cryptography.Certificates.ChainValidationResult.Expired);
                httpBaseProtocolFilter.IgnorableServerCertificateErrors.Add(Windows.Security.Cryptography.Certificates.ChainValidationResult.Untrusted);
                Windows.Web.Http.HttpClient httpClient = new Windows.Web.Http.HttpClient(httpBaseProtocolFilter);
                //WebClientClass wc = new WebClientClass();
                string stringAsync = await httpClient.GetStringAsync((new Uri("https://passport.bilibili.com/login?act=getkey&rnd=" + new Random().Next(1000, 9999), UriKind.Absolute)));

                JObject jObjects = JObject.Parse(stringAsync);
                string  str      = jObjects["hash"].ToString();
                string  str1     = jObjects["key"].ToString();
                string  str2     = string.Concat(str, passWord);
                string  str3     = Regex.Match(str1, "BEGIN PUBLIC KEY-----(?<key>[\\s\\S]+)-----END PUBLIC KEY").Groups["key"].Value.Trim();
                byte[]  numArray = Convert.FromBase64String(str3);
                AsymmetricKeyAlgorithmProvider asymmetricKeyAlgorithmProvider = AsymmetricKeyAlgorithmProvider.OpenAlgorithm(AsymmetricAlgorithmNames.RsaPkcs1);
                CryptographicKey cryptographicKey = asymmetricKeyAlgorithmProvider.ImportPublicKey(WindowsRuntimeBufferExtensions.AsBuffer(numArray), 0);
                IBuffer          buffer           = CryptographicEngine.Encrypt(cryptographicKey, WindowsRuntimeBufferExtensions.AsBuffer(Encoding.UTF8.GetBytes(str2)), null);
                base64String = Convert.ToBase64String(WindowsRuntimeBufferExtensions.ToArray(buffer));
            }
            catch (Exception)
            {
                //throw;
                base64String = passWord;
            }
            return(base64String);
        }
示例#24
0
        private async Task <string> EncryptedPassword(string passWord)
        {
            string base64String;

            try
            {
                HttpBaseProtocolFilter httpBaseProtocolFilter = new HttpBaseProtocolFilter();
                httpBaseProtocolFilter.IgnorableServerCertificateErrors.Add(Windows.Security.Cryptography.Certificates.ChainValidationResult.Expired);
                httpBaseProtocolFilter.IgnorableServerCertificateErrors.Add(Windows.Security.Cryptography.Certificates.ChainValidationResult.Untrusted);
                var    jObjects = (await accountApi.GetKey().Request()).GetJObject();
                string str      = jObjects["data"]["hash"].ToString();
                string str1     = jObjects["data"]["key"].ToString();
                string str2     = string.Concat(str, passWord);
                string str3     = Regex.Match(str1, "BEGIN PUBLIC KEY-----(?<key>[\\s\\S]+)-----END PUBLIC KEY").Groups["key"].Value.Trim();
                byte[] numArray = Convert.FromBase64String(str3);
                AsymmetricKeyAlgorithmProvider asymmetricKeyAlgorithmProvider = AsymmetricKeyAlgorithmProvider.OpenAlgorithm(AsymmetricAlgorithmNames.RsaPkcs1);
                CryptographicKey cryptographicKey = asymmetricKeyAlgorithmProvider.ImportPublicKey(WindowsRuntimeBufferExtensions.AsBuffer(numArray), 0);
                IBuffer          buffer           = CryptographicEngine.Encrypt(cryptographicKey, WindowsRuntimeBufferExtensions.AsBuffer(Encoding.UTF8.GetBytes(str2)), null);
                base64String = Convert.ToBase64String(WindowsRuntimeBufferExtensions.ToArray(buffer));
            }
            catch (Exception)
            {
                base64String = passWord;
            }
            return(base64String);
        }
示例#25
0
        private static async Task <string> EncryptedPassword(string passWord)
        {
            string base64String;

            try
            {
                HttpBaseProtocolFilter httpBaseProtocolFilter = new HttpBaseProtocolFilter();
                httpBaseProtocolFilter.IgnorableServerCertificateErrors.Add(Windows.Security.Cryptography.Certificates.ChainValidationResult.Expired);
                httpBaseProtocolFilter.IgnorableServerCertificateErrors.Add(Windows.Security.Cryptography.Certificates.ChainValidationResult.Untrusted);
                Windows.Web.Http.HttpClient httpClient = new Windows.Web.Http.HttpClient(httpBaseProtocolFilter);
                string url     = "https://passport.bilibili.com/api/oauth2/getKey";
                string content = $"appkey={ApiHelper.AndroidKey.Appkey}&mobi_app=android&platform=android&ts={ApiHelper.GetTimeSpan}";
                content += "&sign=" + ApiHelper.GetSign(content);
                string stringAsync = await WebClientClass.PostResults(new Uri(url), content);

                JObject jObjects = JObject.Parse(stringAsync);
                string  str      = jObjects["data"]["hash"].ToString();
                string  str1     = jObjects["data"]["key"].ToString();
                string  str2     = string.Concat(str, passWord);
                string  str3     = Regex.Match(str1, "BEGIN PUBLIC KEY-----(?<key>[\\s\\S]+)-----END PUBLIC KEY").Groups["key"].Value.Trim();
                byte[]  numArray = Convert.FromBase64String(str3);
                AsymmetricKeyAlgorithmProvider asymmetricKeyAlgorithmProvider = AsymmetricKeyAlgorithmProvider.OpenAlgorithm(AsymmetricAlgorithmNames.RsaPkcs1);
                CryptographicKey cryptographicKey = asymmetricKeyAlgorithmProvider.ImportPublicKey(WindowsRuntimeBufferExtensions.AsBuffer(numArray), 0);
                IBuffer          buffer           = CryptographicEngine.Encrypt(cryptographicKey, WindowsRuntimeBufferExtensions.AsBuffer(Encoding.UTF8.GetBytes(str2)), null);
                base64String = Convert.ToBase64String(WindowsRuntimeBufferExtensions.ToArray(buffer));
            }
            catch (Exception)
            {
                base64String = passWord;
            }
            return(base64String);
        }
示例#26
0
        // method to decrypt ciphertext of AES key
        public async void asymmetricDecryptAESKeySender(
            String strAsymmetricAlgName,
            IBuffer buffEncryptedAESKey)
        {
            // Open the algorithm provider for the specified asymmetric algorithm.
            AsymmetricKeyAlgorithmProvider objAsymmAlgProv = AsymmetricKeyAlgorithmProvider.OpenAlgorithm(strAsymmetricAlgName);

            CryptographicKey pair = objAsymmAlgProv.ImportKeyPair(DataContainer.senderKeyPair);

            try
            {
                // Use the private key embedded in the key pair to decrypt the session key.
                keyMaterialSender = CryptographicEngine.Decrypt(pair, buffEncryptedAESKey, null);
            }
            catch (System.ArgumentException ar)
            {
                Debug.WriteLine(ar.ToString());
                var dialog = new MessageDialog("Error: Key Mismatch. Unable to display new messages.");
                await dialog.ShowAsync();

                // CoreApplication.Exit();
            }


            //convert to string
            keyMaterialStringSender = CryptographicBuffer.EncodeToBase64String(keyMaterialSender);
        }
        public Task <byte[]> RsaExtractPublicKeyAsync(byte[] privateKey)
        {
            // Have to specify some algorithm
            var provider  = AsymmetricKeyAlgorithmProvider.OpenAlgorithm(AsymmetricAlgorithm.RsaOaepSha1);
            var cryptoKey = provider.ImportKeyPair(privateKey, CryptographicPrivateKeyBlobType.Pkcs8RawPrivateKeyInfo);

            return(Task.FromResult(cryptoKey.ExportPublicKey(CryptographicPublicKeyBlobType.X509SubjectPublicKeyInfo)));
        }
        public Task <byte[]> RsaEncryptAsync(byte[] data, byte[] publicKey, CryptoHashAlgorithm algorithm)
        {
            var provider  = AsymmetricKeyAlgorithmProvider.OpenAlgorithm(ToAsymmetricAlgorithm(algorithm));
            var cryptoKey = provider.ImportPublicKey(publicKey,
                                                     CryptographicPublicKeyBlobType.X509SubjectPublicKeyInfo);

            return(Task.FromResult(CryptographicEngine.Encrypt(cryptoKey, data)));
        }
        public bool IsSignatureValid(byte[] publicKey, byte[] data, byte[] signature)
        {
            string base64ServerKey = @"BgIAAACkAABSU0ExAAQAAAEAAQDZr6InA2zWwmTIQig+hi4AFP1+80cGdVf05OACoSPemuD1MlRhVv0FlNyrEPgEUltGpHLWjJVu+52ofFcZ4vlhA9ud63/GNwF+klu93wGnL7/9B3W1H5Wvdk1PBHKKrFgB5B+ThCpu60zU8+/xyqzZCImdm2OakrhqYo/PfHPgzQ==";
            var    alg             = AsymmetricKeyAlgorithmProvider.OpenAlgorithm(AsymmetricAlgorithmNames.RsaSignPkcs1Sha1);
            var    key             = alg.ImportPublicKey(CryptographicBuffer.DecodeFromBase64String(base64ServerKey));

            return(CryptographicEngine.VerifySignature(key, data.AsBuffer(), signature.AsBuffer()));
        }
示例#30
0
文件: RSA.cs 项目: orf53975/HenkChat
        public static byte[] Decrypt(byte[] Data, byte[] PrivateKey)
        {
            CryptographicKey key = AsymmetricKeyAlgorithmProvider.OpenAlgorithm(AsymmetricAlgorithmNames.RsaPkcs1).ImportKeyPair(PrivateKey.AsBuffer(), CryptographicPrivateKeyBlobType.Capi1PrivateKey);

            byte[] PlainData;
            CryptographicBuffer.CopyToByteArray(CryptographicEngine.Decrypt(key, Data.AsBuffer(), null), out PlainData);

            return(PlainData);
        }