/// <summary> /// 对称算法基类 /// </summary> /// <param name="eEncryptType">加密类型</param> /// <param name="iKeySize">Key大小</param> /// <param name="iBlockSize">Block大小</param> /// <returns>对称算法基类</returns> public static SymmetricAlgorithm CreateSymmetricAlgoritm(EncryptType eEncryptType, int iKeySize, int iBlockSize) { SymmetricAlgorithm pResult = null; #region 生成 Key 、IV 值 switch (eEncryptType) { #region 分组密码标准算法 case EncryptType.RIJNDAEL: pResult = new RijndaelManaged(); break; #endregion #region 重数据加密标准算法 case EncryptType.TRIPLEDES: pResult = new TripleDESCryptoServiceProvider(); break; #endregion } if (pResult != null) { //pResult.KeySize = iKeySize; //pResult.BlockSize = iBlockSize; //pResult.Mode = CipherMode.CBC; //pResult.Padding = PaddingMode.ISO10126; } #endregion return(pResult); }
public string result(EncryptType type, string input) { var des = new DESCryptoServiceProvider() { Key = Key, IV = Key }; // 코드 분석 필요합니다. var ms = new MemoryStream(); var property = new { transform = type.Equals(EncryptType.Encrypt) ? des.CreateEncryptor() : des.CreateDecryptor(), data = type.Equals(EncryptType.Encrypt) ? Encoding.UTF8.GetBytes(input.ToCharArray()) : Convert.FromBase64String(input) }; var cryStream = new CryptoStream(ms, property.transform, CryptoStreamMode.Write); var data = property.data; cryStream.Write(data, 0, data.Length); cryStream.FlushFinalBlock(); return(type.Equals(EncryptType.Encrypt) ? Convert.ToBase64String(ms.ToArray()) : Encoding.UTF8.GetString(ms.GetBuffer())); }
public CTransaction() { if (Esam.IsUse) { EnType = EncryptType.Hardware; } else { EnType = EncryptType.Soft; } DType = (DesType)Global.gConfig.TransConfig.DESType; AlType = (AlgorithmType)Global.gConfig.TransConfig.AlgorithmType; if (DType == DesType.Des) { MasterKey = new byte[8]; MasterKey = Utility.str2Bcd(Global.gConfig.TransConfig.MasterKey); } else if (DType == DesType.TripleDes) { MasterKey = new byte[16]; MasterKey = Utility.str2Bcd(Global.gConfig.TransConfig.MasterKey); } TransUpPack = new Iso8583Package(Global.gAppPath + "\\iso8583.xml"); TransUpPack.SmartBitmap = true; TransUpPack.MessageTypeLen = 4; TransDownPack = new Iso8583Package(Global.gAppPath + "\\iso8583.xml"); TransDownPack.SmartBitmap = true; TransDownPack.MessageTypeLen = 4; }
/// <summary> /// ½âÃÜ /// </summary> public static string Decrypt(string value, EncryptType encrypt = EncryptType.AES) { if (string.IsNullOrEmpty(value)) { return(null); } switch (encrypt) { case EncryptType.AES: return(DecryptAES(value)); case EncryptType.DES: return(DecryptDES(value)); case EncryptType.RSA: return(DecryptRSA(value)); case EncryptType.Base64: return(DecryptBase64(value)); default: return(value); } }
/// <summary> /// 加密文字(預設使用SHA256) /// </summary> /// <param name="plainText">原始文字</param> /// <param name="hashAlgorithm">加密演算法(預設為SHA256)</param> /// <returns>加密後文字</returns> public static string ComputeHash(string plainText, EncryptType hashAlgorithm) { byte[] textBytes = Encoding.UTF8.GetBytes(plainText); // implement Encrypt Algorithm HashAlgorithm hash = new SHA256Managed(); switch (hashAlgorithm) { case EncryptType.MD5: hash = new MD5CryptoServiceProvider(); break; case EncryptType.SHA1: hash = new SHA1Managed(); break; case EncryptType.SHA256: hash = new SHA256Managed(); break; case EncryptType.SHA512: hash = new SHA512Managed(); break; default: hash = new SHA256Managed(); break; } byte[] hashBytes = hash.ComputeHash(textBytes); return(Convert.ToBase64String(hashBytes)); }
/// <summary> /// 解密通用函数 /// </summary> /// <param name="DecryptType">解密方法</param> /// <param name="DecryptText">待解密的密文</param> /// <param name="DecryptKey">密匙</param> /// <returns></returns> public static String DataDecrypt(EncryptType Type, String DecryptText) { if (String.IsNullOrEmpty(DecryptText)) { return("Paramters no value"); } switch (Type) { case EncryptType.ASCII: return(ASCIIDecrypt(DecryptText, Skey)); case EncryptType.UTF8: return(UTF8Decrypt(DecryptText, Skey)); case EncryptType.MD5: return(MD5Decrypt(DecryptText, Skey)); case EncryptType.DES: return(DESDecrypt(DecryptText, Skey)); case EncryptType.RC2: return(RC2Decrypt(DecryptText, Skey)); case EncryptType.AES: return(AESDecrypt(DecryptText, Skey)); default: return("Not support this Decrypt type."); } }
public EncryptString(string mac, string last, string target) { this.mac = mac; this.last = last; this.target = target; type = EncryptType.day; }
/// <summary> /// Creates an asymmetric algoritm. /// </summary> /// <param name="encryptType"> /// Encrypt type. /// </param> public static SymmetricAlgorithm CreateSymmetricAlgoritm(EncryptType encryptType) { SymmetricAlgorithm result = null; switch (encryptType) { case EncryptType.etTripleDES: { result = new TripleDESCryptoServiceProvider(); result.KeySize = 192; result.BlockSize = 64; break; } case EncryptType.etRijndael: { result = new RijndaelManaged(); result.KeySize = 256; result.BlockSize = 256; break; } } if (result != null) { result.Mode = CipherMode.CBC; result.Padding = PaddingMode.ISO10126; } return(result); }
/// <summary> /// 得到文件信息 /// </summary> /// <param name="formFile"></param> /// <param name="encryptType">加密方式,默认加密方式为Sha256</param> /// <returns></returns> public static EInfrastructure.Core.Tools.Files.FileInfo Get(IFormFile formFile, EncryptType encryptType = null) { string conditionCode = ""; if (encryptType != null) { if (encryptType.Id == EncryptType.Md5.Id) { conditionCode = GetMd5(formFile); } else if (encryptType.Id == EncryptType.Sha1.Id) { conditionCode = GetSha1(formFile); } else if (encryptType.Id == EncryptType.Sha256.Id) { conditionCode = GetSha256(formFile); } else if (encryptType.Id == EncryptType.Sha384.Id) { conditionCode = GetSha384(formFile); } else if (encryptType.Id == EncryptType.Sha512.Id) { conditionCode = GetSha512(formFile); } } else { conditionCode = GetSha256(formFile); } return(new EInfrastructure.Core.Tools.Files.FileInfo(formFile.FileName, conditionCode)); }
private byte[] DoEncrypt(EncryptType type, string key, string original) { var encrypt = GetEncrypt(type); var encryptData = encrypt != null?encrypt.Encrypt(original, key) : _utf8.GetBytes(original); return(encryptData); }
private string DoDecrypt(EncryptType type, string key, byte[] original) { var encrypt = GetEncrypt(type); var decryptData = encrypt != null?encrypt.StringDecrypt(original, key) : _utf8.GetString(original); return(decryptData); }
/// <summary> /// Initializes a new instance of the <see cref="BaseSocketConnectionCreator"/> class. /// </summary> /// <param name="host">The host.</param> /// <param name="name">The name.</param> /// <param name="localEndPoint">The local end point.</param> /// <param name="encryptType">Type of the encrypt.</param> /// <param name="compressionType">Type of the compression.</param> /// <param name="cryptoService">The crypto service.</param> protected BaseSocketConnectionCreator(BaseSocketConnectionHost host, string name, IPEndPoint localEndPoint, EncryptType encryptType, CompressionType compressionType, ICryptoService cryptoService) { FHost = host; FName = name; FLocalEndPoint = localEndPoint; FCompressionType = compressionType; FEncryptType = encryptType; FCryptoService = cryptoService; }
public NetworkConn(MsgHandler msgHandler, string serverName, Type serverType, int iReceiveTimeout) { m_encryptType = EncryptType.WHOLE_ENCRYPT; m_maxEncryptLen = 100; m_secretKey = 0xBCAF5432; m_strName = serverName; m_type = serverType; m_handler = msgHandler; m_iReceiveTimeout = iReceiveTimeout; }
public RedisEncrypt(Encoding encoding, EncryptType entryptType) { if (encoding != null) { _encoding = encoding; } _entryptType = entryptType; _md5 = new HMACMD5(); }
public static string ReadEncrypt(string path, EncryptType encrypt = EncryptType.AES) { if (File.Exists(path)) { byte[] buffer = File.ReadAllBytes(path); return(Cryptogram.Encrypt(Encoding.Default.GetString(buffer), encrypt)); } return(string.Empty); }
public static string Encrypt(this string src, EncryptType encryptType = EncryptType.Normal) {//编码后 if (encryptType == EncryptType.Normal) { return(EncryptUtility.Encode("" + src).EnCode()); //.Replace("=","-equl-").Replace("/", "-sprit-").Replace("+", "-add-"); } else { return(EncryptUtility.Md5Encrypt("" + src)); } }
public static string Encrypt(this string source, EncryptType encryptType) { switch (encryptType) { case EncryptType.Md5: return(Md5(source)); default: return(source); } }
public SocketConnector(BaseSocketConnectionHost host, string name, IPEndPoint remoteEndPoint, ProxyInfo proxyData, EncryptType encryptType, CompressionType compressionType, ICryptoService cryptoService, int reconnectAttempts, int reconnectAttemptInterval, IPEndPoint localEndPoint) : base(host, name, localEndPoint, encryptType, compressionType, cryptoService, remoteEndPoint) { FReconnectTimer = new Timer(new TimerCallback(ReconnectConnectionTimerCallBack)); FReconnectAttempts = reconnectAttempts; FReconnectAttemptInterval = reconnectAttemptInterval; FReconnectAttempted = 0; FProxyInfo = proxyData; }
public SocketListener AddListener(string name, IPEndPoint localEndPoint, EncryptType encryptType, CompressionType compressionType, ICryptoService cryptoService, byte backLog, byte acceptThreads) { SocketListener listener = null; if (!Disposed) { listener = new SocketListener(this, name, localEndPoint, encryptType, compressionType, cryptoService, backLog, acceptThreads); listener.AddCreator(); } return listener; }
public BaseSocketConnectionCreator(BaseSocketConnectionHost host, string name, IPEndPoint localEndPoint, EncryptType encryptType, CompressionType compressionType, ICryptoService cryptoService) { FHost = host; FName = name; FLocalEndPoint = localEndPoint; FCompressionType = compressionType; FEncryptType = encryptType; FCryptoService = cryptoService; }
public static IEncrypt GetEncryptProvider(EncryptType type, string key, string iv) { switch (type) { case EncryptType.DES: return new DES(key, iv); case EncryptType.TripleDES: return new TripleDES(key, iv); case EncryptType.Rijndeal: default: return new Rijndael(key, iv); } }
public SocketListener AddListener(string name, IPEndPoint localEndPoint, EncryptType encryptType, CompressionType compressionType, ICryptoService cryptoService, byte backLog, byte acceptThreads) { SocketListener listener = null; if (!Disposed) { listener = new SocketListener(this, name, localEndPoint, encryptType, compressionType, cryptoService, backLog, acceptThreads); AddCreator(listener); } return(listener); }
public SocketConnector AddConnector(string name, IPEndPoint remoteEndPoint, ProxyInfo proxyData, EncryptType encryptType, CompressionType compressionType, ICryptoService cryptoService, int reconnectAttempts, int reconnectAttemptInterval, IPEndPoint localEndPoint) { SocketConnector result = null; if (!Disposed) { result = new SocketConnector(this, name, remoteEndPoint, proxyData, encryptType, compressionType, cryptoService, reconnectAttempts, reconnectAttemptInterval, localEndPoint); result.AddCreator(); } return result; }
public SysUserDemo LoginVerify(string uid, string psd, EncryptType encryptType) { var encrypt = EncryptFactory.GetInstance().Create(encryptType); var encryptPsd = encrypt.Encrypt(psd); var user = Query(u => u.Account == uid).FirstOrDefault(); if (user == null || user.Password != encryptPsd) { return(null); } return(user); }
public static string Decrypt(EncryptType type, string sourceString, string key, string iv) { switch (type) { case EncryptType.DES: return(DESDecrypt(sourceString, key, iv)); case EncryptType.AES: return(AESDecrypt(sourceString, key, iv)); default: return("解密算法未实现"); } }
/// <summary> /// 加密 /// </summary> /// <param name="key"></param> /// <param name="text"></param> /// <param name="type"></param> /// <returns></returns> public static string Encrypt(string key, string text, EncryptType type) { switch (type) { case EncryptType.AES: return(AESEncrypt.BaseEncrypt(text, key)); case EncryptType.AESUnsigned: return(AESEncrypt.Encrypt(text, key)); default: throw new Exception("未实现的解密方式"); } }
public static string Encrypt(EncryptType type, string sourceString, string key, string iv) { switch (type) { case EncryptType.DES: return(DESEncrypt(sourceString, key, iv)); case EncryptType.AES: return(AESEncrypt(sourceString, key, iv)); default: return("加密方式不正确"); } }
public static string AESEncryptDecryptStr(string inStr, EncryptType encryptType) { if (string.IsNullOrEmpty(inStr)) { return(string.Empty); } byte[] inbuffer = null; if (encryptType == EncryptType.Encryption) { inbuffer = ASCIIEncoding.UTF8.GetBytes(inStr); } else if (encryptType == EncryptType.Decryption) { inbuffer = Convert.FromBase64String(inStr); } else { throw new Exception("Failed to encrypt decrypt string, the encryptType " + encryptType.ToString() + " doesn't know."); } byte[] outBuffer = new byte[inbuffer.Length]; GCHandle gcHandleIn = GCHandle.Alloc(inbuffer, GCHandleType.Pinned); GCHandle gcHandleOut = GCHandle.Alloc(outBuffer, GCHandleType.Pinned); IntPtr inBufferPtr = Marshal.UnsafeAddrOfPinnedArrayElement(inbuffer, 0); IntPtr outBufferPtr = Marshal.UnsafeAddrOfPinnedArrayElement(outBuffer, 0); try { bool retVal = AESEncryptDecryptBuffer(inBufferPtr, outBufferPtr, (uint)inbuffer.Length, 0, null, 0, null, 0); if (encryptType == EncryptType.Encryption) { return(Convert.ToBase64String(outBuffer)); } else //if (encryptType == EncryptType.Decryption) { return(ASCIIEncoding.UTF8.GetString(outBuffer)); } } finally { gcHandleIn.Free(); gcHandleOut.Free(); } }
/// <summary> /// 根据文件名读取无加密文件 /// </summary> /// <param name="name">文件名</param> /// <returns></returns> public virtual bool Read(string name, string path, EncryptType encryptType = EncryptType.None) { SetSaveSetting(name, path, encryptType); bool bReadSuccess = m_DataReader.Read(ref Data, m_SaveSetting); if (Data == null) { Data = new T(); Data.InitWithEmptyData(); Data.SetDirty(); } Data.SetRecorder(new DataDirtyRecorder()); Data.OnDataLoadFinish(); return(bReadSuccess); }
public BaseSocketConnectionCreator(BaseSocketConnectionHost host, string name, IPEndPoint localEndPoint, EncryptType encryptType, CompressionType compressionType, ICryptoService cryptoService, IPEndPoint remoteEndPoint) { Context = new SocketCreatorContext { CompressionType = compressionType, CryptoService = cryptoService, Host = host, EncryptType = encryptType, Name = name, LocalEndPoint = localEndPoint, RemotEndPoint = remoteEndPoint }; //fWaitCreatorsDisposing = new ManualResetEvent(false); }
public static IEncrypt GetEncryptProvider(EncryptType type, string key, string iv) { switch (type) { case EncryptType.DES: return(new DES(key, iv)); case EncryptType.TripleDES: return(new TripleDES(key, iv)); case EncryptType.Rijndeal: default: return(new Rijndael(key, iv)); } }
public static void WriteEncrypt(string path, string content, EncryptType encrypt = EncryptType.AES) { try { byte[] buffer = Encoding.Default.GetBytes(Cryptogram.Decrypt(content, encrypt)); CreateDirectory(Path.GetDirectoryName(path)); File.WriteAllBytes(path, buffer); } catch (Exception e) { Debuger.LogException(Author.File, e); } }
/// <summary> /// 解密字符串(失败返回空) /// </summary> /// <param name="DecryptString">待解密字符串</param> /// <param name="Mode">加密模式</param> /// <returns></returns> public static string Decode(string DecryptString, EncryptMode Mode) { string ReturnString = ""; if (Mode == EncryptMode.Cipher) { return(ReturnString); } List <EncryptInfo> EncryptList = EncryptConfigs.GetConfig().EncryptInfo; try { foreach (EncryptInfo el in EncryptList) { EncryptMode TempMode = Utils.GetEnum <EncryptMode>(el.EncryptName.Trim(), EncryptMode.Default); if (Mode.Equals(TempMode)) { ReturnString = DecryptString; //反向解密 for (int i = el.EncryptType.Count - 1; i >= 0; i--) { EncryptType ei = el.EncryptType[i]; switch (ei.Type) { case EncryptEnum.AES: ReturnString = AES.Decode(ReturnString, ei.Key); break; case EncryptEnum.DES: ReturnString = DES.Decode(ReturnString, ei.Key); break; default: break; } } break; } } } catch { ReturnString = ""; } return(ReturnString); }
public string Decrypt(string Text, string sKey, EncryptType typecs) { IEncrypt encrypt = null; switch (typecs) { case EncryptType.DES: encrypt = new DESEncrypt(); break; case EncryptType.AES: encrypt = new AESEncrypt(); break; } return(encrypt.Decrypt(Text, sKey)); }
public SaveSetting(string dataName, string path, EncryptType encryptType = EncryptType.AES) { DataName = dataName; BAutoSave = false; SaveType = SaveType.Json; EncryptType = encryptType; BAysn = false; if (string.IsNullOrEmpty(path)) { DataPath = Application.persistentDataPath; } else { DataPath = path; } }
public Encrypt Encode(EncryptType type, string value) { var result = new Encrypt(); result.Value = null; result.Type = type; if (type == EncryptType.OK) { try { var key = AES; if (key != null) { result.Key = key; Cipher c = Cipher.GetInstance("AES"); c.Init(CipherMode.EncryptMode, key as IKey); var encoder = new System.Text.UnicodeEncoding(); result.Value = c.DoFinal(encoder.GetBytes(value)); return(result); } } catch (Exception) { return(null); } } else if (type == EncryptType.STRONG) { try { var keys = RSA; if (keys != null) { result.PublicKey = keys[1]; result.PrivateKey = keys[0]; Cipher c = Cipher.GetInstance("RSA"); c.Init(Javax.Crypto.CipherMode.EncryptMode, result.PublicKey as IKey); var encoder = new System.Text.UnicodeEncoding(); result.Value = c.DoFinal(encoder.GetBytes(value)); return(result); } } catch (Exception) { return(null); } } return(null); }
public Encrypt Encode(EncryptType type, string value) { try { string finalKey = cryptoKey.PadRight(KeyLength, FillCharacter); var result = new Encrypt(); result.Type = EncryptType.OK; RijndaelManaged crypto = null; MemoryStream mStream = null; ICryptoTransform encryptor = null; CryptoStream cryptoStream = null; byte[] plainBytes = System.Text.Encoding.UTF8.GetBytes(value); try { crypto = new RijndaelManaged(); crypto.KeySize = 128; crypto.Padding = PaddingMode.PKCS7; // HERE IS THE "ISSUE" // The default mode on .NET 4 is CBC, wich seems not to be the case on MonoTouch. crypto.Mode = CipherMode.CBC; encryptor = crypto.CreateEncryptor(Encoding.UTF8.GetBytes(finalKey), Encoding.UTF8.GetBytes(finalKey)); mStream = new MemoryStream(); cryptoStream = new CryptoStream(mStream, encryptor, CryptoStreamMode.Write); cryptoStream.Write(plainBytes, 0, plainBytes.Length); } finally { if (crypto != null) crypto.Clear(); cryptoStream.Close(); } result.Value = mStream.ToArray(); return result; } catch (Exception) { return null; } }
/// <summary> /// Creates an asymmetric algoritm. /// </summary> /// <param name="encryptType"> /// Encrypt type. /// </param> public static SymmetricAlgorithm CreateSymmetricAlgoritm(EncryptType encryptType) { SymmetricAlgorithm result = null; switch (encryptType) { case EncryptType.etTripleDES: { result = new TripleDESCryptoServiceProvider(); result.KeySize = 192; result.BlockSize = 64; break; } case EncryptType.etRijndael: { result = new RijndaelManaged(); result.KeySize = 256; result.BlockSize = 256; break; } } if (result != null) { result.Mode = CipherMode.CBC; result.Padding = PaddingMode.ISO10126; } return result; }
public string EncryptData(string data, EncryptType encryptType) { string encryptedString = ""; if (data == "null") { encryptedString = "null"; } if (data != null && data != string.Empty && data.ToLower() != "null") { switch (encryptType) { case EncryptType.Symmetric: Symmetric.Provider p = Symmetric.Provider.TripleDES; Symmetric sym = new Symmetric(p); //sym.Key.Text = symmetricKey; Data encryptedData = null; encryptedData = sym.Encrypt(new Data(data)); encryptedString = encryptedData.Base64; break; case EncryptType.Asymmetric: Asymmetric asym = new Asymmetric(); Asymmetric.PublicKey pubkey = new Asymmetric.PublicKey(); Asymmetric.PrivateKey privkey = new Asymmetric.PrivateKey(); asym.GenerateNewKeyset(ref pubkey, ref privkey); Data EncryptedData = null; EncryptedData = asym.Encrypt(new Data(data), pubkey); encryptedString = EncryptedData.Base64; break; case EncryptType.Hash: Hash.Provider phash = Hash.Provider.SHA1; Hash hash = new Hash(phash); EncryptedData = hash.Calculate(new Data(data)); encryptedString = EncryptedData.Base64; break; } } return encryptedString; }
/// <summary> /// Creates an asymmetric algoritm. /// </summary> /// <param name="encryptType"> /// Encrypt type. /// </param> public static SymmetricAlgorithm CreateSymmetricAlgoritm(EncryptType encryptType) { SymmetricAlgorithm result = null; switch (encryptType) { case EncryptType.etRijndael: { result = new RijndaelManaged(); result.KeySize = 256; result.BlockSize = 256; break; } } if (result != null) { result.Mode = CipherMode.CBC; } return result; }
public SocketClientSync(IPEndPoint host) { FReceivedEvent = new AutoResetEvent(false); FExceptionEvent = new AutoResetEvent(false); FSentEvent = new AutoResetEvent(false); FConnectEvent = new AutoResetEvent(false); FDisconnectEvent = new ManualResetEvent(false); FReceivedQueue = new Queue<string>(); FConnectTimeout = 10000; FSentTimeout = 10000; FConnectedSync = new object(); FConnected = false; FSocketClientEvents = new SocketClientSyncSocketService(this); FCryptClientEvents = new SocketClientSyncCryptService(this); FLocalEndPoint = null; FRemoteEndPoint = host; //----- Message Types! FEncryptType = EncryptType.etNone; FCompressionType = CompressionType.ctNone; FDelimiterType = DelimiterType.dtNone; //----- Proxy! FProxyInfo = null; //----- Socket delimiter and buffer size! FDelimiter = null; FMessageBufferSize = 4096; FSocketBufferSize = 2048; }
public SocketListener AddListener(string name, IPEndPoint localEndPoint, EncryptType encryptType, CompressionType compressionType, ICryptoService cryptoService) { return AddListener(name, localEndPoint, encryptType, compressionType, cryptoService, 5, 2); }
public static Byte[] Encrypt(Byte[] bytearray, EncryptType type = EncryptType.AlphaNumeric) { if (bytearray == null) return null; byte[] result = new byte[bytearray.Length * 2]; for (int i = 0; i < bytearray.Length; i++) { switch (type) { case EncryptType.AlphaNumeric: result[(i * 2)] = AlphaNumericTable[bytearray[i]][0]; result[(i * 2) + 1] = AlphaNumericTable[bytearray[i]][1]; break; case EncryptType.ClearText: result[(i * 2)] = bytearray[i]; result[(i * 2) + 1] = 0; break; case EncryptType.Random: Random random = new Random(); Byte j = (Byte)random.Next(0, 255); result[(i * 2)] = Encrypt(bytearray[i], j); result[(i * 2) + 1] = j; break; case EncryptType.Sequential: result[(i * 2)] = Encrypt(bytearray[i], (byte)i); result[(i * 2) + 1] = (byte)i; break; } } return result; }
public static IEncrypt GetEncryptProvider(EncryptType type) { return GetEncryptProvider(type, "THISISXYFRAMEENCRYPTKEY", "VITPYRCNEEMARYXSISIHT"); }
/// <summary> /// Base SocketListener creator. /// </summary> /// <param name="host"> /// Host. /// </param> /// <param name="localEndPoint"> /// Local endpoint to be used. /// </param> /// <param name="encryptType"> /// Encryption to be used. /// </param> /// <param name="compressionType"> /// Compression to be used. /// </param> /// <param name="cryptoService"> /// CryptoService. if null, will not be used. /// </param> /// <param name="backLog"> /// Socket backlog queue number. /// </param> /// <param name="acceptThreads"> /// Number of accept events to be used. /// </param> public SocketListener(BaseSocketConnectionHost host, string name, IPEndPoint localEndPoint, EncryptType encryptType, CompressionType compressionType, ICryptoService cryptoService, byte backLog, byte acceptThreads) : base(host, name, localEndPoint, encryptType, compressionType, cryptoService) { FBackLog = backLog; FAcceptThreads = acceptThreads; }
/// <summary> /// 将接收到的字节数组转换为结构体 /// </summary> /// <param name="receivedBuffer">还原后的字节数组</param> public void ReadBuffer(byte[] receivedBuffer) { //检验是否有帧头帧尾 int dataLen = receivedBuffer.Length; if (receivedBuffer[0] == 0x7E && receivedBuffer[dataLen - 1] == 0x7E) { //去掉帧头帧尾的数据帧 byte[] dataBuffer = new byte[dataLen - 2]; Array.Copy(receivedBuffer, 1, dataBuffer, 0, dataBuffer.Length); //消息ID MsgIDByte = new byte[] { dataBuffer[0], dataBuffer[1] }; MsgID = (BuBiaoMsgIdType)Enum.ToObject(typeof(BuBiaoMsgIdType), BitConverter.ToUInt16(BuBiaoData.LocalByteToNetByteOrder(MsgIDByte), 0)); //消息体属性 MspProperty = new byte[] { dataBuffer[2], dataBuffer[3] }; //消息体属性的内容 IsMutiPackage = BuBiaoData.getBit(MspProperty[0], 5) == 1 ? true : false; //如果第10位(相当于高字节第二位)为1,则表示RSA加密 if (BuBiaoData.getBit(MspProperty[0], 2) == 1) { IsEncrypt = EncryptType.RSA; } else { IsEncrypt = EncryptType.NoEncrypt; } //取得消息体长度的前两位 byte Length1 = BuBiaoData.DoByteAND(MspProperty[0], 0x03); //取得消息体长度 byte[] LengthBytes = { Length1, MspProperty[1] }; //消息体长度 DataLength = BitConverter.ToUInt16(BuBiaoData.LocalByteToNetByteOrder(LengthBytes), 0); //终端手机号 TMLPhoneNumByte = new byte[] { dataBuffer[4], dataBuffer[5], dataBuffer[6], dataBuffer[7], dataBuffer[8], dataBuffer[9] }; //标准部标协议 byte[] TMLPhoneNumInt = BuBiaoData.BCDToInt(TMLPhoneNumByte); StringBuilder sb = new StringBuilder(); for (int i = 0, i_Count = TMLPhoneNumInt.Length; i < i_Count; i++) { sb.Append(TMLPhoneNumInt[i].ToString()); } TMLPhoneNum = sb.ToString(); GPSCode = "0037" + TMLPhoneNum; //消息流水号 SerialNum = new byte[] { dataBuffer[10], dataBuffer[11] }; //消息体的起始位置 int DataStartIndex = 12; if (IsMutiPackage) { //消息总包数 PackageCountByte = new byte[] { dataBuffer[12], dataBuffer[13] }; PackageCount = BitConverter.ToUInt16(BuBiaoData.LocalByteToNetByteOrder(PackageCountByte), 0); //包序号 PackageIndexByte = new byte[] { dataBuffer[14], dataBuffer[15] }; PackageIndex = BitConverter.ToUInt16(BuBiaoData.LocalByteToNetByteOrder(PackageIndexByte), 0); DataStartIndex = 16; } //消息体 if (DataLength > 0) { Data = new byte[DataLength]; Array.Copy(dataBuffer, DataStartIndex, Data, 0, DataLength); } //校验码 CheckSum = dataBuffer[dataBuffer.Length - 1]; //计算校验和 if (BuBiaoData.GetCheckSum(receivedBuffer) == CheckSum) { //标为有效数据 IsValidData = true; } } }
//public GPRSFrame(BuBiaoMsgIdType MsgID, bool IsMutiPackage, EncryptType IsEncrypt, UInt16 DataLength // , byte[] TMLPhoneNum, byte[] SerialNum, UInt16 PackageCount, UInt16 PackageIndex, byte[] Data) public GPRSFrame(BuBiaoMsgIdType MsgID, bool IsMutiPackage, EncryptType IsEncrypt, UInt16 DataLength , string FullGpsCode, UInt16 SerialNum, UInt16 PackageCount, UInt16 PackageIndex, byte[] Data) { byte[] PhoneNumberByt; this.MsgIDByte = null; this.MsgID = MsgID; this.MspProperty = null; this.IsMutiPackage = IsMutiPackage; this.IsEncrypt = IsEncrypt; this.DataLength = DataLength; this.TMLPhoneNum = string.Empty; this.GPSCode = string.Empty; string strTmpSimNum = FullGpsCode.Substring(4); string strPhoneNumber = ""; if (strTmpSimNum.Length == 11) strPhoneNumber = "0" + strTmpSimNum; else strPhoneNumber = "0" + strTmpSimNum.PadLeft(11, '1'); PhoneNumberByt = new byte[strPhoneNumber.Length]; for (int i = 0; i < strPhoneNumber.Length; i++) { PhoneNumberByt[i] = Convert.ToByte(strPhoneNumber.Substring(i, 1)); } this.TMLPhoneNumByte = BuBiaoData.IntToBCD(PhoneNumberByt); this.SerialNum = new byte[2]; byte[] tmpWriteBuffer = new byte[2]; tmpWriteBuffer = BitConverter.GetBytes(SerialNum); Array.Copy(BuBiaoData.LocalByteToNetByteOrder(tmpWriteBuffer), 0, this.SerialNum, 0, 2); //this.SerialNum = SerialNum; this.PackageCountByte = null; this.PackageCount = PackageCount; this.PackageIndexByte = null; this.PackageIndex = PackageIndex; this.Data = Data; this.CheckSum = 0; this.IsValidData = false; this.LastPackUpdateTime = DateTime.Now; this.dicChildPacket = new Dictionary<ushort, byte[]>(); }
public Encrypt Encode(EncryptType type, string value) { var result = new Encrypt (); result.Value = null; result.Type = type; if (type == EncryptType.OK) { try { var key = AES; if (key != null) { result.Key = key; Cipher c = Cipher.GetInstance("AES"); c.Init(CipherMode.EncryptMode, key as IKey); var encoder = new System.Text.UnicodeEncoding(); result.Value = c.DoFinal(encoder.GetBytes(value)); return result; } } catch (Exception) { return null; } } else if (type == EncryptType.STRONG) { try { var keys = RSA; if (keys != null) { result.PublicKey = keys[1]; result.PrivateKey = keys[0]; Cipher c = Cipher.GetInstance ("RSA"); c.Init(Javax.Crypto.CipherMode.EncryptMode, result.PublicKey as IKey); var encoder = new System.Text.UnicodeEncoding(); result.Value = c.DoFinal (encoder.GetBytes(value)); return result; } } catch (Exception) { return null; } } return null; }
/// <summary> /// 带参数构造方法 /// </summary> /// <param name="MsgID"></param> /// <param name="IsMutiPackage"></param> /// <param name="IsEncrypt"></param> /// <param name="DataLength"></param> /// <param name="TMLPhoneNum"></param> /// <param name="SerialNum"></param> /// <param name="PackageCount"></param> /// <param name="PackageIndex"></param> /// <param name="Data"></param> public GPRSFrame(BuBiaoMsgIdType MsgID, bool IsMutiPackage, EncryptType IsEncrypt, UInt16 DataLength , byte[] TMLPhoneNumbyte, byte[] SerialNum, UInt16 PackageCount, UInt16 PackageIndex, byte[] Data) { this.MsgIDByte = null; this.MsgID = MsgID; this.MspProperty = null; this.IsMutiPackage = IsMutiPackage; this.IsEncrypt = IsEncrypt; this.DataLength = DataLength; this.TMLPhoneNum = string.Empty; this.TMLPhoneNumByte = TMLPhoneNumbyte; this.GPSCode = string.Empty; this.SerialNum = SerialNum; this.PackageCountByte = null; this.PackageCount = PackageCount; this.PackageIndexByte = null; this.PackageIndex = PackageIndex; this.Data = Data; this.CheckSum = 0; this.IsValidData = false; this.LastPackUpdateTime = DateTime.Now; this.dicChildPacket = new Dictionary<ushort, byte[]>(); }
public SocketConnector AddConnector(string name, IPEndPoint remoteEndPoint, ProxyInfo proxyData, EncryptType encryptType, CompressionType compressionType, ICryptoService cryptoService, int reconnectAttempts, int reconnectAttemptInterval) { return AddConnector(name, remoteEndPoint, proxyData, encryptType, compressionType, cryptoService, reconnectAttempts, reconnectAttemptInterval, new IPEndPoint(IPAddress.Any, 0)); }
public BaseSocketConnectionCreator(BaseSocketConnectionHost host, string name, IPEndPoint localEndPoint, EncryptType encryptType, ICryptoService cryptoService) : this(host, name, localEndPoint, encryptType, CompressionType.ctNone, cryptoService, null) { }
/// <summary> /// /// </summary> /// <param name="msg">数据明文</param> /// <param name="token">sha1签名使用的token</param> /// <param name="key">aes_key或rsa 秘钥或rsa公钥</param> /// <param name="crypttype">加密算法</param> /// <param name="id">接入商id或唯一md5字符串</param> /// <returns>null 加密异常 或 加密密文</returns> public static string Encode(string msg,string token,string key, EncryptType crypttype,string id) { try { string encode_msg = msg; if (crypttype == EncryptType.IsAES) { encode_msg = AESHelper.Base64ToBase64Url(AESHelper.AESEncrypt(msg, key,key)); } else if (crypttype == EncryptType.IsRSA) { encode_msg = AESHelper.Base64ToBase64Url(RSAHelper.RSAEncrypt(key, msg)); } StringBuilder s = new StringBuilder(); string timestamp = ConvertDateTimeInt(DateTime.Now).ToString(); string msign = MD5Sign(crypttype==EncryptType.IsRSA?token:key, encode_msg); string sign = SHA1Sign(msign, timestamp, token); s.AppendFormat("compress={0}&id={1}&sign={2}×tamp={3}&msign={4}&encrypt={5}", encode_msg, id, sign, timestamp, msign,crypttype.ToString()); return s.ToString(); }catch(Exception e) { return null; } }
public string DecryptData(string encryptedString, EncryptType encryptType) { string data = ""; if (encryptedString != null && encryptedString != string.Empty && data.ToLower() != "null") { switch (encryptType) { case EncryptType.Symmetric: Symmetric.Provider p = Symmetric.Provider.TripleDES; Data symdecryptedData = null; p = Symmetric.Provider.TripleDES; Symmetric sym2 = new Symmetric(p); //sym2.Key.Text = symmetricKey; System.Text.ASCIIEncoding symEncoding = new System.Text.ASCIIEncoding(); Byte[] symBytes = symEncoding.GetBytes(encryptedString); Data symencryptedData = null; symencryptedData = new Data(); symencryptedData.Base64 = encryptedString; symdecryptedData = sym2.Decrypt(symencryptedData); data = symdecryptedData.Text; break; case EncryptType.Asymmetric: System.Text.ASCIIEncoding asymEncoding = new System.Text.ASCIIEncoding(); Data asymdecryptedData = null; Asymmetric asym2 = new Asymmetric(); Byte[] asymBytes = asymEncoding.GetBytes(encryptedString); Data asymencryptedData = null; asymencryptedData = new Data(); asymencryptedData.Base64 = encryptedString; asymdecryptedData = asym2.Decrypt(asymencryptedData); data = asymdecryptedData.Text; break; case EncryptType.Hash: //hashing is one way break; } } return data; }