public static string TextToCrypto(string text, CryptoType cryptoType) { byte[] bytes; HashAlgorithm hash = null; switch (cryptoType) { case CryptoType.MD5: hash = new MD5CryptoServiceProvider(); break; case CryptoType.SHA1: hash = new SHA1CryptoServiceProvider(); break; } bytes = hash.ComputeHash(Encoding.UTF8.GetBytes(text)); hash.Clear(); StringBuilder sb = new StringBuilder(); foreach (byte b in bytes) { sb.Append(b.ToString("x2")); } return(sb.ToString()); }
/// <summary> /// Creates encryptor or decryptor from key and IV. /// </summary> /// <returns>The crypto.</returns> /// <param name="keyBytes">Key bytes.</param> /// <param name="iv">IV</param> /// <param name="cryptoType">Crypto type.</param> public static ICryptoTransform CreateCrypto(byte[] keyBytes, byte[] iv, CryptoType cryptoType) { if (keyBytes.Length * 8 != 256) { throw new Exception("Invalid key size."); } RijndaelManaged symmetricKey = new RijndaelManaged(); symmetricKey.Mode = CipherMode.CBC; symmetricKey.KeySize = 256; // default padding: PKCS7 ICryptoTransform cryptor; switch (cryptoType) { case CryptoType.Encryptor: cryptor = symmetricKey.CreateEncryptor(keyBytes, iv); break; case CryptoType.Decryptor: cryptor = symmetricKey.CreateDecryptor(keyBytes, iv); break; default: cryptor = null; break; } return(cryptor); }
private void SwitchCryptoLIBType(CryptoType type) { if (type == CryptoType.DNA) { if (cryptoLIB == null) { cryptoLIB = new DNACryptoLIB.DNACrypto(); } else if (cryptoLIB.GetType() == typeof(DNACryptoLIB.DNACrypto)) { return; } else { cryptoLIB = new DNACryptoLIB.DNACrypto(); } } else { if (cryptoLIB == null) { cryptoLIB = new DNACryptoLIB.RNACrypto(); } else if (cryptoLIB.GetType() == typeof(DNACryptoLIB.RNACrypto)) { return; } else { cryptoLIB = new DNACryptoLIB.RNACrypto(); } } }
public static byte[] WriteCryptoStream(this byte[] data, byte[] key, CryptoType cryptoType, ref byte[] iv) { using (var aes = new RijndaelManaged()) { aes.Key = key; if (iv != null) aes.IV = iv; else iv = aes.IV; ICryptoTransform crypto; if (cryptoType == CryptoType.Decrypt) crypto = aes.CreateDecryptor(); else crypto = aes.CreateEncryptor(); using (var ms = new MemoryStream()) { using (CryptoStream csCrypt = new CryptoStream(ms, crypto, CryptoStreamMode.Write)) { csCrypt.Write(data, 0, data.Length); csCrypt.FlushFinalBlock(); return ms.ToArray(); } } } }
/// <summary> /// Sets the member service provider object to a specific type of cryptography algorithm /// </summary> /// <param name="type"></param> private void SetServiceProvider(CryptoType type) { try { switch (type) { case CryptoType.DES: mCSP = new DESCryptoServiceProvider(); break; case CryptoType.RC2: mCSP = new RC2CryptoServiceProvider(); break; case CryptoType.Rijndael: mCSP = new RijndaelManaged(); break; case CryptoType.TripleDES: mCSP = new TripleDESCryptoServiceProvider(); break; default: break; } } catch (Exception ex) { throw (new Exception(ex.Message + " -- SetServiceProvider ")); } }
public static byte[] WriteCryptoStream(this byte[] data, byte[] key, CryptoType cryptoType) { byte[] iv = null; if (cryptoType == CryptoType.Decrypt) iv = ReadIV(data); return WriteCryptoStream(data, key, cryptoType, ref iv); }
// Constructor public CryptoManager(CryptoType type, string key, string iv) { // Set the Cryptography Service Provider object SetServiceProvider(type); // Set properties Key = key; IV = iv; }
public async Task <CoinMarketCapData> GetCoinMarketCapData(CryptoType cryptoType) { if (!_coinMarketcapCrypoLookupNames.ContainsKey(cryptoType)) { return(null); } var coinMarketCapData = this._cache.Get(cryptoType.ToString()) as CoinMarketCapData; if (coinMarketCapData == null) { var url = new UriBuilder("https://api.coingecko.com/api/v3/simple/price"); var queryString = HttpUtility.ParseQueryString(string.Empty); queryString["ids"] = _coinMarketcapCrypoLookupNames[cryptoType]; queryString["vs_currencies"] = "USD"; queryString["include_market_cap"] = "true"; queryString["include_24hr_change"] = "true"; url.Query = queryString.ToString(); var client = new HttpClient { BaseAddress = url.Uri }; try { HttpResponseMessage response = await client.GetAsync(""); var content = await response.Content.ReadAsStringAsync(); if (response.IsSuccessStatusCode) { var data = Newtonsoft.Json.Linq.JObject.Parse(content).First?.First; if (data != null) { coinMarketCapData = new CoinMarketCapData { Crypto = cryptoType, PriceInUsd = data.Value <decimal>("usd"), TwentyFourHourChangePercent = data.Value <decimal>("usd_24h_change") / (decimal)100.0, MarketCap = data.Value <decimal>("usd_market_cap"), }; } this._cache.Set(new CacheItem(cryptoType.ToString(), coinMarketCapData), this._defaultCacheItemPolicyFactory()); } } catch { /* swallow exception */ } } return(coinMarketCapData); }
public void TestFunctions() { CryptoType <bool> value = false.crypto(); Assert.AreEqual(value.value(), false); Assert.AreEqual(value.value(), false.crypto().value()); value = true.crypto(); Assert.AreEqual(value.value(), true); Assert.AreEqual(value.value(), true.crypto().value()); }
/// <summary> /// Decrypt a byte array /// </summary> /// <param name="cType">Type of encryption</param> /// <param name="key">Key aka password</param> /// <param name="input">Data to encrypt</param> /// <returns>Decrypted data</returns> public static byte[] Decrypt(CryptoType cType, string key, byte[] input) { PasswordDeriveBytes pdb = new PasswordDeriveBytes(key, SALT); SymmetricAlgorithm algo = selectAlgorithm(cType); algo.Key = pdb.GetBytes(algo.KeySize / 8); algo.IV = pdb.GetBytes(algo.BlockSize / 8); return DoCrypt(algo.CreateDecryptor(), input); }
public override int GetHashCode() { unchecked { var hashCode = (AssetId != null ? AssetId.GetHashCode() : 0); hashCode = (hashCode * 397) ^ (OriginalSymbol != null ? OriginalSymbol.GetHashCode() : 0); hashCode = (hashCode * 397) ^ (Name != null ? Name.GetHashCode() : 0); hashCode = (hashCode * 397) ^ CryptoType.GetHashCode(); hashCode = (hashCode * 397) ^ (Id != null ? Id.GetHashCode() : 0); return(hashCode); } }
public static byte[] WriteCryptoStream(this byte[] data, byte[] key, CryptoType cryptoType) { using (var aes = new RijndaelManaged()) { aes.Key = key; aes.IV = new byte[16]; if (cryptoType == CryptoType.Encrypt) { aes.IV = RNGExtensions.GetRandomBytes(16); } else { aes.IV = ReadIV(data); } ICryptoTransform crypto; if (cryptoType == CryptoType.Decrypt) { crypto = aes.CreateDecryptor(aes.Key, aes.IV); } else { crypto = aes.CreateEncryptor(aes.Key, aes.IV); } using (var ms = new MemoryStream()) { if (cryptoType == CryptoType.Encrypt) { ms.Write(aes.IV, 0, aes.IV.Length); } using (CryptoStream csCrypt = new CryptoStream(ms, crypto, CryptoStreamMode.Write)) { if (cryptoType == CryptoType.Encrypt) { csCrypt.Write(data, 0, data.Length); } else { csCrypt.Write(data, 16, data.Length - 16); } csCrypt.FlushFinalBlock(); ms.Position = 0; var b = new byte[ms.Length]; ms.Read(b, 0, b.Length); return(b); } } } }
public static string ToStr(this CryptoType cryptoType) { switch (cryptoType) { case CryptoType.All: return("all"); case CryptoType.Coins: return("coins"); case CryptoType.Tokens: return("tokens"); default: return("all"); } }
/// <summary> /// 解密 /// </summary> /// <param name="ciphertext"></param> /// <param name="cryptoType"></param> /// <returns></returns> public static string Decode(string ciphertext, CryptoType cryptoType) { if (ciphertext == null || ciphertext == "") { return(""); } if (cryptoType == CryptoType.Base64) { return(DecodeByBase64(ciphertext)); } throw new Exception(cryptoType.ToString() + " 类型无法解密"); }
/// <summary> /// Recreates the specified current. /// </summary> /// <param name="current">The current.</param> /// <param name="cryptoType">Type of the crypto.</param> /// <param name="privateKeyPath">The private key path.</param> /// <param name="privateKeyPassword">The private key password.</param> /// <param name="publicKeyPath">The public key path.</param> /// <returns>Implementation of crypto helper.</returns> public static ICryptoHelper Recreate(ref ICryptoHelper current, CryptoType cryptoType, string privateKeyPath, string privateKeyPassword, string publicKeyPath) { if ((current == null) || (current.Type != cryptoType)) { current = CreateRSA(cryptoType, privateKeyPath, privateKeyPassword, publicKeyPath); } return(current); }
/// <summary> /// Recreates the specified current. /// </summary> /// <param name="current">The current.</param> /// <param name="cryptoType">Type of the crypto.</param> /// <param name="privateKeyPath">The private key path.</param> /// <param name="privateKeyPassword">The private key password.</param> /// <param name="publicKeyPath">The public key path.</param> /// <returns>Implementation of crypto helper.</returns> public static ICryptoHelper Recreate(ref ICryptoHelper current, CryptoType cryptoType, string privateKeyPath, string privateKeyPassword, string publicKeyPath) { if ((current == null) || (current.Type != cryptoType)) { current = CreateRSA(cryptoType, privateKeyPath, privateKeyPassword, publicKeyPath); } return current; }
public async Task <CryptoInfo> GetCryptoInfo(CryptoType cryptoType) { using (HttpClient client = new HttpClient()) { HttpResponseMessage response = await client.GetAsync("https://api.cryptonator.com/api/ticker/" + GetUriSuffix(cryptoType) + "-usd"); string jsonResponse = await response.Content.ReadAsStringAsync(); CryptoInfo cryptoInfo = JsonConvert.DeserializeObject <CryptoInfo>(jsonResponse); cryptoInfo.Type = cryptoType; client.Dispose(); return(cryptoInfo); } }
//''' AES - Key must be 32 characters (256 bytes) and IV must be 16 characters (128 bytes) //''' DES - Key must be 8 characters (64 bytes) and IV must be 8 characters (64 bytes) //''' RC2 - Key must be 16 characters (128 bytes) and IV must be 8 characters (64 bytes) //''' Rijndael - Key must be 32 characters (256 bytes) and IV must be 16 characters (128 bytes) //''' Triple DES - Key must be 24 characters (192 bytes) and IV must be 8 characters (64 bytes) public static string Encrypt(CryptoType cryptoMethod, string txt) { string retVal = String.Empty; try { //CryptoCollection cc = CryptoCollection.GetCryptoCollectionInfoByMethod(cryptoMethod); //retVal = Encrypt(cryptoMethod, txt, cc); } catch { } return(retVal); }
public string GetTradedPairName(CryptoType Ctype, FiatType Ftype, XBTPossiblePairs Xtype, ETHPossiblePairs Etype) { if (Etype.ToString() != "-1") { return(!Etype.ToString().Equals("ZUSD") ? Etype.ToString() + Ctype.ToString() : Ctype.ToString() + Etype.ToString()); } else if (Xtype.ToString() != "-1" && !Xtype.ToString().Equals("BCH")) { return(!Xtype.ToString().Equals("ZUSD") ? Xtype.ToString() + Ctype.ToString() : Ctype.ToString() + Xtype.ToString()); } else { return("BCHXBT"); } }
public static byte[] WriteCryptoStream(this byte[] data, byte[] key, CryptoType cryptoType) { using (var aes = new RijndaelManaged()) { aes.Key = key; aes.IV = new byte[16]; if (cryptoType == CryptoType.Encrypt) aes.IV = RNGExtensions.GetRandomBytes(16); else { aes.IV = ReadIV(data); } ICryptoTransform crypto; if (cryptoType == CryptoType.Decrypt) crypto = aes.CreateDecryptor(aes.Key, aes.IV); else crypto = aes.CreateEncryptor(aes.Key, aes.IV); using (var ms = new MemoryStream()) { if (cryptoType == CryptoType.Encrypt) ms.Write(aes.IV, 0, aes.IV.Length); using (CryptoStream csCrypt = new CryptoStream(ms, crypto, CryptoStreamMode.Write)) { if (cryptoType == CryptoType.Encrypt) { csCrypt.Write(data, 0, data.Length); } else { csCrypt.Write(data, 16, data.Length - 16); } csCrypt.FlushFinalBlock(); ms.Position = 0; var b = new byte[ms.Length]; ms.Read(b, 0, b.Length); return b; } } } }
/// <summary> /// Creates the RSA. /// </summary> /// <param name="privateKeyPath">The private key path.</param> /// <param name="privateKeyPassword">The private key password.</param> /// <param name="publicKeyPath">The public key path.</param> /// <returns>Implementation of crypto helper.</returns> public static ICryptoHelper CreateRSA(CryptoType cryptoType, string privateKeyPath, string privateKeyPassword, string publicKeyPath) { if (cryptoType == CryptoType.RSA) { return(new RSAEncryption(privateKeyPath, privateKeyPassword, publicKeyPath)); } else if (cryptoType == CryptoType.RSATripleDES) { return(new RSATripleDESEncryption(privateKeyPath, privateKeyPassword, publicKeyPath)); } else { return(Create(cryptoType)); } }
/// <summary> /// Decrypt a text string /// </summary> /// <param name="cType">Type of encryption</param> /// <param name="key">Key aka password</param> /// <param name="inputText">Text to decrypt</param> /// <returns>Decrypted text</returns> public static string Decrypt(CryptoType cType, string key, string inputText) { //declare a new encoder UTF8Encoding UTF8Encoder = new UTF8Encoding(); //get byte representation of string byte[] inputBytes; try { inputBytes = Convert.FromBase64String(inputText); } catch(FormatException) { throw new ArgumentException("Input text is not Base64", "inputText"); } //convert back to a string return UTF8Encoder.GetString(Decrypt(cType, key, inputBytes)); }
/// <summary> /// Creates the RSA. /// </summary> /// <param name="privateKeyPath">The private key path.</param> /// <param name="privateKeyPassword">The private key password.</param> /// <param name="publicKeyPath">The public key path.</param> /// <returns>Implementation of crypto helper.</returns> public static ICryptoHelper CreateRSA(CryptoType cryptoType, string privateKeyPath, string privateKeyPassword, string publicKeyPath) { if (cryptoType == CryptoType.RSA) { return new RSAEncryption(privateKeyPath, privateKeyPassword, publicKeyPath); } else if (cryptoType == CryptoType.RSATripleDES) { return new RSATripleDESEncryption(privateKeyPath, privateKeyPassword, publicKeyPath); } else { return Create(cryptoType); } }
public Crypter(CryptoType cryptoType, FileInfo inputFile, FileInfo outputFile) { switch (cryptoType) { case CryptoType.AES: myAlgorithm = Aes.Create(); break; case CryptoType.DES: myAlgorithm = DES.Create(); break; case CryptoType.RC2: myAlgorithm = RC2.Create(); break; } this.inputFile = inputFile; this.outputFile = outputFile; }
public PotentialTradeModel PopulateTM(CryptoType Ctype, FiatType Ftype, TimeLine Tl, XBTPossiblePairs Xtype, ETHPossiblePairs Etype) { var symbol = GetTradedPairName(Ctype, Ftype, Xtype, Etype); PotentialTradeModel x = new PotentialTradeModel { TimeLoaded = timestamp, Fiate = Ftype, FiateBalance = _KrakenUtils.GetFiateBalance(FiatType.ZUSD), TradePairName = symbol, CryptoCurrentPrice = _KrakenUtils.GetTradedPairPrice(symbol), VWAPCurrentAveragePrice = _KrakenUtils.GetCurrentVWAPAverage(symbol), VWAPCurrent24HRolling = _KrakenUtils.GetCurrentVWAP24Hrolling(symbol), VWAPCurrentDaily = _KrakenUtils.GetCurrentVWAPAverageValueToday(symbol), Trigger = false }; return(x); }
private string Crypt(byte[] key, byte[] data, CryptoType cryptoType, CancellationToken token) { using (var aes = new AesManaged()) { aes.BlockSize = _blockSize * 8; aes.KeySize = Defaults.KEYSIZE * 8; ICryptoTransform cryptor = null; if (cryptoType == CryptoType.Encrypt) { cryptor = aes.CreateEncryptor(key, Defaults.AESIV); } else { cryptor = aes.CreateDecryptor(key, Defaults.AESIV); } using (cryptor) { using (var memoStream = new MemoryStream()) { using (var cryptoStream = new CryptoStream(memoStream, cryptor, CryptoStreamMode.Write)) { if (token != default(CancellationToken)) { token.ThrowIfCancellationRequested(); } cryptoStream.Write(data, 0, data.Length); cryptoStream.FlushFinalBlock(); if (cryptoType == CryptoType.Encrypt) { return(memoStream.ToArray().AsBase64String()); } else { return(memoStream.ToArray().AsString()); } } } } } }
/// <summary> /// 加密 /// </summary> /// <param name="plaintext">明文</param> /// <param name="cryptoType">加密类型</param> /// <returns>密文</returns> public static string Encrypt(string plaintext, CryptoType cryptoType) { if (plaintext == null || plaintext == "") { return(""); } if (cryptoType == CryptoType.Base64) { return(EncryptByBase64(plaintext)); } Byte[] plaintextBytes = Encoding.ASCII.GetBytes(plaintext); Byte[] hashedBytes = ((HashAlgorithm)CryptoConfig.CreateFromName(cryptoType.ToString())).ComputeHash(plaintextBytes); StringBuilder ciphertext = new StringBuilder(); for (int i = 0; i < hashedBytes.Length; i++) { ciphertext.Append(hashedBytes[i].ToString("X2")); } return(ciphertext.ToString()); }
public string AES_Crypto(CryptoType type, string key, string input) { // Check arguments. if (string.IsNullOrEmpty(input)) { throw new ArgumentNullException("input"); } if (string.IsNullOrEmpty(key)) { throw new ArgumentNullException("key"); } using (AesCryptoServiceProvider aesObj = new AesCryptoServiceProvider()) { ICryptoTransform transformer; byte[] bytes_input; byte[] bytes_output; string output; aesObj.Key = getKey(key); aesObj.IV = getSalt(key); if (type == CryptoType.Encrypt) { transformer = aesObj.CreateEncryptor(); bytes_input = Encoding.UTF8.GetBytes(input); bytes_output = transformer.TransformFinalBlock(bytes_input, 0, bytes_input.Length); output = Convert.ToBase64String(bytes_output); } else { transformer = aesObj.CreateDecryptor(); bytes_input = Convert.FromBase64String(input); bytes_output = transformer.TransformFinalBlock(bytes_input, 0, bytes_input.Length); output = Encoding.UTF8.GetString(bytes_output); } return(output); } }
private static string _processData(string data, string key, CryptoType cType, string iv = "") { if (string.IsNullOrEmpty(iv)) { iv = key; } byte[] keyArray = UTF8Encoding.UTF8.GetBytes(key); byte[] ivArray = UTF8Encoding.UTF8.GetBytes(iv); byte[] toProcessArrary = cType == CryptoType.Encrypt ? UTF8Encoding.UTF8.GetBytes(data) : Convert.FromBase64String(data); ICryptoTransform cTransform; switch (cType) { case CryptoType.Encrypt: cTransform = _createRijndaelManaged(keyArray, ivArray).CreateEncryptor(); break; case CryptoType.Decrypt: cTransform = _createRijndaelManaged(keyArray, ivArray).CreateDecryptor(); break; default: throw new Exception("没有找到匹配的CryptoType类型。"); } byte[] resultArray = cTransform.TransformFinalBlock(toProcessArrary, 0, toProcessArrary.Length); //返回不同结果 if (cType == CryptoType.Encrypt) { return(Convert.ToBase64String(resultArray, 0, resultArray.Length)); } else { return(UTF8Encoding.UTF8.GetString(resultArray).Replace("\0", "")); } }
private string GetUriSuffix(CryptoType cryptoType) { switch (cryptoType) { case CryptoType.BTC: return("BTC"); case CryptoType.ETH: return("ETH"); case CryptoType.BNB: return("BNB"); case CryptoType.USDT: return("USDT"); case CryptoType.ADA: return("ADA"); case CryptoType.DOT: return("DOT"); case CryptoType.XRP: return("XRP"); case CryptoType.UNI: return("UNI"); case CryptoType.LTC: return("LTC"); case CryptoType.LINK: return("LINK"); default: return("BTC"); } }
public static IConnectionCrypto CreateCrypto(CryptoType type, bool active) { switch (type) { case CryptoType.NoCrypto: return(new NoCrypto()); case CryptoType.RSA: return(new RSACrypto(active)); case CryptoType.RSALegacy: return(new RSALegacyCrypto(active)); case CryptoType.EC: return(new ECCrypto(active)); case CryptoType.EC25519: return(new EC25519Crypto(active)); default: throw new NotImplementedException(); } }
public static ICrypto GetCrypto(CryptoType algorithm) { switch (algorithm) { case CryptoType.Aes: return(new Sym_Aes()); case CryptoType.DES: return(new Sym_DES()); case CryptoType.RC2: return(new Sym_RC2()); case CryptoType.Rijndael: return(new Sym_Rijndael()); case CryptoType.TripleDES: return(new Sym_TripleDES()); case CryptoType.RSA: return(new Asym_RSA()); case CryptoType.MD5: return(new Hash_MD5()); case CryptoType.SHA1: return(new Hash_SHA1()); case CryptoType.SHA256: return(new Hash_SHA256()); case CryptoType.SHA512: return(new Hash_SHA512()); } return(null); }
private static IntPtr GRFProcess(IntPtrEx dst, IntPtrEx src, int len, byte flags, int digitsGen, byte[] ks, CryptoType dir) { int digits, i; if ((flags & GRFFILE_FLAG_MIXCRYPT) == GRFFILE_FLAG_MIXCRYPT) { for (i = digitsGen, digits = 0; i > 0; i /= 0xA, digits++) ; if (digits < 1) digits = 1; GRFMixedProcess(dst, src, len, (byte)digits, ks, dir); } else if ((flags & GRFFILE_FLAG_0x14_DES) == GRFFILE_FLAG_0x14_DES) { i = len / 8; if (i > 0x14) { i = 0x14; MemCpy(src + 0x14 * 8, dst + 0x14 * 8, len - 0x14 * 8); } DESProcess(dst, src, i * 8, ks, dir); } else { MemCpy(src, dst, len); } return dst; }
private static IntPtr GRFMixedProcess(IntPtrEx dst, IntPtrEx src, int len, byte cycle, byte[] ks, CryptoType dir) { IntPtr orig = dst; byte j = 0, tmp; if (cycle < 3) cycle = 1; else if (cycle < 5) cycle++; else if (cycle < 7) cycle += 9; else cycle += 0xF; for (int i = 0; i < len / 8; i++, dst += 8, src += 8) { if (i < 0x14 || i % cycle == 0) { DESProcessBlock(1, dst, src, ks, dir); } else { if (j == 7) { if (dir == CryptoType.Decrypt) { // 3450162 MemCpy(src + 3, dst, 2); // 01_____ dst[2] = src[6]; // 012____ MemCpy(src, dst + 3, 3); // 012345_ dst[6] = src[5]; } else { // 0123456 MemCpy(src, dst + 3, 2); // ___01__ dst[6] = src[2]; // ___01_2 MemCpy(src + 3, dst, 3); // 34501_2 dst[5] = src[6]; // 3450162 } // Modify byte 7 if ((tmp = src[7]) <= 0x77) { if (tmp == 0x77) // 0x77 dst[7] = 0x48; else if (tmp == 0) // 0x00 dst[7] = 0x2B; else if ((--tmp) == 0) // 0x01 dst[7] = 0x68; else if ((tmp -= 0x2A) == 0) // 0x2B dst[7] = 0x00; else if ((tmp -= 0x1D) == 0) // 0x48 dst[7] = 0x77; else if ((tmp -= 0x18) == 0) // 0x60 dst[7] = 0xFF; else if ((tmp -= 0x08) == 0) // 0x68 dst[7] = 0x01; else if ((tmp -= 0x04) == 0) // 0x6C dst[7] = 0x80; else dst[7] = src[7]; } else { if ((tmp -= 0x80) == 0) // 0x80 dst[7] = 0x6C; else if ((tmp -= 0x39) == 0) // 0xB9 dst[7] = 0xC0; else if ((tmp -= 0x07) == 0) // 0xC0 dst[7] = 0xB9; else if ((tmp -= 0x2B) == 0) // 0xEB dst[7] = 0xFE; else if ((tmp -= 0x13) == 0) // 0xFE dst[7] = 0xEB; else if ((--tmp) == 0) // 0xFF dst[7] = 0x60; else dst[7] = src[7]; } j = 0; } else { MemCpy(src, dst, 8); } j++; } } return orig; }
private static IntPtr DESProcessBlock(byte rounds, IntPtrEx dst, IntPtrEx src, byte[] ks, CryptoType dir) { byte[] tmp = new byte[4]; MemCpy(src, dst, 8); DESPermutation(dst, DES_IP); if (rounds > 0) { for (int i = 0; i < rounds; i++) { //DES_RawProcessBlock(dst, ks + (dir == CryptoType.Decrypt ? 0xF - i : i) * 8); DESRawProcessBlock(dst, ks); MemCpy(dst, tmp, 4); MemCpy(dst + 4, dst, 4); MemCpy(tmp, dst + 4, 4); } } MemCpy(dst, tmp, 4); MemCpy(dst + 4, dst, 4); MemCpy(tmp, dst + 4, 4); DESPermutation(dst, DES_IP_INV); return dst; }
private static IntPtr DESProcess(IntPtrEx dst, IntPtrEx src, int len, byte[] ks, CryptoType dir) { IntPtr orig = dst; for (int i = 0; i < len / 8; i++, dst += 8, src += 8) DESProcessBlock(1, dst, src, ks, dir); return orig; }
public CryptoInfo(CryptoType type, Ticker ticker) { this.Type = type; this.Ticker = ticker; }
public void TestCreate() { CryptoType <bool> value = false.crypto(); Assert.AreEqual(value.value(), false); }
/// <summary> /// Creates the specified crypto type. /// </summary> /// <param name="cryptoType">Type of the crypto.</param> /// <returns>Implementation of crypto helper.</returns> public static ICryptoHelper Create(CryptoType cryptoType) { return new CryptoHelperImpl(cryptoType); }
//private BGSEncryption _bgsEncryption = null; /// <summary> /// Initializes a new instance of the <see cref="CryptoHelperImpl"/> class. /// </summary> /// <param name="cryptoType">Type of the crypto.</param> internal CryptoHelperImpl(CryptoType cryptoType) { _cryptoType = cryptoType; //if (cryptoType == CryptoType.BGSWithHex) _bgsEncryption = new BGSEncryption(true); //else if (cryptoType == CryptoType.BSGWithoutHex) _bgsEncryption = new BGSEncryption(false); }
/// <summary> /// 创建加解密服务 /// </summary> /// <param name="source"></param> /// <param name="key"></param> /// <param name="iCrypto"></param> /// <returns></returns> private static byte[] CreateICrypto(byte[] source, string key, CryptoType iCrypto) { if (source.IsInvalid()) { throw (new Exception("加解密数据源不可以为空!")); } if (string.IsNullOrEmpty(key)) { throw (new Exception("密钥不可以为空")); } byte[] strSource; var aesProvider = Rijndael.Create(); try { var mStream = new MemoryStream(); var pdb = new PasswordDeriveBytes(key, Convert.FromBase64String(AESSALT)); ICryptoTransform transform = null; if (iCrypto == CryptoType.Encrypt) { transform = aesProvider.CreateEncryptor(pdb.GetBytes(32), Convert.FromBase64String(AESRGBIV)); } if (iCrypto == CryptoType.Decrypt) { transform = aesProvider.CreateDecryptor(pdb.GetBytes(32), Convert.FromBase64String(AESRGBIV)); } var mCsstream = new CryptoStream(mStream, transform, CryptoStreamMode.Write); mCsstream.Write(source, 0, source.Length); mCsstream.FlushFinalBlock(); strSource = mStream.ToArray(); mStream.Close(); mStream.Dispose(); mCsstream.Close(); mCsstream.Dispose(); } catch (IOException ex) { throw ex; } catch (CryptographicException ex) { throw ex; } catch (ArgumentException ex) { throw ex; } catch (Exception ex) { throw ex; } finally { aesProvider.Clear(); } return(strSource); }
// Constructor public CryptoManager(CryptoType type) { // Set the Cryptography Service Provider object SetServiceProvider(type); }
/// <summary> /// Encrypt a text string /// </summary> /// <param name="cType">Type of encryption</param> /// <param name="key">Key aka password</param> /// <param name="inputText">Text to encrypt</param> /// <returns>Encrypted text</returns> public static string Encrypt(CryptoType cType, string key, string inputText) { //declare a new encoder UTF8Encoding UTF8Encoder = new UTF8Encoding(); //get byte representation of string byte[] inputBytes = UTF8Encoder.GetBytes(inputText); //convert back to a string return Convert.ToBase64String(Encrypt(cType, key, inputBytes)); }
public static string TextToCrypto(string text, CryptoType cryptoType) { byte[] bytes; HashAlgorithm hash = null; switch (cryptoType) { case CryptoType.MD5: hash = new MD5CryptoServiceProvider(); break; case CryptoType.SHA1: hash = new SHA1CryptoServiceProvider(); break; } bytes = hash.ComputeHash(Encoding.UTF8.GetBytes(text)); hash.Clear(); StringBuilder sb = new StringBuilder(); foreach (byte b in bytes) { sb.Append(b.ToString("x2")); } return sb.ToString(); }
public static string Encrypt(CryptoType cryptoMethod, string txt, string cryptoKey, string cryptoIV) { string retValue = String.Empty; try { byte[] key = Encoding.UTF8.GetBytes(cryptoKey); byte[] iv = Encoding.UTF8.GetBytes(cryptoIV); ICryptoTransform cTransform = null; switch (cryptoMethod) { case CryptoType.aes: using (Aes aes = Aes.Create()) { if ((checkSize(aes.Key.Length, key.Length).Equals(true)) & (checkSize(aes.IV.Length, iv.Length).Equals(true))) { cTransform = aes.CreateEncryptor(key, iv); } } break; case CryptoType.des: using (DESCryptoServiceProvider des = new DESCryptoServiceProvider()) { if ((checkSize(des.Key.Length, key.Length).Equals(true)) & (checkSize(des.IV.Length, iv.Length).Equals(true))) { cTransform = des.CreateEncryptor(key, iv); } } break; case CryptoType.rc2: using (RC2 rc2 = RC2.Create()) { if ((checkSize(rc2.Key.Length, key.Length).Equals(true)) & (checkSize(rc2.IV.Length, iv.Length).Equals(true))) { cTransform = rc2.CreateEncryptor(key, iv); } } break; case CryptoType.rijndael: using (Rijndael rij = Rijndael.Create()) { if ((checkSize(rij.Key.Length, key.Length).Equals(true)) & (checkSize(rij.IV.Length, iv.Length).Equals(true))) { cTransform = rij.CreateEncryptor(key, iv); } } break; case CryptoType.tripledes: using (TripleDESCryptoServiceProvider triDES = new TripleDESCryptoServiceProvider()) { if ((checkSize(triDES.Key.Length, key.Length).Equals(true)) & (checkSize(triDES.IV.Length, iv.Length).Equals(true))) { cTransform = triDES.CreateEncryptor(key, iv); } } break; } if (cTransform != null) { using (MemoryStream ms = new MemoryStream()) { using (CryptoStream cs = new CryptoStream(ms, cTransform, CryptoStreamMode.Write)) { using (StreamWriter sw = new StreamWriter(cs)) { sw.Write(txt); } retValue = Convert.ToBase64String(ms.ToArray()); } } cTransform.Dispose(); } else { throw new CryptographicException(); } } catch (CryptographicException cex) { throw new ApplicationException("Cryptographic Encryption Exception", cex); } catch (Exception ex) { throw new ApplicationException("Encrypt Exception", ex); } return(retValue); }
/// <summary> /// returns the specific symmetric algorithm acc. to the cryptotype /// </summary> /// <returns>SymmetricAlgorithm</returns> private static SymmetricAlgorithm selectAlgorithm(CryptoType cType) { switch (cType) { /* case CryptoTypes.encTypeDES: SA = DES.Create(); break; case CryptoTypes.encTypeRC2: SA = RC2.Create(); break; */ case CryptoType.Rijndael: return Rijndael.Create(); case CryptoType.TripleDES: return TripleDES.Create(); // Default is Rijndael default: return Rijndael.Create(); } }