private static RsaKeyPair GetRsaKeyPair(RSA rsa, string comment) { const string sshrsa = "ssh-rsa"; // Use Bouncy castle's pem reader to get the modulus and exponent as a byte array PemReader reader = new PemReader(new StringReader(rsa.PublicKeyAsPEM)); RsaKeyParameters r = (RsaKeyParameters)reader.ReadObject(); byte[] sshrsa_bytes = Encoding.Default.GetBytes(sshrsa); byte[] n = r.Modulus.ToByteArray(); byte[] e = r.Exponent.ToByteArray(); Buffer buf = new Buffer(sshrsa_bytes.Length + 4 + e.Length + 4 + n.Length + 4); // Add the bytes buf.add(sshrsa_bytes, e, n); // Encode in Base64 string buffer64 = buf.AsBase64String(); // Set the base DTO RsaKeyPair pair = new RsaKeyPair() { PublicSSHKey = string.Format("ssh-rsa {0} {1}", buffer64, comment), PublicKeyAsPEM = rsa.PublicKeyAsPEM, PrivateKeyAsPEM = rsa.PrivateKeyAsPEM, // Later add parameters if required. }; return pair; }
public OpenSSL.Crypto.RSA getKeyPair2() { OpenSSL.Crypto.RSA keypair = new OpenSSL.Crypto.RSA(); keypair.GenerateKeys(1024, 65537, null, null); return(keypair); }
public bool VerifyCryptographicallyOpenSsl(byte[] signatureData, byte[] signedData, byte[] keyData) { RSAParameters rsaParameters = GetRsaParameters(keyData); if (rsaParameters.Modulus.Length != signatureData.Length) { return(false); } using (var rsa = new RSA()) { rsa.PublicModulus = BigNumber.FromArray(rsaParameters.Modulus); rsa.PublicExponent = BigNumber.FromArray(rsaParameters.Exponent); byte[] locallyFormedSig = rsa.PublicDecrypt(signatureData, RSA.Padding.PKCS1); byte[] hashOfSignedData = GetHashOfSignedData(signedData); Console.WriteLine(hashOfSignedData.ToHexString()); Console.WriteLine(locallyFormedSig.Skip(15).ToArray().ToHexString()); //File.AppendAllText("C:\\combonsis.txt", "Hash of signed:" + System.Environment.NewLine); //File.AppendAllText("C:\\combonsis.txt", hashOfSignedData.ToHexString() + System.Environment.NewLine); //File.AppendAllText("C:\\combonsis.txt", "Locallyformed:" + System.Environment.NewLine); //File.AppendAllText("C:\\combonsis.txt", locallyFormedSig.Skip(19).ToArray().ToHexString() + System.Environment.NewLine); return(true); } }
public static byte[] RsaEncrypt(byte[] toEncrypt) { using (OpenSSL.Core.BIO bio = new OpenSSL.Core.BIO(PublicKey)) using (RSA rsa = RSA.FromPublicKey(bio)) { return(rsa.PublicEncrypt(toEncrypt, RSA.Padding.None)); } }
/// <summary> /// Generates the Rsa keys accordingly. /// </summary> /// <param name="bits"></param> /// <param name="comment"></param> /// <returns></returns> public static RsaKeyPair GenerateRsaKeyPair(int bits, string comment) { // Generate keys using OpenSSL RSA generator. RSA rsa = new RSA(); rsa.GenerateKeys(bits, 65537, null, null); return GetRsaKeyPair(rsa, comment); }
private PacketOut CreateAESPacket() { PacketOut o = new PacketOut(71); m_cRSA = new OpenSSL.Crypto.RSA(); m_cRSA.GenerateKeys(1024, 65537, null, null); o.WriteInt32(m_cRSA.PublicKeyAsPEM.Length); o.FillString(m_cRSA.PublicKeyAsPEM, m_cRSA.PublicKeyAsPEM.Length); return(o); }
public string RSAPrivateEncrypt(string keyFile, string rawData) { string strEncryptedData = string.Empty; using (OpenSSL.Core.BIO bioPrivateKey = OpenSSL.Core.BIO.File(keyFile, "r")) { using (OpenSSL.Crypto.RSA rsaServiceProvider = OpenSSL.Crypto.RSA.FromPrivateKey(bioPrivateKey)) { byte[] byteEncryptedData = rsaServiceProvider.PrivateEncrypt(new UTF8Encoding().GetBytes(rawData), OpenSSL.Crypto.RSA.Padding.PKCS1); strEncryptedData = BitConverter.ToString(byteEncryptedData).Replace("-", ""); } } return(strEncryptedData); }
public void changeKey(object sender, EventArgs e) { // AsymmetricCipherKeyPair keyPair = getKeyPair(); // PrivateKeyInfo pkInfo = PrivateKeyInfoFactory.CreatePrivateKeyInfo(keyPair.Private); // StringBuilder builder=new StringBuilder(); // builder.AppendLine("-----BEGIN PRIVATE KEY-----"); // builder.AppendLine(Convert.ToBase64String(pkInfo.GetDerEncoded())); // builder.AppendLine("-----END PRIVATE KEY-----"); OpenSSL.Crypto.RSA keyPair = getKeyPair2(); string privateKey = keyPair.PrivateKeyAsPEM; MemoryStream ms = new MemoryStream(); TextWriter tw = new StreamWriter(ms); tw.Write(privateKey); tw.Flush(); byte[] bytes = ms.ToArray(); ms.Close(); Debug.WriteLine("I Am HERE"); Response.Clear(); Response.ContentType = "application/force-download"; Response.AddHeader("content-disposition", "attachment; filename=key.txt"); Response.BinaryWrite(bytes); HttpContext.Current.Response.Flush(); // Sends all currently buffered output to the client. HttpContext.Current.Response.SuppressContent = true; // Gets or sets a value indicating whether to send HTTP content to the client. HttpContext.Current.ApplicationInstance.CompleteRequest(); // Response.End(); // var encrypted = RsaEncryptWithPrivate(challenge, builder.ToString()); /* SubjectPublicKeyInfo info = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(keyPair.Public); * builder = new StringBuilder(); * builder.AppendLine("-----BEGIN PUBLIC KEY-----"); * builder.AppendLine(Convert.ToBase64String(info.GetDerEncoded())); * builder.AppendLine("-----END PUBLIC KEY-----");*/ string pubKey = keyPair.PublicKeyAsPEM; KeyManager.changeKey(userID, pubKey); string eText = RsaEncryptWithPrivate("Hello", privateKey); Debug.WriteLine(RsaDecryptWithPublic(eText, pubKey)); }
private PacketOut CreateAESPacket() { PacketOut o = new PacketOut( 71 ); m_cRSA = new OpenSSL.Crypto.RSA(); m_cRSA.GenerateKeys( 1024, 65537, null, null ); o.WriteInt32( m_cRSA.PublicKeyAsPEM.Length ); o.FillString( m_cRSA.PublicKeyAsPEM, m_cRSA.PublicKeyAsPEM.Length ); return o; }
/* The certificate request protocol is performed over HTTPS. The request is an HTTP POST with the following properties: o If authentication is required, there is a URL parameter of "password" and "username" containing the user's name and password in the clear (hence the need for HTTPS) o The body is of content type "application/pkcs10", as defined in [RFC2311]. o The Accept header contains the type "application/pkix-cert", indicating the type that is expected in the response. */ /// <summary> /// Used to generate certificate request /// </summary> public bool CertificateSigningRequest(string enrollment_url) { OpenSSL.X509.X509Request CertificateRequest = null; string sLocalCertFilename; sLocalCertFilename = m_ReloadConfig.IMSI == "" ? "VNODE_" + m_ReloadConfig.ListenPort.ToString() : m_ReloadConfig.IMSI; string cert_file = sLocalCertFilename + ".der"; string privateKey_file = sLocalCertFilename + ".key"; OpenSSL.Crypto.RSA rsa = null; byte[] byteCSR = null; byte[] privateKey = null; if (byteCSR == null || byteCSR.Length == 0) { try { if (m_ReloadConfig.Logger != null) m_ReloadConfig.Logger(ReloadGlobals.TRACEFLAGS.T_INFO, String.Format("Generate new Certificate Signing Request, please wait..")); //new openssl certificate request CertificateRequest = new OpenSSL.X509.X509Request(); /* private certificate configuration */ String CN = "reload:" + ReloadGlobals.IPAddressFromHost(m_ReloadConfig, ReloadGlobals.HostName).ToString() + ":" + m_ReloadConfig.ListenPort; //String CN = TSystems.RELOAD.Enroll.EnrollmentSettings.Default.CN; String Country = TSystems.RELOAD.Enroll.EnrollmentSettings.Default.Country; String Locality = TSystems.RELOAD.Enroll.EnrollmentSettings.Default.Locality; String State = TSystems.RELOAD.Enroll.EnrollmentSettings.Default.State; String Organization = TSystems.RELOAD.Enroll.EnrollmentSettings.Default.Organization; String Unit = TSystems.RELOAD.Enroll.EnrollmentSettings.Default.Unit; CertificateRequest.Subject = new OpenSSL.X509.X509Name("/CN=" + CN + "/C=" + Country + "/L=" + Locality + "/ST=" + State + "/O=" + Organization + "/OU=" + Unit); rsa = new OpenSSL.Crypto.RSA(); //TODO: remove 0x10021 ? //rsa.GenerateKeys(2048, 0x10021, null, null); // why 0x10021? // use 4th fermat number as public key exponent rsa.GenerateKeys(2048, 0x10001, null, null); CertificateRequest.PublicKey = OpenSSL.Crypto.CryptoKey.FromPublicKey(rsa.PublicKeyAsPEM, null); OpenSSL.Crypto.CryptoKey privatKey = OpenSSL.Crypto.CryptoKey.FromPrivateKey(rsa.PrivateKeyAsPEM, null); // signes REQ by using SHA1 and the private key CertificateRequest.Sign(privatKey, OpenSSL.Crypto.MessageDigest.SHA1); // Log for testing reasons in Wireshark //File.WriteAllText("C:\\Users\\sleonhardt\\Desktop\\ServerPemKey.key", rsa.PrivateKeyAsPEM); // PEM to DER workaround string[] pemString = CertificateRequest.PEM.Split('\n'); string s = ""; for (int i = 1; i < pemString.Length - 2; i++) s += pemString[i] + "\r\n"; byteCSR = Convert.FromBase64String(s); pemString = rsa.PrivateKeyAsPEM.Split('\n'); s = ""; for (int i = 1; i < pemString.Length - 2; i++) s += pemString[i] + "\r\n"; privateKey = Convert.FromBase64String(s); //save Certificate Signing Request and private Key to disk - unsafe, do not use //File.WriteAllBytes(cert_file, byteCSR); //File.WriteAllBytes(privateKey_file, privateKey); if (m_ReloadConfig.Logger != null) m_ReloadConfig.Logger(ReloadGlobals.TRACEFLAGS.T_INFO, String.Format("... ready.")); } catch (Exception ex) { if (m_ReloadConfig.Logger != null) m_ReloadConfig.Logger(ReloadGlobals.TRACEFLAGS.T_ERROR, String.Format("Generation of CSR failed {0}", ex.ToString())); } } try { if (enrollment_url != null) { HttpWebRequest httpWebPost; httpWebPost = (HttpWebRequest)WebRequest.Create(new Uri(enrollment_url)); /* As of RELOAD draft, use POST */ httpWebPost.Method = "POST"; httpWebPost.Accept = "application/pkix-cert"; httpWebPost.ContentType = "application/pkcs10"; #if !WINDOWS_PHONE // Additional HttpWebRequest parameters are not supported httpWebPost.Timeout = ReloadGlobals.WEB_REQUEST_TIMEOUT; //httpWebPost.AllowWriteStreamBuffering = true; //httpWebPost.SendChunked = true; httpWebPost.ContentLength = byteCSR.Length; httpWebPost.ProtocolVersion = HttpVersion.Version10; #endif httpWebPost.UserAgent = "T-Systems RELOAD MDI Appl 1.0"; /* this is a sample post request of Marcs Testformular at https://reloadnet-reload.implementers.org/enrollment -----------------------------265001916915724 Content-Disposition: form-data; name="username" Thomas -----------------------------265001916915724 Content-Disposition: form-data; name="password" ********** -----------------------------265001916915724 Content-Disposition: form-data; name="nodeids" 1 -----------------------------265001916915724 Content-Disposition: form-data; name="csr"; filename="blob" Content-Type: application/pkcs10 */ /* private enrollment server configuration */ string username = TSystems.RELOAD.Enroll.EnrollmentSettings.Default.Username; string password = TSystems.RELOAD.Enroll.EnrollmentSettings.Default.Password; string boundary = "----------------------------" + DateTime.Now.Ticks.ToString("x"); httpWebPost.ContentType = "multipart/form-data; boundary=" + boundary; byte[] boundaryclosebytes = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "--\r\n"); string formdataTemplate = "\r\n--" + boundary + "\r\nContent-Disposition: form-data; name=\"username\"\r\n\r\n{0}\r\n--" + boundary + "\r\nContent-Disposition: form-data; name=\"password\"\r\n\r\n{1}\r\n--" + boundary + "\r\nContent-Disposition: form-data; name=\"nodeids\"\r\n\r\n1"; string formitem = string.Format(formdataTemplate, username, password); byte[] formitembytes = System.Text.Encoding.UTF8.GetBytes(formitem); Stream memStream = new System.IO.MemoryStream(); BinaryWriter writer = new BinaryWriter(memStream); // send CSR to Enrollment Server writer.Write(formitembytes); formitem = "\r\n--" + boundary + "\r\nContent-Disposition: form-data; name=\"csr\"; filename=\"blob\"\r\nContent-Type: application/pkcs10\r\n\r\n"; formitembytes = System.Text.Encoding.UTF8.GetBytes(formitem); writer.Write(formitembytes); writer.Write(byteCSR); writer.Write(boundaryclosebytes); httpWebPost.ContentLength = memStream.Length; Stream requestStream = httpWebPost.GetRequestStream(); memStream.Position = 0; memStream.CopyTo(requestStream); //using (Stream file = File.OpenWrite("C:\\Windows\\Temp\\test.dat")) //{ // memStream.Position = 0; // memStream.CopyTo(file); //} writer.Close(); HttpWebResponse httpPostResponse = null; //Send Web-Request and receive a Web-Response try { httpPostResponse = (HttpWebResponse)httpWebPost.GetResponse(); } catch (WebException ex) { m_ReloadConfig.Logger(ReloadGlobals.TRACEFLAGS.T_ERROR, "CSR returns:" + ex.Message); } if (httpPostResponse != null) { // use .net classes for Certificate Response X509Certificate2 myCert; byte[] byteCert = ReloadGlobals.ConvertNonSeekableStreamToByteArray(httpPostResponse.GetResponseStream()); myCert = new X509Certificate2(byteCert); if (privateKey != null) { byte[] keyBuffer = Helpers.GetBytesFromPEM(rsa.PrivateKeyAsPEM, PemStringType.RsaPrivateKey); RSACryptoServiceProvider prov = Crypto.DecodeRsaPrivateKey(keyBuffer); myCert.PrivateKey = prov; if (Utils.X509Utils.VerifyCertificate(myCert, m_ReloadConfig.RootCertificate)) m_ReloadConfig.Logger(ReloadGlobals.TRACEFLAGS.T_TOPO, String.Format("Verified certificate!")); m_ReloadConfig.ReloadLocalNetCertStorage.Add(myCert, true); // Add client certificate to trusted root certificate store //X509Store store = new X509Store(StoreName.My, StoreLocation.CurrentUser); //store.Open(OpenFlags.ReadWrite); //store.Add(myCert); //store.Close(); m_ReloadConfig.Logger(ReloadGlobals.TRACEFLAGS.T_TOPO, String.Format("Successfully received certificate, Issuer: {0}", myCert.Issuer)); return true; } } } } catch (Exception ex) { m_ReloadConfig.Logger(ReloadGlobals.TRACEFLAGS.T_ERROR, String.Format("CSR failed {0}", ex.ToString())); } return false; }
//Gönder butonu private void btnSend_Click(object sender, EventArgs e) { OpenSSL.Crypto.RSA rsa = new OpenSSL.Crypto.RSA(); rsa.GenerateKeys(1024, 65537, null, null); File.WriteAllText("MasterPrivateKey.pem", rsa.PrivateKeyAsPEM); File.WriteAllText("MasterPublicKey.pem", rsa.PublicKeyAsPEM); Packet packet = new Packet(); packet.message = txMessage.Text; if (!txMessage.Text.StartsWith("@"))// Mesaj @ işareti ile başlamıyorsa broadcast yapılacaktır. { packet.path = "broadcast"; for (int i = 1; i < clientSockets.Count + 1; i++)//Broadcast yapılması için dictionarydeki tüm clientlara mesaj gönderilmektedir. { //Class serialize ile binary formata dönüştürüldü. using (NetworkStream ns = new NetworkStream(clientSockets[i]))//Tüm soketlere gönderilmesi için clientSockets[i] işlemi gerçekleştirildi. { using (MemoryStream ms = new MemoryStream()) { BinaryFormatter formatter = new BinaryFormatter(); formatter.Serialize(ms, packet); byte[] buf = ms.ToArray(); ns.Write(buf, 0, buf.Length);//Serialize edilmiş class gönderilir } } } listMessages.Items.Add("Broadcast : " + txMessage.Text); } else//mesaj @ işareti ile başlıyorsa tek clienta yönlendirme yapılacaktır. { packet.message = txMessage.Text; try { string[] words = packet.message.Split(' '); packet.receiver_ID = Convert.ToInt32(words[0].Substring(1)); //words[0]'da hedef client ıd bulunur. Substring ile başındaki @ işareti kaldırılarak atanır. if (clientSockets.ContainsKey(packet.receiver_ID)) // Client var mı diye kontrol ediyor { packet.path = "server-client"; packet.message = words[1];//@ işaretinden sonraki kelime alınır. Sonrasındaki kelimeler aşağıdaki for döngüsünde boşluklu şekilde eklenir. for (int i = 2; i < words.Length - 1; i++) { packet.message += " " + words[i]; // words[1] -> @'ten sonrasına denk geliyor, words[2] ilkine boşluk gelmemesi için döngüden önce yapılıyor } using (NetworkStream ns = new NetworkStream(clientSockets[packet.receiver_ID])) { using (MemoryStream ms = new MemoryStream()) { BinaryFormatter formatter = new BinaryFormatter(); formatter.Serialize(ms, packet); byte[] buf = ms.ToArray(); ns.Write(buf, 0, buf.Length); } } listMessages.Items.Add("Client " + packet.receiver_ID + " : " + txMessage.Text); } else// Client dictionary array'inde yoksa { listMessages.Items.Add("There is no such client"); } } catch (Exception ex)// @ ifadesinden sonra sayı dışında farklı veri girilirse buraya girer. { MessageBox.Show("You should write like @[client_id] [message] this format!"); } } txMessage.Text = string.Empty; }