usingMaths.com
From Theory to Practice - Math You Can Use.







<< PreviousNext >>

Implementing Single, Secret Key Encryption in C#



C# Secret Key Encryption Using a Single Key

This page presents a C# secret key encryption tutorial based on a key-dependent encoding algorithm. The method demonstrates how a single secret key can be used to both encrypt and decrypt textual data using a mathematical recurrent sequence. The implementation is intended for educational purposes, helping students and developers understand the fundamentals of custom encryption algorithms in C#.

Secret Key Encryption in C# Explained

Encryption, or Encoding, simply is the art of leaving data in obfuscated form in order to keep it secure.

It could be as simple as replacing all characters in a text file with those from a predetermined set in a manner that has the original text having a direct correlation with the encrypted / encoded version.
An example of this is seen in the Base-64 Encoding System.

Encryption could also mean adding junk data to an original data in such a way that the original data is completely defaced but can still be comfortably extracted from the encrypted version.

Encryption processes must always be consistent: i.e. the same type of encryption, or encoding, carried out on the same data or file must always produce exactly the same obfuscated output.


What Is Single Key Encryption in C#?

Single key encryption, also known as symmetric encryption, is a cryptographic approach in which the same secret key is used for both encryption and decryption. In a C# context, this means that any party wishing to decode an encrypted message must possess the same key that was used to encode it.

In this tutorial, the secret key influences the encoding process directly. Each character in the message is transformed according to a mathematically generated sequence that depends on the key, making this a clear example of key-dependent encoding in C#.

How Single Key Encryption Works | Explanation for C# Kids

In secret key cryptography, both parties rely on the same key for encryption and decryption. We'll explore how C# cryptography algorithms apply recurrent series to strengthen security, ensuring that sensitive information remains protected.

With key dependent encryption, every unique key produces a completely different encoded set or obfuscated data.
This ensures better security of data since brute-forcing becomes very difficult without knowledge of the secret key used.
Also, the longer the key used, the more useless brute-forcing becomes.

This means that different individuals or firms can employ the same encryption process, but have their own unique secret key (Private Key) to encrypt data with.
Such encrypted data cannot be comfortably decrypted by a second firm using the same encryption process if the first firm can keep its key secret enough.


Overview of the C# Encryption Algorithm

The C# encryption algorithm used here is not based on standard cryptographic libraries or industry encryption standards. Instead, it illustrates how encryption can be constructed from first principles using mathematics and programming logic.

Key characteristics of the C# algorithm include:

  • A single secret key shared between encryption and decryption
  • A recurrent mathematical series generated from the key
  • Character-by-character transformation of plaintext
  • Reversible encoding that allows accurate decryption

This makes the approach well suited for learning how C# encryption and decryption mechanisms work internally, rather than for securing sensitive production data.

Key-Dependent Encoding Process | Explanation for C# Kids

At the core of this implementation is a key-dependent encoding algorithm in C#. The secret key is first converted into a numerical form, which then seeds a recurrent series. This series determines how each character's numeric representation is modified during encryption.

Because the same sequence can be regenerated using the same key, the process is fully reversible. During decryption, the algorithm applies the inverse operations to recover the original text.

This approach demonstrates an important principle in cryptography: the strength of an encryption system depends heavily on the secrecy and handling of the key.

Use of BigInteger for Large Number Arithmetic

C#'s native number type has limitations when working with very large integers. To overcome this, the algorithm uses the BigInteger library, allowing calculations to be performed beyond standard numeric bounds.

Using BigInteger enables:

  • Reliable handling of large values generated by the recurrent sequence
  • Accurate encryption and decryption without numeric overflow
  • A clearer demonstration of mathematical encryption with C#

This makes the example particularly useful for educational settings where precision and transparency are important.

C# Encryption and Decryption Example | Explanation for C# Kids

The following implementation shows how to encrypt text in C# using a single secret key, and how to decode the encrypted output using the same key. The example illustrates a complete **encode and decode workflow with a secret key**, highlighting the symmetry of the algorithm.

By studying the code, readers can observe how:

  • Plaintext characters are converted to numeric form
  • The key-generated sequence modifies each value
  • The encrypted output is produced and later reversed

This reinforces understanding of custom cryptography implementations in C#.


Geometric Sequences or Series | Maths Explanation for C# Kids

Remember Geometric Sequences and Series from Ordinary Level Mathematics; Recurrent Series to be precise? They become as useful as they can be here!

Recurrent Series has the unique characteristic that all succeeding terms in a progression are totally dependent on all preceding terms - i.e. for any Recurrent Series, any n+1th term cannot be determined unless the value of the nth term and its predecessors are known;
and even more true is the fact that every other term in the progression is absolutely dependent on the 1st term of the series.

So given the carefully selected recurrent series

$$ T_n = \frac{3^{n-1}(2t_1 + 1) - 1}{2} $$ where \(t_1\) is the first term,

We can exploit the core property of recurrent series and use the above sequence for encrypting data in C# with reference to single secret keys.

Create a new C++ class file;
Call it SoleKeyEncryption.
Type out the adjoining C++ code for encrypting a chunk of data with a secret key.


Important: BigInteger is inbuilt in C#.
You only need to use the System.Numerics library.

You might have to add the above library in the reference section - Project >> Add Reference...; tick off System.Numerics - to be able to use it.


Educational Use and Limitations | Explanation for C# Kids

While this example demonstrates core ideas behind encryption, it should not be used as a replacement for established cryptographic standards such as those provided by the Web Crypto API.

This tutorial is best suited for:

  • Learning how encryption algorithms work internally
  • Teaching cryptography concepts with C#
  • Exploring key-dependent encoding methods
  • Understanding the relationship between mathematics and data security

For real-world applications, standardized and peer-reviewed cryptographic libraries should always be used.

Applications of Secret Key Encryption Algorithm in C#

  • Securing user authentication systems
  • Protecting sensitive data in web applications
  • Implementing data security with C# for client-side operations

Summary: C# Secret Key Encryption Algorithm

This tutorial provides a clear and practical introduction to single key encryption in C# using a mathematical, key-dependent encoding algorithm. By combining recurrent sequences with BigInteger arithmetic, it demonstrates how encryption and decryption can be implemented from first principles.

The example serves as a foundation for further study in C# cryptography, algorithm design, and data security concepts. Mastering C# secret key encryption equips developers with essential skills for building secure applications.











C# Code for Sole Key Encryption - Class File

using System;
using System.Numerics;
using System.Globalization;

namespace Miscellaneous
{
    class SoleKeyEncryption
    {

        public SoleKeyEncryption()
        {
        }

        public string[] encodeWord(char[] msg, char[] key)
        {
            // encoding eqn { Tn = 3^n-1(2t1 + 1) - 1 } - please use your own eqn
            //                        2
            string[] encryption = new string[msg.Length];
            int n;
            int t1;
            BigInteger Tn;
            for (int i = 0; i < msg.Length; i++)
            {
                // get unicode of this character as t1
                t1 = (int)msg[i];
                // get next key digit as n
                n =  Convert.ToInt32(key[i % (key.Length - 1)].ToString(), 16);
                // use recurrence series equation to encrypt & save in base 16
                Tn = BigInteger.Divide(BigInteger.Subtract(BigInteger.Multiply(BigInteger.Pow(3, n - 1), 2 * t1 + 1), 1), 2);
                encryption[i] = Tn.ToString("X");
            }

            return encryption;
        }

        public string decodeWord(string[] code, char[] key)
        {
            // decoding eqn { t1 = 3^1-n(2Tn + 1) - 1 }
            //                        2
            string decryption = "";
            int n;
            BigInteger t1;
            BigInteger Tn;
            for (int i = 0; i < code.Length; i++)
            {
                Tn = BigInteger.Parse(code[i], NumberStyles.HexNumber);
                // get next key digit as n
                n = Convert.ToInt32(key[i % (key.Length - 1)].ToString(), 16);
                // use recurrence series equation to decrypt
                t1 = BigInteger.Divide(BigInteger.Subtract(BigInteger.Divide(2 * Tn + 1, BigInteger.Pow(3, n - 1)), 1), 2);
                decryption += (char)t1;
            }

            return decryption;
        }
    }
}


C# Code for Sole Key Encryption - Main Class

using System;

namespace Miscellaneous
{
    class Program
    {
        static void Main(string[] args)
        {
            char[] message = "merry xmas".ToCharArray();
            char[] key = "A5FB17C4D8".ToCharArray(); // you might want to avoid zeroes
            SoleKeyEncryption go_secure = new SoleKeyEncryption();

            string[] encrypted = go_secure.encodeWord(message, key);
            Console.WriteLine("Message is '" + String.Join("", message) +
                "';\nEncrypted version is " + String.Join(", ", encrypted));

            string decrypted = go_secure.decodeWord(encrypted, key);
            Console.WriteLine("\n\nDecrypted version is '" + decrypted + "'.");
        }
    }
}







<< PreviousNext >>