article

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 (https://bouncycastle.org/)

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;
        }
    }
}
gameon
10 |5000 characters needed characters left characters exceeded

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

Article

Contributors

levonl contributed to this article