using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Security;
using System.Text;
using System.Threading.Tasks;
using Microsoft.VisualBasic;
// using Org.BouncyCastle.Crypto;
// using Org.BouncyCastle.Crypto.Engines;
// using Org.BouncyCastle.Crypto.Generators;
// using Org.BouncyCastle.Crypto.Modes;
// using Org.BouncyCastle.Crypto.Parameters;
// using Org.BouncyCastle.Security;
// using System.Configuration;
public class AES_GCM
{
// Public Shared ReadOnly Random As Org.BouncyCastle.Security.SecureRandom = New SecureRandom()
public static string SimpleEncryptWithPassword(string secretMessage, string password, byte[] nonSecretPayload = null)
{
if (string.IsNullOrEmpty(secretMessage))
throw new ArgumentException("Secret Message Required!", "secretMessage");
var plainText = Encoding.UTF8.GetBytes(secretMessage);
var cipherText = SimpleEncryptWithPassword(plainText, password, nonSecretPayload);
return Convert.ToBase64String(cipherText);
}
public static string SimpleDecryptWithPassword(string encryptedMessage, string password, int nonSecretPayloadLength = 0)
{
try
{
if (string.IsNullOrWhiteSpace(encryptedMessage))
throw new ArgumentException("Encrypted Message Required!", "encryptedMessage");
var cipherText = Convert.FromBase64String(encryptedMessage.TrimEnd(System.Convert.ToChar(0x0)));
var plainText = SimpleDecryptWithPassword(cipherText, password, nonSecretPayloadLength);
return plainText == null ? null : Encoding.UTF8.GetString(plainText);
}
catch (Exception ex)
{
LogManager.Log(ex);
return null;
}
}
public static byte[] SimpleEncrypt(byte[] secretMessage, byte[] key, byte[] nonSecretPayload = null)
{
if (key == null || key.Length != Convert.ToInt32(ConfigurationManager.AppSettings["KeyBitSize"], 16) / (double)8)
throw new ArgumentException("Key needs to be {KeyBitSize} bit!", "key");
if (secretMessage == null || secretMessage.Length == 0)
throw new ArgumentException("Secret Message Required!", "secretMessage");
nonSecretPayload = nonSecretPayload ?? new byte[] { };
var nonce = new byte[System.Convert.ToInt32(Convert.ToInt32(ConfigurationManager.AppSettings["NonceBitSize"], 16) / (double)8 - 1) + 1];
System.Security.Cryptography.RNGCryptoServiceProvider ran = new System.Security.Cryptography.RNGCryptoServiceProvider();
ran.GetBytes(nonce);
BitConverter.ToInt32(nonce, 0);
var cipher = new GcmBlockCipher(new AesEngine());
var parameters = new AeadParameters(new KeyParameter(key), Convert.ToInt32(ConfigurationManager.AppSettings["MacBitSize"], 16), nonce, nonSecretPayload);
cipher.Init(true, parameters);
var cipherText = new byte[cipher.GetOutputSize(secretMessage.Length) - 1 + 1];
var len = cipher.ProcessBytes(secretMessage, 0, secretMessage.Length, cipherText, 0);
cipher.DoFinal(cipherText, len);
using (var combinedStream = new MemoryStream())
{
using (var binaryWriter = new BinaryWriter(combinedStream))
{
binaryWriter.Write(nonSecretPayload);
binaryWriter.Write(nonce);
binaryWriter.Write(cipherText);
}
return combinedStream.ToArray();
}
}
public static byte[] SimpleDecrypt(byte[] encryptedMessage, byte[] key, int nonSecretPayloadLength = 0)
{
if (key == null || key.Length != Convert.ToInt32(ConfigurationManager.AppSettings["KeyBitSize"], 16) / (double)8)
throw new ArgumentException("Key needs to be {KeyBitSize} bit!", "key");
if (encryptedMessage == null || encryptedMessage.Length == 0)
throw new ArgumentException("Encrypted Message Required!", "encryptedMessage");
using (var cipherStream = new MemoryStream(encryptedMessage))
{
using (var cipherReader = new BinaryReader(cipherStream))
{
var nonSecretPayload = cipherReader.ReadBytes(nonSecretPayloadLength);
var nonce = cipherReader.ReadBytes(System.Convert.ToInt32(Convert.ToInt32(ConfigurationManager.AppSettings["NonceBitSize"], 16) / (double)8));
var cipher = new GcmBlockCipher(new AesEngine());
var parameters = new AeadParameters(new KeyParameter(key), Convert.ToInt32(ConfigurationManager.AppSettings["MacBitSize"], 16), nonce, nonSecretPayload);
cipher.Init(false, parameters);
var cipherText = cipherReader.ReadBytes(encryptedMessage.Length - nonSecretPayloadLength - nonce.Length);
var plainText = new byte[cipher.GetOutputSize(cipherText.Length) - 1 + 1];
try
{
var len = cipher.ProcessBytes(cipherText, 0, cipherText.Length, plainText, 0);
cipher.DoFinal(plainText, len);
}
catch (InvalidCipherTextException unusedInvalidCipherTextException1)
{
return null;
}
return plainText;
}
}
}
public static byte[] SimpleEncryptWithPassword(byte[] secretMessage, string password, byte[] nonSecretPayload = null)
{
nonSecretPayload = nonSecretPayload ?? new byte[] { };
if (string.IsNullOrWhiteSpace(password))
throw new ArgumentException("Must have a password ", "password");
if (secretMessage == null || secretMessage.Length == 0)
throw new ArgumentException("Secret Message Required!", "secretMessage");
var generator = new Pkcs5S2ParametersGenerator();
var salt = new byte[System.Convert.ToInt32(Convert.ToInt32(ConfigurationManager.AppSettings["SaltBitSize"], 16) / (double)8 - 1) + 1];
System.Security.Cryptography.RNGCryptoServiceProvider ran = new System.Security.Cryptography.RNGCryptoServiceProvider();
ran.GetBytes(salt);
BitConverter.ToInt32(salt, 0);
generator.Init(PbeParametersGenerator.Pkcs5PasswordToBytes(password.ToCharArray()), salt, Convert.ToInt32(ConfigurationManager.AppSettings["Iterations"], 16));
var key = (KeyParameter)generator.GenerateDerivedMacParameters(Convert.ToInt32(ConfigurationManager.AppSettings["KeyBitSize"], 16));
var payload = new byte[salt.Length + nonSecretPayload.Length - 1 + 1];
Array.Copy(nonSecretPayload, payload, nonSecretPayload.Length);
Array.Copy(salt, 0, payload, nonSecretPayload.Length, salt.Length);
return SimpleEncrypt(secretMessage, key.GetKey(), payload);
}
public static byte[] SimpleDecryptWithPassword(byte[] encryptedMessage, string password, int nonSecretPayloadLength = 0)
{
try
{
if (string.IsNullOrWhiteSpace(password))
throw new ArgumentException("Must have a password of at least MinPasswordLength characters!");
if (encryptedMessage == null || encryptedMessage.Length == 0)
throw new ArgumentException("Encrypted Message Required!", "encryptedMessage");
var generator = new Pkcs5S2ParametersGenerator();
var salt = new byte[System.Convert.ToInt32(Convert.ToInt32(ConfigurationManager.AppSettings["SaltBitSize"], 16) / (double)8 - 1) + 1];
Array.Copy(encryptedMessage, nonSecretPayloadLength, salt, 0, salt.Length);
generator.Init(PbeParametersGenerator.Pkcs5PasswordToBytes(password.ToCharArray()), salt, Convert.ToInt32(ConfigurationManager.AppSettings["Iterations"], 16));
var key = (KeyParameter)generator.GenerateDerivedMacParameters(Convert.ToInt32(ConfigurationManager.AppSettings["KeyBitSize"], 16));
return SimpleDecrypt(encryptedMessage, key.GetKey(), salt.Length + nonSecretPayloadLength);
}
catch (Exception ex)
{
LogManager.Log(ex);
return null;
}
}
}
Write, Run & Share C# code online using OneCompiler's C# online compiler for free. It's one of the robust, feature-rich online compilers for C# language, running on the latest version 8.0. Getting started with the OneCompiler's C# compiler is simple and pretty fast. The editor shows sample boilerplate code when you choose language as C# and start coding.
OneCompiler's C# online compiler supports stdin and users can give inputs to programs using the STDIN textbox under the I/O tab. Following is a sample program which takes name as input and print your name with hello.
using System;
namespace Sample
{
class Test
{
public static void Main(string[] args)
{
string name;
name = Console.ReadLine();
Console.WriteLine("Hello {0} ", name);
}
}
}
C# is a general purpose object-oriented programming language by Microsoft. Though initially it was developed as part of .net but later it was approved by ECMA and ISO standards.
You can use C# to create variety of applications, like web, windows, mobile, console applications and much more using Visual studio.
| Data Type | Description | Range | size |
|---|---|---|---|
| int | To store integers | -2,147,483,648 to 2,147,483,647 | 4 bytes |
| double | to store large floating point numbers with decimals | can store 15 decimal digits | 8 bytes |
| float | to store floating point numbers with decimals | can store upto 7 decimal digits | 4 bytes |
| char | to store single characters | - | 2 bytes |
| string | to stores text | - | 2 bytes per character |
| bool | to stores either true or false | - | 1 bit |
datatype variable-name = value;
When ever you want to perform a set of operations based on a condition or set of few conditions IF-ELSE is used.
if(conditional-expression) {
// code
}
else {
// code
}
You can also use if-else for nested Ifs and If-Else-If ladder when multiple conditions are to be performed on a single variable.
Switch is an alternative to If-Else-If ladder.
switch(conditional-expression) {
case value1:
// code
break; // optional
case value2:
// code
break; // optional
...
default:
// code to be executed when all the above cases are not matched;
}
For loop is used to iterate a set of statements based on a condition.
for(Initialization; Condition; Increment/decrement) {
// code
}
While is also used to iterate a set of statements based on a condition. Usually while is preferred when number of iterations are not known in advance.
while(condition) {
// code
}
Do-while is also used to iterate a set of statements based on a condition. It is mostly used when you need to execute the statements atleast once.
do {
// code
} while (condition);
Array is a collection of similar data which is stored in continuous memory addresses. Array values can be fetched using index. Index starts from 0 to size-1.
data-type[] array-name;
Method is a set of statements which gets executed only when they are called. Call the method name in the main function to execute the method.
static void method-name()
{
// code to be executed
}