private RSA getClientCertRSA(RSA privKey) { RSAParameters parameters = new RSAParameters(); RSAParameters rsaParameters = privKey.ExportParameters(true); ASN1 asN1_1 = new ASN1(this.Context.ClientSettings.Certificates[0].GetPublicKey()); ASN1 asN1_2 = asN1_1[0]; if (asN1_2 == null || asN1_2.Tag != (byte)2) { return((RSA)null); } ASN1 asN1_3 = asN1_1[1]; if (asN1_3.Tag != (byte)2) { return((RSA)null); } parameters.Modulus = this.getUnsignedBigInteger(asN1_2.Value); parameters.Exponent = asN1_3.Value; parameters.D = rsaParameters.D; parameters.DP = rsaParameters.DP; parameters.DQ = rsaParameters.DQ; parameters.InverseQ = rsaParameters.InverseQ; parameters.P = rsaParameters.P; parameters.Q = rsaParameters.Q; RSAManaged rsaManaged = new RSAManaged(parameters.Modulus.Length << 3); rsaManaged.ImportParameters(parameters); return((RSA)rsaManaged); }
public void ProcessCommon(bool sendLength) { byte[] array = base.Context.Negotiating.Cipher.CreatePremasterSecret(); RSA rsa; if (base.Context.ServerSettings.ServerKeyExchange) { rsa = new RSAManaged(); rsa.ImportParameters(base.Context.ServerSettings.RsaParameters); } else { rsa = base.Context.ServerSettings.CertificateRSA; } RSAPKCS1KeyExchangeFormatter rsapkcs1KeyExchangeFormatter = new RSAPKCS1KeyExchangeFormatter(rsa); byte[] array2 = rsapkcs1KeyExchangeFormatter.CreateKeyExchange(array); if (sendLength) { base.Write((short)array2.Length); } base.Write(array2); base.Context.Negotiating.Cipher.ComputeMasterSecret(array); base.Context.Negotiating.Cipher.ComputeKeys(); rsa.Clear(); }
public override void GenerateClient(TlsContext ctx) { // Compute pre master secret using (var preMasterSecret = ctx.Session.GetSecureRandomBytes(48)) { preMasterSecret.Buffer [0] = (byte)((short)ctx.Configuration.RequestedProtocol >> 8); preMasterSecret.Buffer [1] = (byte)ctx.Configuration.RequestedProtocol; RSA rsa = null; // Create a new RSA key var serverCertificates = ctx.Session.PendingCrypto.ServerCertificates; if (serverCertificates == null || serverCertificates.Count == 0) { // FIXME: Should have received ServerKeyExchange message. throw new TlsException(AlertDescription.IlegalParameter); } else { rsa = new RSAManaged(serverCertificates [0].RSA.KeySize); rsa.ImportParameters(serverCertificates [0].RSA.ExportParameters(false)); } ComputeMasterSecret(ctx, preMasterSecret); // Encrypt premaster_sercret var formatter = new RSAPKCS1KeyExchangeFormatter(rsa); encryptedPreMasterSecret = formatter.CreateKeyExchange(preMasterSecret.Buffer); rsa.Clear(); } }
private void crakerKey() { var forBuild = 65535; var validTillDate = DateTime.Now.AddDays(64).Subtract(new DateTime(2010, 12, 31)).TotalDays; var forgedBytes = new byte[16]; forgedBytes[0] = (byte)(validTillDate / 256); forgedBytes[1] = (byte)(validTillDate % 256); forgedBytes[2] = (byte)(forBuild / 256); forgedBytes[3] = (byte)(forBuild % 256); var output = new byte[32]; output[0] = 7; var rnd = new Random(); for (var x = 1; x < 13; x++) { output[x] = (byte)rnd.Next(1, 256); } Array.Copy(forgedBytes, 0, output, 14, forgedBytes.Length); var rsaManaged2 = new RSAManaged(); rsaManaged2.FromXmlString("<RSAKeyValue><Modulus>thycVKzZzdxBD6Rl8RoS9MEs1rrLY5qDhse+a+ljfpM=</Modulus><Exponent>AQAB</Exponent><P>xJXNbvuhJEpA647ZChJHMQ==</P><Q>7Sb4m1/8WXGGL/2Zw075Aw==</Q><DP>VtattvbkyfkbEHM7oN1OIQ==</DP><DQ>0kQaatCpErjYDBbjTUro9w==</DQ><InieQ>AVeR8pKZ4H05p7NRb02kNw==</InverseQ><D>ENshFS1Sk51ZYEtFLEXPjzPUmZbbIak0S+dyUK5o/sE=</D></RSAKeyValue>"); var decrypted = rsaManaged2.DecryptValue(output); var key = "==A" + Convert.ToBase64String(decrypted) + "="; string a = key.ToString(); Rebex.Licensing.Key = a; }
void GenerateKeyPair() { var rsa = new RSAManaged((int)keySize); KeyValue = rsa.ToXmlString(true); IsValid = true; }
void Common(int dwKeySize, bool parameters) { // Microsoft RSA CSP can do between 384 and 16384 bits keypair LegalKeySizesValue = new KeySizes[1]; LegalKeySizesValue[0] = new KeySizes(384, 16384, 8); base.KeySize = dwKeySize; rsa = new RSAManaged(KeySize); rsa.KeyGenerated += new RSAManaged.KeyGeneratedEventHandler(OnKeyGenerated); persistKey = parameters; if (parameters) { return; } // no need to load - it cannot exists var p = new CspParameters(PROV_RSA_FULL); if (useMachineKeyStore) { p.Flags |= CspProviderFlags.UseMachineKeyStore; } store = new KeyPairPersistence(p); }
private RSA getClientCertRSA(RSA privKey) { RSAParameters parameters = default(RSAParameters); RSAParameters rsaparameters = privKey.ExportParameters(true); ASN1 asn = new ASN1(base.Context.ClientSettings.Certificates[0].GetPublicKey()); ASN1 asn2 = asn[0]; if (asn2 == null || asn2.Tag != 2) { return(null); } ASN1 asn3 = asn[1]; if (asn3.Tag != 2) { return(null); } parameters.Modulus = this.getUnsignedBigInteger(asn2.Value); parameters.Exponent = asn3.Value; parameters.D = rsaparameters.D; parameters.DP = rsaparameters.DP; parameters.DQ = rsaparameters.DQ; parameters.InverseQ = rsaparameters.InverseQ; parameters.P = rsaparameters.P; parameters.Q = rsaparameters.Q; int keySize = parameters.Modulus.Length << 3; RSAManaged rsamanaged = new RSAManaged(keySize); rsamanaged.ImportParameters(parameters); return(rsamanaged); }
static void DisplayCertificate(X509Certificate x509, bool machine, bool verbose) { Console.WriteLine("{0}X.509 v{1} Certificate", (x509.IsSelfSigned ? "Self-signed " : String.Empty), x509.Version); Console.WriteLine(" Serial Number: {0}", CryptoConvert.ToHex(x509.SerialNumber)); Console.WriteLine(" Issuer Name: {0}", x509.IssuerName); Console.WriteLine(" Subject Name: {0}", x509.SubjectName); Console.WriteLine(" Valid From: {0}", x509.ValidFrom); Console.WriteLine(" Valid Until: {0}", x509.ValidUntil); Console.WriteLine(" Unique Hash: {0}", CryptoConvert.ToHex(x509.Hash)); if (verbose) { Console.WriteLine(" Key Algorithm: {0}", x509.KeyAlgorithm); Console.WriteLine(" Algorithm Parameters: {0}", (x509.KeyAlgorithmParameters == null) ? "None" : CryptoConvert.ToHex(x509.KeyAlgorithmParameters)); Console.WriteLine(" Public Key: {0}", CryptoConvert.ToHex(x509.PublicKey)); Console.WriteLine(" Signature Algorithm: {0}", x509.SignatureAlgorithm); Console.WriteLine(" Algorithm Parameters: {0}", (x509.SignatureAlgorithmParameters == null) ? "None" : CryptoConvert.ToHex(x509.SignatureAlgorithmParameters)); Console.WriteLine(" Signature: {0}", CryptoConvert.ToHex(x509.Signature)); RSACryptoServiceProvider rsaCsp = x509.RSA as RSACryptoServiceProvider; RSAManaged rsaManaged = x509.RSA as RSAManaged; Console.WriteLine(" Private Key: {0}", ((rsaCsp != null && !rsaCsp.PublicOnly) || (rsaManaged != null && !rsaManaged.PublicOnly))); CspParameters cspParams = new CspParameters(); cspParams.KeyContainerName = CryptoConvert.ToHex(x509.Hash); cspParams.Flags = machine ? CspProviderFlags.UseMachineKeyStore : 0; KeyPairPersistence kpp = new KeyPairPersistence(cspParams); Console.WriteLine(" KeyPair Key: {0}", kpp.Load()); } Console.WriteLine(); }
private void test1() { //服务端生成好一对 公私钥 RSACryptoServiceProvider rsaServer = new RSACryptoServiceProvider(); //公钥给客户端,用来加密数据(内置,或第一次请求时下行给客户端) string clientPublicKey = rsaServer.ToXmlString(false); //私钥存在服务端,用来解密数据 string serverPrivateKey = rsaServer.ToXmlString(true); //客户端也生成一对 公私钥 RSACryptoServiceProvider rsaClient = new RSACryptoServiceProvider(); //公钥加密后上行给服务端,用来加密数据 string serverPublicKey = rsaClient.ToXmlString(false); //私钥存在客户端,用来解密下行数据 string clientPrivateKey = rsaClient.ToXmlString(true); //客户端请求登录 生成上行数据 string username = "******"; string password = "******"; login upPost = new login() { username = RSAManaged.Encrypt(username, clientPublicKey), password = RSAManaged.Encrypt(password, clientPublicKey), key = RSAManaged.Encrypt(serverPublicKey, clientPublicKey), }; Console.WriteLine("上行数据:" + upPost.ToJson()); //服务端解密 生成下行数据 //解密 login userInfo = new login() { username = RSAManaged.Decrypt(upPost.username, serverPrivateKey), password = RSAManaged.Decrypt(upPost.password, serverPrivateKey), key = RSAManaged.Decrypt(upPost.key, serverPrivateKey), }; Console.WriteLine("上行数据解密:" + userInfo.ToJson()); //生成下行告诉客户断是否登录成功 login downPost = new login() { username = RSAManaged.Encrypt(userInfo.username, userInfo.key), message = RSAManaged.Encrypt((username == "test01" && password == "111111") ? "登录成功!" : "登录失败", userInfo.key), }; Console.WriteLine("下行数据:" + downPost.ToJson()); //客户端取的下行数据,并解密 userInfo = new login() { username = RSAManaged.Decrypt(downPost.username, clientPrivateKey), message = RSAManaged.Decrypt(downPost.message, clientPrivateKey), }; Console.WriteLine("下行数据解密:" + userInfo.ToJson()); Console.WriteLine(userInfo.username); Console.WriteLine(userInfo.message); Console.WriteLine(); }
internal PublicKey(MSX.X509Certificate certificate) { // note: _key MUSTonly contains the public part of the key bool export_required = true; if (certificate.KeyAlgorithm == rsaOid) { #if !MOONLIGHT // shortcut export/import in the case the private key isn't available RSACryptoServiceProvider rcsp = (certificate.RSA as RSACryptoServiceProvider); if ((rcsp != null) && rcsp.PublicOnly) { _key = certificate.RSA; export_required = false; } else #endif { RSAManaged rsam = (certificate.RSA as RSAManaged); if ((rsam != null) && rsam.PublicOnly) { _key = certificate.RSA; export_required = false; } } if (export_required) { RSAParameters rsap = certificate.RSA.ExportParameters(false); _key = RSA.Create(); (_key as RSA).ImportParameters(rsap); } } else { #if !MOONLIGHT // shortcut export/import in the case the private key isn't available DSACryptoServiceProvider dcsp = (certificate.DSA as DSACryptoServiceProvider); if ((dcsp != null) && dcsp.PublicOnly) { _key = certificate.DSA; export_required = false; } // note: DSAManaged isn't available in Mono.Security due to a bug in Fx 1.x if (export_required) { DSAParameters rsap = certificate.DSA.ExportParameters(false); _key = DSA.Create(); (_key as DSA).ImportParameters(rsap); } #endif } _oid = new Oid(certificate.KeyAlgorithm); _keyValue = new AsnEncodedData(_oid, certificate.PublicKey); _params = new AsnEncodedData(_oid, certificate.KeyAlgorithmParameters); }
public void UpdateCertificateRSA() { if (clientCertificate == null) { certificateRSA = null; return; } Mono.Security.X509.X509Certificate x509Certificate = new Mono.Security.X509.X509Certificate(clientCertificate.GetRawCertData()); certificateRSA = new RSAManaged(x509Certificate.RSA.KeySize); certificateRSA.ImportParameters(x509Certificate.RSA.ExportParameters(includePrivateParameters: false)); }
public void UpdateCertificateRSA() { if (this.clientCertificate == null) { this.certificateRSA = (RSAManaged)null; } else { Mono.Security.X509.X509Certificate x509Certificate = new Mono.Security.X509.X509Certificate(this.clientCertificate.GetRawCertData()); this.certificateRSA = new RSAManaged(x509Certificate.RSA.KeySize); this.certificateRSA.ImportParameters(x509Certificate.RSA.ExportParameters(false)); } }
static internal bool TryImportCapiPrivateKeyBlob(byte[] blob, int offset) { try { var rsap = GetParametersFromCapiPrivateKeyBlob(blob, offset); // Since we are only checking whether this throws an exception and // not actually returning the `RSA` object, we can use `RSAManaged` // here because that's what the `RSACryptoServiceProvider` implementation // does internally. var rsa = new RSAManaged(); rsa.ImportParameters(rsap); return(true); } catch (CryptographicException) { return(false); } }
public void UpdateCertificateRSA() { if (Certificates == null || Certificates.Count == 0) { CertificateRSA = null; } else { CertificateRSA = new RSAManaged( Certificates[0].RSA.KeySize); CertificateRSA.ImportParameters( Certificates[0].RSA.ExportParameters(false)); } }
internal PublicKey(X509Certificate certificate) { bool flag = true; if (certificate.KeyAlgorithm == "1.2.840.113549.1.1.1") { RSACryptoServiceProvider rsacryptoServiceProvider = certificate.RSA as RSACryptoServiceProvider; if (rsacryptoServiceProvider != null && rsacryptoServiceProvider.PublicOnly) { this._key = certificate.RSA; flag = false; } else { RSAManaged rsamanaged = certificate.RSA as RSAManaged; if (rsamanaged != null && rsamanaged.PublicOnly) { this._key = certificate.RSA; flag = false; } } if (flag) { RSAParameters parameters = certificate.RSA.ExportParameters(false); this._key = RSA.Create(); (this._key as RSA).ImportParameters(parameters); } } else { DSACryptoServiceProvider dsacryptoServiceProvider = certificate.DSA as DSACryptoServiceProvider; if (dsacryptoServiceProvider != null && dsacryptoServiceProvider.PublicOnly) { this._key = certificate.DSA; flag = false; } if (flag) { DSAParameters parameters2 = certificate.DSA.ExportParameters(false); this._key = DSA.Create(); (this._key as DSA).ImportParameters(parameters2); } } this._oid = new Oid(certificate.KeyAlgorithm); this._keyValue = new AsnEncodedData(this._oid, certificate.PublicKey); this._params = new AsnEncodedData(this._oid, certificate.KeyAlgorithmParameters); }
/// <summary> /// Initializes user connections listener. /// </summary> /// <param name="localEndPoint">Local ip endpoint.</param> /// <param name="backlog">Backlog.</param> /// <param name="enableFirewall">True, if firewall must be enabled, otherwise false.</param> internal static void Initialize(IPEndPoint localEndPoint, int backlog, bool enableFirewall) { m_LocalEndPoint = localEndPoint; m_Backlog = backlog; m_EnableFirewall = enableFirewall; RSAManaged rsa = new RSAManaged(1024); PrivateKey = rsa.ExportParameters(true); PublicKey = rsa.ExportParameters(false); ScrambledKeysPair = new ScrambledKeyPair(ref PrivateKey, ref PublicKey); rsa = null; Enable(); }
public void UpdateCertificateRSA() { if (this.clientCertificate == null) { this.certificateRSA = null; } else { X509.X509Certificate cert = new X509.X509Certificate(this.clientCertificate.GetRawCertData()); this.certificateRSA = new RSAManaged( cert.RSA.KeySize); this.certificateRSA.ImportParameters( cert.RSA.ExportParameters(false)); } }
public void UpdateCertificateRSA() { if (clientCertificate == null) { CertificateRSA = null; } else { var cert = new MonoSecurity::Mono.Security.X509.X509Certificate(clientCertificate.GetRawCertData()); CertificateRSA = new RSAManaged( cert.RSA.KeySize); CertificateRSA.ImportParameters( cert.RSA.ExportParameters(false)); } }
private void ImportPrivateKey(X509Certificate certificate, CspParameters cspParams) { RSACryptoServiceProvider rsaCsp = certificate.RSA as RSACryptoServiceProvider; if (rsaCsp != null) { if (rsaCsp.PublicOnly) { return; } RSACryptoServiceProvider csp = new RSACryptoServiceProvider(cspParams); csp.ImportParameters(rsaCsp.ExportParameters(true)); csp.PersistKeyInCsp = true; return; } RSAManaged rsaMng = certificate.RSA as RSAManaged; if (rsaMng != null) { if (rsaMng.PublicOnly) { return; } RSACryptoServiceProvider csp = new RSACryptoServiceProvider(cspParams); csp.ImportParameters(rsaMng.ExportParameters(true)); csp.PersistKeyInCsp = true; return; } DSACryptoServiceProvider dsaCsp = certificate.DSA as DSACryptoServiceProvider; if (dsaCsp != null) { if (dsaCsp.PublicOnly) { return; } DSACryptoServiceProvider csp = new DSACryptoServiceProvider(cspParams); csp.ImportParameters(dsaCsp.ExportParameters(true)); csp.PersistKeyInCsp = true; } }
private RSA getClientCertRSA(RSA privKey) { RSAParameters rsaParams = new RSAParameters(); RSAParameters privateParams = privKey.ExportParameters(true); // for RSA m_publickey contains 2 ASN.1 integers // the modulus and the public exponent ASN1 pubkey = new ASN1(this.Context.ClientSettings.Certificates[0].GetPublicKey()); ASN1 modulus = pubkey [0]; if ((modulus == null) || (modulus.Tag != 0x02)) { return(null); } ASN1 exponent = pubkey [1]; if (exponent.Tag != 0x02) { return(null); } rsaParams.Modulus = this.getUnsignedBigInteger(modulus.Value); rsaParams.Exponent = exponent.Value; // Set private key parameters rsaParams.D = privateParams.D; rsaParams.DP = privateParams.DP; rsaParams.DQ = privateParams.DQ; rsaParams.InverseQ = privateParams.InverseQ; rsaParams.P = privateParams.P; rsaParams.Q = privateParams.Q; // BUG: MS BCL 1.0 can't import a key which // isn't the same size as the one present in // the container. int keySize = (rsaParams.Modulus.Length << 3); RSAManaged rsa = new RSAManaged(keySize); rsa.ImportParameters(rsaParams); return((RSA)rsa); }
/// <inheritdoc/> public ICryptographicKey ImportKeyPair(byte[] keyBlob, CryptographicPrivateKeyBlobType blobType = CryptographicPrivateKeyBlobType.Pkcs8RawPrivateKeyInfo) { Requires.NotNull(keyBlob, "keyBlob"); var parameters = KeyFormatter.GetFormatter(blobType) .Read(keyBlob) .ComputeFullPrivateKeyData(); if (!CapiKeyFormatter.IsCapiCompatible(parameters)) { // Try to make it CAPI compatible since it's faster on desktop, // and the only thing that could possibly work on wp8. RSAParameters adjustedParameters = KeyFormatter.NegotiateSizes(parameters); if (CapiKeyFormatter.IsCapiCompatible(adjustedParameters)) { parameters = adjustedParameters; } } Platform.RSA rsa; if (CapiKeyFormatter.IsCapiCompatible(parameters)) { rsa = new Platform.RSACryptoServiceProvider(); } else { #if DESKTOP rsa = new RSAManaged(); #else // Throw the exception explaining the problem. CapiKeyFormatter.VerifyCapiCompatibleParameters(parameters); // Make it obvious to the compiler that the buck stops here. // er... on the line above. throw new NotSupportedException(); #endif } rsa.ImportParameters(KeyFormatter.ToPlatformParameters(parameters)); return(new RsaCryptographicKey(rsa, this.algorithm)); }
public void ProcessCommon(bool sendLength) { // Compute pre master secret var preMasterSecret = Context.Negotiating.Cipher.CreatePremasterSecret(); // Create a new RSA key RSA rsa = null; if (Context.ServerSettings.ServerKeyExchange) { // this is the case for "exportable" ciphers rsa = new RSAManaged(); rsa.ImportParameters(Context.ServerSettings.RsaParameters); } else { rsa = Context.ServerSettings.CertificateRSA; } // Encrypt premaster_sercret var formatter = new RSAPKCS1KeyExchangeFormatter(rsa); // Write the preMasterSecret encrypted var buffer = formatter.CreateKeyExchange(preMasterSecret); if (sendLength) { Write((short)buffer.Length); } Write(buffer); // Create master secret Context.Negotiating.Cipher.ComputeMasterSecret(preMasterSecret); // Create keys Context.Negotiating.Cipher.ComputeKeys(); // Clear resources rsa.Clear(); }
private void PublicKeySign(string input, RSAPublicKey _publicKey, RSAPrivateKey _privateKey) { byte[] inputData = Encoding.UTF8.GetBytes(input); SHA1Managed sha1 = new SHA1Managed(); DateTime d1 = DateTime.Now; byte[] signature = RSAManaged.Sign(inputData, _publicKey, sha1); TimeSpan t1 = DateTime.Now - d1; Console.WriteLine("公钥签名用时:{0}", t1); DateTime d2 = DateTime.Now; bool result = RSAManaged.Verify(inputData, _privateKey, sha1, signature); TimeSpan t2 = DateTime.Now - d2; Console.WriteLine("私钥验证用时:{0}", t2); sha1.Clear(); Console.WriteLine(string.Format("私钥验证结果:{0}", result)); Console.WriteLine(); }
private void PublicKeyEncrypt(string input, RSAPublicKey _publicKey, RSAPrivateKey _privateKey) { byte[] inputData = Encoding.UTF8.GetBytes(input); DateTime d1 = DateTime.Now; byte[] inputDateEnc = RSAManaged.Encrypt(inputData, _publicKey); TimeSpan t1 = DateTime.Now - d1; Console.WriteLine("公钥加密用时:{0}", t1); DateTime d2 = DateTime.Now; byte[] inputDataDec = RSAManaged.Decrypt(inputDateEnc, _privateKey); TimeSpan t2 = DateTime.Now - d2; Console.WriteLine("私钥解密用时:{0}", t2); string inputDec = Encoding.UTF8.GetString(inputDataDec, 0, inputDataDec.Length); Console.WriteLine(string.Format("私钥解密结果:{0}", inputDec)); Console.WriteLine(); }
/// <inheritdoc/> public ICryptographicKey ImportKeyPair(byte[] keyBlob, CryptographicPrivateKeyBlobType blobType = CryptographicPrivateKeyBlobType.Pkcs8RawPrivateKeyInfo) { Requires.NotNull(keyBlob, "keyBlob"); var parameters = KeyFormatter.GetFormatter(blobType).Read(keyBlob); Platform.RSA rsa; if (CapiKeyFormatter.IsCapiCompatible(parameters)) { rsa = new Platform.RSACryptoServiceProvider(); } else { #if DESKTOP rsa = new RSAManaged(); #else CapiKeyFormatter.VerifyCapiCompatibleParameters(parameters); throw new NotSupportedException(); #endif } rsa.ImportParameters(KeyFormatter.ToPlatformParameters(parameters)); return(new RsaCryptographicKey(rsa, this.algorithm)); }
/// <summary> /// Handles incoming packet. /// </summary> /// <param name="packet">Incoming packet.</param> protected override void Handle(Packet packet) { Logger.WriteLine(Source.OuterNetwork, "Received: {0}", packet.ToString()); if (!CacheServiceConnection.Active) // validate if login service is active { Send(LoginFailed.ToPacket(UserAuthenticationResponseType.ServerMaintenance)); UserConnectionsListener.CloseActiveConnection(this); return; } if (QueuedRequestsPool.HasRequest(this, true)) // validate if user is awaiting response from cache service { return; } switch (packet.FirstOpcode) { case 0x07: { Send(ResponseAuthGameGuard.Static); return; } case 0x00: { m_RSADecryptor = new RSAManaged(); m_RSADecryptor.ImportParameters(UserConnectionsListener.PrivateKey); // get login and password unsafe { byte[] bytes = new byte[0x80]; fixed(byte *buf = bytes, src = packet.GetBuffer()) L2Buffer.Copy(src, 0x01, buf, 0x00, 0x80); fixed(byte *buf = m_RSADecryptor.DecryptValue(bytes)) { L2Buffer.GetTrimmedString(buf, 0x03, ref Login, 0x0e); L2Buffer.GetTrimmedString(buf, 0x11, ref Password, 0x10); } } // validate user login if (!Utils.IsValidUserLogin(Login)) { Send(LoginFailed.ToPacket(UserAuthenticationResponseType.UserOrPasswordWrong)); return; } //Password = Utils.HashPassword(Password); Session.AccountName = Login; Logger.WriteLine(Session.ToString()); long requestId = long.MinValue; // request cache to auth user if (QueuedRequestsPool.Enqueue(this, ref requestId)) { CacheServiceConnection.Send(new UserAuthenticationRequest(requestId, Login, Password, Session.ID).ToPacket()); } else { Logger.WriteLine(Source.InnerNetwork, "Failed to send UserAuthenticationRequest to cache service, request was not enqueued by QueuedRequestsPool ?..."); Send(LoginFailed.ToPacket(UserAuthenticationResponseType.SystemError)); UserConnectionsListener.CloseActiveConnection(this); } return; } case 0x05: { int login1 = packet.ReadInt(); int login2 = packet.ReadInt(); if (login1 != Session.Login1 || login2 != Session.Login2) { Logger.WriteLine(Source.OuterNetwork, "Invalid UserSession data: {0}. BAN!", Session.ToString()); CacheServiceConnection.Send(new UnCacheUser(Session.ID).ToPacket()); UserConnectionsListener.CloseActiveConnection(this); } else { long requestID = long.MinValue; if (QueuedRequestsPool.Enqueue(this, ref requestID)) { CacheServiceConnection.Send(new WorldsListRequest(requestID).ToPacket()); } else { Logger.WriteLine(Source.InnerNetwork, "Failed to send WorldsListRequest to cache service, request was not enqueued by QueuedRequestsPool ?..."); UserConnectionsListener.CloseActiveConnection(this); } } return; } case 0x02: { // skip not needed data packet.MoveOffset(8); long requestID = long.MinValue; if (QueuedRequestsPool.Enqueue(this, ref requestID)) { CacheServiceConnection.Send(new JoinWorldRequest(requestID, Session.ID, packet.ReadByte()).ToPacket()); } else { Logger.WriteLine(Source.InnerNetwork, "Failed to send JionWorldRequest to cache service, request was not enqueued by QueuedRequestsPool ?..."); UserConnectionsListener.CloseActiveConnection(this); } return; } } Logger.WriteLine(Source.OuterNetwork, "Unknown packet received: {0}", packet.ToString()); UserConnectionsListener.CloseActiveConnection(this); }
public void FixtureSetup() { key = new RSAManaged(384); }
private bool VerifyCounterSignature(PKCS7.SignerInfo cs, byte[] signature) { if (cs.Version == 1) { string str = null; ASN1 asn = null; for (int i = 0; i < cs.AuthenticatedAttributes.Count; i++) { ASN1 asn2 = (ASN1)cs.AuthenticatedAttributes[i]; string key = ASN1Convert.ToOid(asn2[0]); if (key != null) { if (__f__switch_map3 == null) { Dictionary <string, int> dictionary = new Dictionary <string, int>(3) { { "1.2.840.113549.1.9.3", 0 }, { "1.2.840.113549.1.9.4", 1 }, { "1.2.840.113549.1.9.5", 2 } }; __f__switch_map3 = dictionary; } if (__f__switch_map3.TryGetValue(key, out int num2)) { switch (num2) { case 0: str = ASN1Convert.ToOid(asn2[1][0]); break; case 1: asn = asn2[1][0]; break; case 2: this.timestamp = ASN1Convert.ToDateTime(asn2[1][0]); break; } } } } if (str != "1.2.840.113549.1.7.1") { return(false); } if (asn == null) { return(false); } string hashName = null; switch (asn.Length) { case 0x10: hashName = "MD5"; break; case 20: hashName = "SHA1"; break; } HashAlgorithm hash = HashAlgorithm.Create(hashName); if (asn.CompareValue(hash.ComputeHash(signature))) { byte[] buffer = cs.Signature; ASN1 asn3 = new ASN1(0x31); IEnumerator enumerator = cs.AuthenticatedAttributes.GetEnumerator(); try { while (enumerator.MoveNext()) { ASN1 current = (ASN1)enumerator.Current; asn3.Add(current); } } finally { if (enumerator is IDisposable disposable) { disposable.Dispose(); } } byte[] hashValue = hash.ComputeHash(asn3.GetBytes()); string issuerName = cs.IssuerName; byte[] serialNumber = cs.SerialNumber; X509CertificateCollection.X509CertificateEnumerator enumerator2 = this.coll.GetEnumerator(); try { while (enumerator2.MoveNext()) { X509Certificate current = enumerator2.Current; if (this.CompareIssuerSerial(issuerName, serialNumber, current) && (current.PublicKey.Length > buffer.Length)) { RSACryptoServiceProvider rSA = (RSACryptoServiceProvider)current.RSA; RSAManaged rsa = new RSAManaged(); rsa.ImportParameters(rSA.ExportParameters(false)); if (PKCS1.Verify_v15(rsa, hash, hashValue, buffer, true)) { this.timestampChain.LoadCertificates(this.coll); return(this.timestampChain.Build(current)); } } } } finally { if (enumerator2 is IDisposable disposable2) { disposable2.Dispose(); } } } } return(false); }
private bool VerifyCounterSignature (PKCS7.SignerInfo cs, byte[] signature) { // SEQUENCE { // INTEGER 1 if (cs.Version != 1) return false; // SEQUENCE { // SEQUENCE { string contentType = null; ASN1 messageDigest = null; for (int i=0; i < cs.AuthenticatedAttributes.Count; i++) { // SEQUENCE { // OBJECT IDENTIFIER ASN1 attr = (ASN1) cs.AuthenticatedAttributes [i]; string oid = ASN1Convert.ToOid (attr[0]); switch (oid) { case "1.2.840.113549.1.9.3": // contentType contentType = ASN1Convert.ToOid (attr[1][0]); break; case "1.2.840.113549.1.9.4": // messageDigest messageDigest = attr[1][0]; break; case "1.2.840.113549.1.9.5": // SEQUENCE { // OBJECT IDENTIFIER // signingTime (1 2 840 113549 1 9 5) // SET { // UTCTime '030124013651Z' // } // } timestamp = ASN1Convert.ToDateTime (attr[1][0]); break; default: break; } } if (contentType != PKCS7.Oid.data) return false; // verify message digest if (messageDigest == null) return false; // TODO: must be read from the ASN.1 structure string hashName = null; switch (messageDigest.Length) { case 16: hashName = "MD5"; break; case 20: hashName = "SHA1"; break; } HashAlgorithm ha = HashAlgorithm.Create (hashName); if (!messageDigest.CompareValue (ha.ComputeHash (signature))) return false; // verify signature byte[] counterSignature = cs.Signature; // change to SET OF (not [0]) as per PKCS #7 1.5 ASN1 aa = new ASN1 (0x31); foreach (ASN1 a in cs.AuthenticatedAttributes) aa.Add (a); byte[] p7hash = ha.ComputeHash (aa.GetBytes ()); // we need to try all certificates string issuer = cs.IssuerName; byte[] serial = cs.SerialNumber; foreach (X509Certificate x509 in coll) { if (CompareIssuerSerial (issuer, serial, x509)) { if (x509.PublicKey.Length > counterSignature.Length) { RSACryptoServiceProvider rsa = (RSACryptoServiceProvider) x509.RSA; // we need to HACK around bad (PKCS#1 1.5) signatures made by Verisign Timestamp Service // and this means copying stuff into our own RSAManaged to get the required flexibility RSAManaged rsam = new RSAManaged (); rsam.ImportParameters (rsa.ExportParameters (false)); if (PKCS1.Verify_v15 (rsam, ha, p7hash, counterSignature, true)) { timestampChain.LoadCertificates (coll); return (timestampChain.Build (x509)); } } } } // no certificate can verify this signature! return false; }
private bool VerifyCounterSignature(PKCS7.SignerInfo cs, byte[] signature) { if (cs.Version != 1) { return(false); } string a = null; ASN1 asn = null; int i = 0; while (i < cs.AuthenticatedAttributes.Count) { ASN1 asn2 = (ASN1)cs.AuthenticatedAttributes[i]; string text = ASN1Convert.ToOid(asn2[0]); string text2 = text; switch (text2) { case "1.2.840.113549.1.9.3": a = ASN1Convert.ToOid(asn2[1][0]); break; case "1.2.840.113549.1.9.4": asn = asn2[1][0]; break; case "1.2.840.113549.1.9.5": this.timestamp = ASN1Convert.ToDateTime(asn2[1][0]); break; } IL_FC: i++; continue; goto IL_FC; } if (a != "1.2.840.113549.1.7.1") { return(false); } if (asn == null) { return(false); } string hashName = null; int length = asn.Length; if (length != 16) { if (length == 20) { hashName = "SHA1"; } } else { hashName = "MD5"; } HashAlgorithm hashAlgorithm = HashAlgorithm.Create(hashName); if (!asn.CompareValue(hashAlgorithm.ComputeHash(signature))) { return(false); } byte[] signature2 = cs.Signature; ASN1 asn3 = new ASN1(49); foreach (object obj in cs.AuthenticatedAttributes) { ASN1 asn4 = (ASN1)obj; asn3.Add(asn4); } byte[] hashValue = hashAlgorithm.ComputeHash(asn3.GetBytes()); string issuerName = cs.IssuerName; byte[] serialNumber = cs.SerialNumber; foreach (X509Certificate x509Certificate in this.coll) { if (this.CompareIssuerSerial(issuerName, serialNumber, x509Certificate) && x509Certificate.PublicKey.Length > signature2.Length) { RSACryptoServiceProvider rsacryptoServiceProvider = (RSACryptoServiceProvider)x509Certificate.RSA; RSAManaged rsamanaged = new RSAManaged(); rsamanaged.ImportParameters(rsacryptoServiceProvider.ExportParameters(false)); if (PKCS1.Verify_v15(rsamanaged, hashAlgorithm, hashValue, signature2, true)) { this.timestampChain.LoadCertificates(this.coll); return(this.timestampChain.Build(x509Certificate)); } } } return(false); }