You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

247 lines
11 KiB

using System;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
namespace Common.Helper
{
public static class Crypto
{
private static string saltValue = "K0r3@GM3";
private static string hashAlgorithm = "SHA1";
private static int passwordIterations = 5;
private static string initVector = "P@s$w0rDGm3KoR3@";
private static int keySize = 256;
private static int keySize128 = 128;
/// <summary>
/// Encrypts specified plaintext using Rijndael symmetric key algorithm and returns a
/// base64-encoded result.
/// </summary>
/// <param name="plainText">Plain Text to Encrypt</param>
/// <param name="passPhrase">Pass Phrase to use in Password Generation</param>
/// <returns>Encrypted text encoded into Base 64 text format</returns>
public static string Encrypt(string plainText, string passPhrase)
{
// Convert strings into byte arrays. Let us assume that strings only contain ASCII
// codes. If strings include Unicode characters, use Unicode, UTF7, or UTF8 encoding.
byte[] initVectorBytes = Encoding.ASCII.GetBytes(initVector);
byte[] saltValueBytes = Encoding.ASCII.GetBytes(saltValue);
// Convert our plaintext into a byte array. Let us assume that plaintext contains
// UTF8-encoded characters.
byte[] plainTextBytes = Encoding.UTF8.GetBytes(plainText);
// First, we must create a password, from which the key will be derived. This password
// will be generated from the specified passphrase and salt value. The password will be
// created using the specified hash algorithm. Password creation can be done in several iterations.
var password = new PasswordDeriveBytes(
passPhrase,
saltValueBytes,
hashAlgorithm,
passwordIterations);
// Use the password to generate pseudo-random bytes for the encryption key. Specify the
// size of the key in bytes (instead of bits).
#pragma warning disable 618, 612
byte[] keyBytes = password.GetBytes(keySize / 8);
#pragma warning restore 618, 612
// Create uninitialized Rijndael encryption object.
var symmetricKey = new RijndaelManaged();
// It is reasonable to set encryption mode to Cipher Block Chaining (CBC). Use default
// options for other symmetric key parameters.
symmetricKey.Mode = CipherMode.CBC;
// Generate encryptor from the existing key bytes and initialization vector. Key size
// will be defined based on the number of the key bytes.
ICryptoTransform encryptor = symmetricKey.CreateEncryptor(
keyBytes,
initVectorBytes);
var memoryStream = new MemoryStream();
// Define memory stream which will be used to hold encrypted data.
var cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write);
// Start encrypting.
cryptoStream.Write(plainTextBytes, 0, plainTextBytes.Length);
// Finish encrypting.
cryptoStream.FlushFinalBlock();
// Convert our encrypted data from a memory stream into a byte array.
byte[] cipherTextBytes = memoryStream.ToArray();
// Close both streams.
memoryStream.Close();
cryptoStream.Close();
// Convert encrypted data into a base64-encoded string.
string cipherText = Convert.ToBase64String(cipherTextBytes);
// Return encrypted string.
return cipherText;
}
/// <summary>
/// Decrypts specified cipherText using Rijndael symmetric key algorithm and returns a plain
/// text result.
/// </summary>
/// <param name="cipherText">Encryted Text</param>
/// <param name="passPhrase">Pass Phrase used in Password Generation</param>
/// <returns></returns>
public static string Decrypt(string cipherText, string passPhrase)
{
// Convert strings defining encryption key characteristics into byte arrays. Let us
// assume that strings only contain ASCII codes. If strings include Unicode characters,
// use Unicode, UTF7, or UTF8 encoding.
byte[] initVectorBytes = Encoding.ASCII.GetBytes(initVector);
byte[] saltValueBytes = Encoding.ASCII.GetBytes(saltValue);
// Convert our ciphertext into a byte array.
byte[] cipherTextBytes = Convert.FromBase64String(cipherText);
// First, we must create a password, from which the key will be derived. This password
// will be generated from the specified passphrase and salt value. The password will be
// created using the specified hash algorithm. Password creation can be done in several iterations.
var password = new PasswordDeriveBytes(
passPhrase,
saltValueBytes,
hashAlgorithm,
passwordIterations);
// Use the password to generate pseudo-random bytes for the encryption key. Specify the
// size of the key in bytes (instead of bits).
#pragma warning disable 618, 612
byte[] keyBytes = password.GetBytes(keySize / 8);
#pragma warning restore 618, 612
// Create uninitialized Rijndael encryption object.
var symmetricKey = new RijndaelManaged();
// It is reasonable to set encryption mode to Cipher Block Chaining (CBC). Use default
// options for other symmetric key parameters.
symmetricKey.Mode = CipherMode.CBC;
// Generate decryptor from the existing key bytes and initialization vector. Key size
// will be defined based on the number of the key bytes.
ICryptoTransform decryptor = symmetricKey.CreateDecryptor(
keyBytes,
initVectorBytes);
// Define memory stream which will be used to hold encrypted data.
var memoryStream = new MemoryStream(cipherTextBytes);
// Define cryptographic stream (always use Read mode for encryption).
var cryptoStream = new CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read);
// Since at this point we don't know what the size of decrypted data will be, allocate
// the buffer long enough to hold ciphertext; plaintext is never longer than ciphertext.
var plainTextBytes = new byte[cipherTextBytes.Length];
// Start decrypting.
int decryptedByteCount = cryptoStream.Read(plainTextBytes, 0, plainTextBytes.Length);
// Close both streams.
memoryStream.Close();
cryptoStream.Close();
// Convert decrypted data into a string. Let us assume that the original plaintext
// string was UTF8-encoded.
string plainText = Encoding.UTF8.GetString(plainTextBytes, 0, decryptedByteCount);
// Return decrypted string.
return plainText;
}
public static string Encrypt128(string plainText, string key)
{
RijndaelManaged RijndaelCipher = new RijndaelManaged();
RijndaelCipher.Mode = CipherMode.ECB;
RijndaelCipher.Padding = PaddingMode.None;
RijndaelCipher.KeySize = keySize128;
int paddingLengh = 16 - plainText.Length % 16;
byte[] encrypByte = new byte[plainText.Length + paddingLengh];
byte[] plainByte = Encoding.UTF8.GetBytes(plainText);
for (int i = 0; i < encrypByte.Length; ++i)
{
if (i < plainByte.Length)
{
encrypByte[i] = plainByte[i];
}
else
{
encrypByte[i] = (byte)0x20;
}
}
byte[] keyByte = Encoding.UTF8.GetBytes(key);
ICryptoTransform Encryptor = RijndaelCipher.CreateEncryptor(keyByte, null);
MemoryStream memoryStream = new MemoryStream();
CryptoStream cryptoStream = new CryptoStream(memoryStream, Encryptor, CryptoStreamMode.Write);
cryptoStream.Write(encrypByte, 0, encrypByte.Length);
cryptoStream.FlushFinalBlock();
byte[] cipherBytes = memoryStream.ToArray();
memoryStream.Close();
cryptoStream.Close();
var encryptedData = BitConverter.ToString(cipherBytes).Replace("-", string.Empty);
return encryptedData;
}
//public static string Decrypt128(string cipherText, string key)
//{
// RijndaelManaged rijndaelManaged = new RijndaelManaged();
// // Convert our ciphertext into a byte array.
// byte[] cipherTextBytes = Convert.FromBase64String(cipherText);
// byte[] saltValueBytes = Encoding.ASCII.GetBytes(key);
// PasswordDeriveBytes SecretKey = new PasswordDeriveBytes(key, saltValueBytes);
// ICryptoTransform Decryptor = rijndaelManaged.CreateDecryptor(SecretKey.GetBytes(32), SecretKey.GetBytes(16));
// MemoryStream memoryStream = new MemoryStream(cipherTextBytes);
// CryptoStream cryptoStream = new CryptoStream(memoryStream, Decryptor, CryptoStreamMode.Read);
// byte[] plainText = new byte[cipherTextBytes.Length];
// int DecryptedCount = cryptoStream.Read(plainText, 0, plainText.Length);
// memoryStream.Close(); cryptoStream.Close();
// string DecryptedData = Encoding.Unicode.GetString(plainText, 0, DecryptedCount);
// return DecryptedData;
//}
/* @Max - 2018.10.25
* 지정한 개수만큼의 랜덤스트링을 만들어 리턴하는 함수
* */
public static string GetRandomString(int _totLen)
{
Random rand = new Random();
string input = "abcdefghijklmnopqrstuvwxyz0123456789";
var chars = Enumerable.Range(0, _totLen).Select(x => input[rand.Next(0, input.Length)]);
return new string(chars.ToArray());
}
/* @Max - 2018.11.07
* 지정한 개수만큼의 랜덤숫자를 만들어 리턴하는 함수
* */
public static string GetRandomNumber(int _totLen)
{
Random rand = new Random();
string input = "0123456789";
var chars = Enumerable.Range(0, _totLen).Select(x => input[rand.Next(0, input.Length)]);
return new string(chars.ToArray());
}
}
}