Unity sample code for handling encryption / decryption of game keys

This Unity / C# sample demonstrates encryption of the game public key and the client public key. The sample uses Bouncy Castle crypto libraries.

using System;
using System.Security.Cryptography;
using System.Text;
using Org.BouncyCastle.Crypto;
using Org.BouncyCastle.Crypto.Parameters;
using Org.BouncyCastle.Security;

namespace crypto
{
    class Program
    {
        static String gamePublicKey = "your_game_public_key_here";
        static String clientPublicKey = "players_generated_1024_pkcs8_here";
        static void Main(string[] args)
        {
            // build key
            var rsaParameters = base64ToRsaParameters(gamePublicKey);
            // init crypto
            RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
            rsa.ImportParameters(rsaParameters); // Use gamePublicKey
            // encrypt
            var encryptedData = rsa.Encrypt(Encoding.UTF8.GetBytes(clientPublicKey), false);
            var encryptedPayload = Convert.ToBase64String(encryptedData);
            Console.WriteLine(encryptedPayload);
        }
        static RSAParameters base64ToRsaParameters(String cryptoKey) {
            byte[] publicKeyBytes = Convert.FromBase64String(gamePublicKey);
            AsymmetricKeyParameter asymmetricKeyParameter = PublicKeyFactory.CreateKey(publicKeyBytes);
            RsaKeyParameters rsaKeyParameters = (RsaKeyParameters)asymmetricKeyParameter;
            RSAParameters rsaParameters = new RSAParameters
            {
                Modulus = rsaKeyParameters.Modulus.ToByteArrayUnsigned(),
                Exponent = rsaKeyParameters.Exponent.ToByteArrayUnsigned()
            };
            return rsaParameters;
        }
    }
}

Related: