Levon@Amazon avatar image
Levon@Amazon posted

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);
        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;
10 |5000

Up to 2 attachments (including images) can be used with a maximum of 512.0 KiB each and 1.0 MiB total.



levonl contributed to this article