<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by edayardim on Medium]]></title>
        <description><![CDATA[Stories by edayardim on Medium]]></description>
        <link>https://medium.com/@edayardiim?source=rss-c511b4d4715d------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*Hxho66gQaDneEoL0v92cNg.jpeg</url>
            <title>Stories by edayardim on Medium</title>
            <link>https://medium.com/@edayardiim?source=rss-c511b4d4715d------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 20 Nov 2026 15:51:31 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@edayardiim/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[WebSockets in Rust Actix Framework]]></title>
            <link>https://towardsdev.com/websockets-in-rust-actix-framework-10686a8fa9bd?source=rss-c511b4d4715d------2</link>
            <guid isPermaLink="false">https://medium.com/p/10686a8fa9bd</guid>
            <category><![CDATA[rust]]></category>
            <category><![CDATA[websocket]]></category>
            <dc:creator><![CDATA[edayardim]]></dc:creator>
            <pubDate>Tue, 20 Sep 2022 20:17:29 GMT</pubDate>
            <atom:updated>2022-09-28T21:35:25.831Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>WHAT </strong>is Web-Socket</p><p>The Web Socket API is cutting-edge technology, providing full duplex communication between the user’s browser and a server. With this API, you can send a message to a server and receive a message over a single TCP connection. It provides easier real-time data transfer because the server can send content to you without any request from you!</p><p><strong>Advantages of Web Socket</strong></p><p><strong>Bidirectional</strong></p><p>In HTTP, request is initiated by the client, then the response is operated and returned to the client by the server. In web-socket client and server do not need pre-defined request/response scheme — except handshake. After handshake, either the client or server can send a message.</p><p><strong>Full Duplex</strong></p><p>In HTTP, at the same time, either client can send a request, or the server can send a response to the client. Full duplex communication allows that server and client can talk to each other separately.</p><p><strong>Single TCP Connection</strong></p><p>In general, a new TCP connection is created for an HTTP request, after getting response this connection terminated. In Web Socket, the connection is kept alive over the same TCP for the lifecycle of either the client or server.</p><p><strong>HOW </strong>is Web-Socket</p><p>Using Rust’s Actix framework, we can work with a web socket server. Moreover, we can handle requests and response using Actix’s actor system. At the end of the project, we are going to create an HTTP endpoint for clients to connect to the web-socket within the topic they want to join.</p><p>I will explain step by step how to implement in Actix.</p><p><strong>First step:</strong></p><p>Define a struct for Web Socket object.</p><pre>pub struct WebSocketSession  {<br>    room: String,<br>    lobby_addr: Addr&lt;Lobby&gt;,<br>    hb: Instant,<br>    id: Uuid,<br>}</pre><p>Let me explain meaning of fields</p><ul><li>Room: This uuid shows room id. I will implement a ‘rooms’. The rooms will be just a HashMap that maps each room Uuid to List of Socket Ids. Because each socket exists in a room.</li><li>Lobby_addr: This address shows where the lobby is. We need this id because each socket’s room exist in a lobby. We need this property because it is used to send data to lobby.</li><li>Hb: This time shows when we receive the last heartbeat. Sometimes connection lost without any warning, so we should handle this situation. Having the actor forever is unnecessary. So, we send a heartbeat to socket every specified N second, if we do not get any response, we terminate the actor.</li><li>Id: this is the id of socket. Assigning an id to each socket is helpful in many cases. Especially, if we want to send private message to specific socket.</li></ul><p><strong>Step Two: The Web-Socket Actor</strong></p><p>So far, WebSocketSession is just a simple struct. We need to convert this struct into an actor. Let me implement the Actor trait on it.</p><p>Here is the implementation:</p><pre>impl Actor for WebSocketSession  {</pre><pre>type Context = ws::WebsocketContext&lt;Self&gt;;</pre><pre>fn started(&amp;mut self, ctx: &amp;mut Self::Context) {</pre><pre>self.hb(ctx);</pre><pre>let addr = ctx.address();</pre><pre>self.lobby_addr</pre><pre>.send(Connect {</pre><pre>addr: addr.recipient(),</pre><pre>lobby_id: self.room.clone(),</pre><pre>self_id: self.id,</pre><pre>})</pre><pre>.into_actor(self)</pre><pre>.then(|res, _, ctx| {</pre><pre>match res {</pre><pre>Ok(_res) =&gt; (),</pre><pre>_ =&gt; ctx.stop(),</pre><pre>}</pre><pre>fut::ready(())</pre><pre>})</pre><pre>.wait(ctx);</pre><pre>}</pre><pre>fn stopping(&amp;mut self, _: &amp;mut Self::Context) -&gt; Running {</pre><pre>self.lobby_addr.do_send(Disconnect { id: self.id, room_id: self.room.clone() });</pre><pre>Running::Stop</pre><pre>}</pre><pre>}</pre><p>Since we are creating WebSocket actor we need a WebSocket context. So context is declared as ws::WebsocketContext. This context allowed us to do WebSocket works. To create and close the Actor we should have started and stopping methods.</p><p>Started function is called when the actor starts up. In started function, we run the heartbeat function first. We will see this function in a bit, but basically it will automatically close the socket if the heartbeat is not echo’d.</p><p>Then we take the addres of the lobby because we send a Connect message to that lobby. This message also includes id and address of the socket. I will show how lobby handle this connect message. If anything goes in wrong way, we just stop the whole Actor with ctx.stop.</p><p>In stopping function, we send a Disconnect message to the lobby. If you noticed, do_send is used here. This allows us to send message synchronously. We do not care if message has been sent or read. As you seen in started method, send needs to be awaited.</p><p>WebSocketSession is now an Actor!</p><p>Here’s the helper heartbeat method</p><pre>impl WebSocketSession  {</pre><pre>fn hb(&amp;self, ctx: &amp;mut ws::WebsocketContext&lt;Self&gt;) {</pre><pre>ctx.run_interval(HEARTBEAT_INTERVAL, |act, ctx| {</pre><pre>if Instant::now().duration_since(act.hb) &gt; CLIENT_TIMEOUT {</pre><pre>println!(&quot;Disconnecting failed heartbeat&quot;);</pre><pre>act.lobby_addr.do_send(Disconnect { id: act.id, room_id: act.room.clone() });</pre><pre>ctx.stop();</pre><pre>return;</pre><pre>}</pre><pre>ctx.ping(b&quot;hi&quot;);</pre><pre>});</pre><pre>}</pre><pre>}</pre><p>This method pings the client and wait for a response on a specified interval. If it does not get response, send a Disconnect message to the lobby. Then lobby clears this session and socket died.</p><p><strong>How to handle WS messages</strong></p><p>We need to implement the StreamHandler trait that will allow us to process an events stream coming into the actor. This pattern matches on all possible WebSocket events.</p><pre>impl StreamHandler&lt;Result&lt;ws::Message, ws::ProtocolError&gt;&gt; for WebSocketSession  {</pre><pre>fn handle(&amp;mut self, msg: Result&lt;ws::Message, ws::ProtocolError&gt;, ctx: &amp;mut Self::Context) {</pre><pre>match msg {</pre><pre>Ok(ws::Message::Ping(msg)) =&gt; {</pre><pre>self.hb = Instant::now();</pre><pre>ctx.pong(&amp;msg);</pre><pre>}</pre><pre>Ok(ws::Message::Pong(_)) =&gt; {</pre><pre>self.hb = Instant::now();</pre><pre>}</pre><pre>Ok(ws::Message::Binary(bin)) =&gt; ctx.binary(bin),</pre><pre>Ok(ws::Message::Close(reason)) =&gt; {</pre><pre>ctx.close(reason);</pre><pre>ctx.stop();</pre><pre>}</pre><pre>Ok(ws::Message::Continuation(_)) =&gt; {</pre><pre>ctx.stop();</pre><pre>}</pre><pre>Ok(ws::Message::Nop) =&gt; (),</pre><pre>Ok(Text(s)) =&gt; self.lobby_addr.do_send(BroadcastMessage {</pre><pre>id: self.id,</pre><pre>msg: serde_json::Value::String(s),</pre><pre>room_id: self.room.clone()</pre><pre>}),</pre><pre>Err(e) =&gt; panic!(&quot;{}&quot;, e),</pre><pre>}</pre><pre>}</pre><pre>}</pre><p>The ping and pong events are basic sending of data to validate the connection is still alive. Since we know they are alive, reset the heartbeat to the current timestamp. If it is a close request, just close and stop the context. On a text message, send it to the lobby. The lobby will figure out to where it needs to go.</p><p><strong>Responding to text messages</strong></p><pre>impl Handler&lt;WsMessage&gt; for WebSocketSession  {</pre><pre>type Result = ();</pre><pre>fn handle(&amp;mut self, msg: WsMessage, ctx: &amp;mut Self::Context) {</pre><pre>ctx.text(msg.0);</pre><pre>}</pre><pre>}</pre><p>If the server puts a WsMessage into our mailbox, we just pass the message String to the actor context as a text message. We forward the messages from the server to the client in this way.</p><p><strong>This is all about </strong>WebSocketSession <strong>for this project.</strong></p><p><strong>Step Three: Defining Messages for our Mailboxes</strong></p><p>Here is the message structs we used in this project</p><pre>use actix::prelude::{Message, Recipient};</pre><pre>use uuid::Uuid;</pre><pre>use serde_json::Value;</pre><pre>use serde::{Deserialize, Serialize};</pre><pre>#[derive(Message)]</pre><pre>#[rtype(result = &quot;()&quot;)]</pre><pre>pub struct WsMessage(pub String);</pre><pre>#[derive(Message)]</pre><pre>#[rtype(result = &quot;()&quot;)]</pre><pre>pub struct Connect {</pre><pre>pub addr: Recipient&lt;WsMessage&gt;,</pre><pre>pub lobby_id: String,</pre><pre>pub self_id: Uuid,</pre><pre>}</pre><pre>#[derive(Message)]</pre><pre>#[rtype(result = &quot;()&quot;)]</pre><pre>pub struct Disconnect {</pre><pre>pub id: Uuid,</pre><pre>pub room_id: String,</pre><pre>}</pre><pre>#[derive(Message, Deserialize, Serialize, Clone)]</pre><pre>#[rtype(result = &quot;()&quot;)]</pre><pre>pub struct BroadcastMessage {</pre><pre>pub id: Uuid,</pre><pre>pub msg: Value,</pre><pre>pub room_id: String</pre><pre>}</pre><pre>impl BroadcastMessage {</pre><pre>pub fn new(id: Uuid, data: Value, r_id: String) -&gt; Self {</pre><pre>Self {</pre><pre>id,</pre><pre>msg :data,</pre><pre>room_id: r_id</pre><pre>}</pre><pre>}</pre><pre>}</pre><p>It is important to describe return type here. Because it must be the same as the type that get returned after the message is handled.</p><p>The msg field is one of Value from serde_json. So any type that can be formed into a Value type.</p><p><strong>Step Four: Defining the Lobby</strong></p><p>We need to define Lobby struct. Here is the plain simple Lobby struct.</p><pre>type Socket = Recipient&lt;WsMessage&gt;;</pre><pre>pub struct Lobby {</pre><pre>sessions: HashMap&lt;Uuid, Socket&gt;, //self id to self</pre><pre>rooms: HashMap&lt;String, HashSet&lt;Uuid&gt;&gt;,      //room id  to list of users id</pre><pre>}</pre><p>The socket here is a recipient of WsMessage. So, when a client connects, we can receive the Recipient&lt; WsMessage &gt; from the HTTP request and store it in the Server.</p><p>Lobby will store the the current sessions using an Uuid as a key. It will also store the chat rooms using a room Uuid as a key.</p><p>We will implement a default method for the server.</p><pre>impl Default for Lobby {</pre><pre>fn default() -&gt; Lobby {</pre><pre>Lobby {</pre><pre>sessions: HashMap::new(),</pre><pre>rooms: HashMap::new(),</pre><pre>}</pre><pre>}</pre><pre>}</pre><p>And here is the helper that sends a message to a specified client actor.</p><pre>impl Lobby {</pre><pre>fn send_message(&amp;self, message: &amp;str, id_to: &amp;Uuid) {</pre><pre>if let Some(socket_recipient) = self.sessions.get(id_to) {</pre><pre>let _ = socket_recipient</pre><pre>.do_send(WsMessage(message.to_owned()));</pre><pre>} else {</pre><pre>println!(&quot;attempting to send message but couldn&#39;t find user id.&quot;);</pre><pre>}</pre><pre>}</pre><pre>}</pre><p>This method takes a string message and an id, if the id is existing send that message to a client with that id. If it does not exist just give an error or print something says that given id does not exist.</p><p><strong>Making the lobby an actor</strong></p><p>We need to make our lobby an actor because Server needs to receive messages as an Actor. Now we can pull it in to our route handlers and send messages to it. Actix will send these messages asynchronously.</p><pre>impl Actor for Lobby {</pre><pre>type Context = Context&lt;Self&gt;;</pre><pre>}</pre><p>If you noticed, we do not have to look out any lifecycle of the Lobby. The only launch when the app starts and remove it when the app closes.</p><p><strong>Handling Messages</strong></p><p>Our server will get 3 types of messages: Connects, Disconnects and WsMessage from the client actor. All of them come from the WsConn lifecycle methods from the actor trait.</p><pre>impl Handler&lt;Disconnect&gt; for Lobby {</pre><pre>type Result = ();</pre><pre>fn handle(&amp;mut self, msg: Disconnect, _: &amp;mut Context&lt;Self&gt;) {</pre><pre>if self.sessions.remove(&amp;msg.id).is_some() {</pre><pre>self.rooms</pre><pre>.get(&amp;msg.room_id)</pre><pre>.unwrap()</pre><pre>.iter()</pre><pre>.filter(|conn_id| *conn_id.to_owned() != msg.id)</pre><pre>.for_each(|user_id| self.send_message(&amp;format!(&quot;{} disconnected.&quot;, &amp;msg.id), user_id));</pre><pre>if let Some(lobby) = self.rooms.get_mut(&amp;msg.room_id) {</pre><pre>if lobby.len() &gt; 1 {</pre><pre>lobby.remove(&amp;msg.id);</pre><pre>} else {</pre><pre>//only one in the lobby, remove it entirely</pre><pre>self.rooms.remove(&amp;msg.room_id);</pre><pre>}</pre><pre>}</pre><pre>}</pre><pre>}</pre><pre>}</pre><p>Here we are responding Disconnect message in a two different way:</p><p>1.remove a single client from a room — remove its identifier. You can inform other clients. send everyone else X disconnected!</p><p>2.If that client was the last one in the room, remove the room completely to prevent blocked HashMap</p><pre>impl Handler&lt;Connect&gt; for Lobby {</pre><pre>type Result = ();</pre><pre>fn handle(&amp;mut self, msg: Connect, _: &amp;mut Context&lt;Self&gt;) -&gt; Self::Result {</pre><pre>self.rooms</pre><pre>.entry(msg.lobby_id.clone())</pre><pre>.or_insert_with(HashSet::new).insert(msg.self_id);</pre><pre>self</pre><pre>.rooms</pre><pre>.get(&amp;msg.lobby_id)</pre><pre>.unwrap()</pre><pre>.iter()</pre><pre>.filter(|conn_id| *conn_id.to_owned() != msg.self_id)</pre><pre>.for_each(|conn_id| self.send_message(&amp;format!(&quot;{} just joined!&quot;, msg.self_id), conn_id));</pre><pre>self.sessions.insert(</pre><pre>msg.self_id,</pre><pre>msg.addr,</pre><pre>);</pre><pre>self.send_message(&amp;format!(&quot;your id is {}&quot;, msg.self_id), &amp;msg.self_id);</pre><pre>}</pre><pre>}</pre><p>We are responding Connect message in this way:</p><p>If we cannot found room id,create new one then add the id to it. Otherwise, inform everyone in the room that new client just joined then add new socket id to sessions.</p><pre>impl Handler&lt;BroadcastMessage&gt; for Lobby {</pre><pre>type Result = ();</pre><pre>fn handle(&amp;mut self, msg: BroadcastMessage, _ctx: &amp;mut Context&lt;Self&gt;) -&gt; Self::Result {</pre><pre>if let Some(_socket_recipient) = self.sessions.get(&amp;msg.id) {</pre><pre>self.rooms.get(&amp;msg.room_id).unwrap().iter().for_each(|_client| self.send_message(&amp;to_string(&amp;msg).unwrap(), _client));</pre><pre>} else {</pre><pre>println!(&quot;attempting to send message but couldn&#39;t find admin id.&quot;);</pre><pre>}</pre><pre>}</pre><pre>}</pre><p>Finally, the lobby listen BroadcastMessage. Clients can send messages to lobby for the lobby to forward to clients.</p><p><strong>Final Step: Setting up the Route / Running the Server</strong></p><p>I define a route that just has a topic name as a path param. Then, I create a new WebSocketSession with a refrence to the Lobby address. Finally, I upgrade the request to a WebSocket request then I have an open persistant connection.</p><pre>#[get(&quot;/{topic_name}&quot;)]</pre><pre>pub async fn start_connection(</pre><pre>req: HttpRequest,</pre><pre>stream: Payload,</pre><pre>topic_name: web::Path&lt;String&gt;,</pre><pre>srv: Data&lt;Addr&lt;Lobby&gt;&gt;,</pre><pre>) -&gt; Result&lt;HttpResponse, Error&gt; {</pre><pre>println!(&quot;client&quot;);</pre><pre>let topic_name = topic_name.into_inner();</pre><pre>let ws = WebSocketSession::new(</pre><pre>topic_name,</pre><pre>srv.get_ref().clone(),</pre><pre>);</pre><pre>let resp = ws::start(ws, &amp;req, stream)?;</pre><pre>Ok(resp)</pre><pre>}</pre><p>Then I define second route to broadcast some statistics. I call the web-socket server, converting the statistics into a value, then send it as a BroadcastMessage. Using this route, you can send statistics as an admin to everyone who connect to “dailyNews “ room.</p><pre>#[post(&quot;/dailyDashBoard&quot;)]</pre><pre>pub async fn send_statistics(</pre><pre>websocket_srv: Data&lt;Addr&lt;Lobby&gt;&gt;,</pre><pre>params: Json&lt;Vec&lt;StatisticRecord&gt;&gt;,</pre><pre>) -&gt; Result&lt;HttpResponse, Error&gt; {</pre><pre>let _msg =params.into_inner();</pre><pre>let msg = BroadcastMessage{</pre><pre>id:Uuid::parse_str(&quot;470bb217-ffa7-43d8-a0cc-b3d30421d1werfw&quot;).unwrap(),</pre><pre>msg:json!(_msg) ,</pre><pre>room_id:  &quot;dailyNews&quot;.to_string()</pre><pre>};</pre><pre>websocket_srv.do_send(msg);</pre><pre>return  Ok(HttpResponse::Ok().json(()));</pre><pre>}</pre><p>The last step is to register the Lobby as shared data so we can get address of the server. Here is the main class;</p><pre>#[actix_web::main]</pre><pre>async fn main() -&gt; std::io::Result&lt;()&gt; {</pre><pre>let chat_server = Lobby::default().start(); //create and spin up a lobby</pre><pre>HttpServer::new(move || {</pre><pre>App::new()</pre><pre>.service(start_connection_route)</pre><pre>.service(send_statistics) //register our route. rename with “as” import or naming conflict</pre><pre>.data(chat_server.clone()) //register the lobby</pre><pre>})</pre><pre>.bind(“127.0.0.1:8081”)?</pre><pre>.run()</pre><pre>.await</pre><pre>}</pre><p>To test the socket client, you can use web-socket extension for <a href="https://chrome.google.com/webstore/detail/simple-websocket-client/pfdhoblngboilpfeibdedpjgfnlcodoo?hl=en">chrome</a>.</p><p>Have fun with web-sockets!</p><p>check out repo for the completed tutorial: <a href="https://github.com/edayardim/web-socket">edayardim/web-socket (github.com)</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=10686a8fa9bd" width="1" height="1" alt=""><hr><p><a href="https://towardsdev.com/websockets-in-rust-actix-framework-10686a8fa9bd">WebSockets in Rust Actix Framework</a> was originally published in <a href="https://towardsdev.com/">Towards Dev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[RSA Encryption/Decryption with Open SSL library in Rust]]></title>
            <link>https://medium.com/@edayardiim/rsa-encryption-decryption-with-open-ssl-library-in-rust-22594e1db971?source=rss-c511b4d4715d------2</link>
            <guid isPermaLink="false">https://medium.com/p/22594e1db971</guid>
            <dc:creator><![CDATA[edayardim]]></dc:creator>
            <pubDate>Wed, 05 Jan 2022 11:38:50 GMT</pubDate>
            <atom:updated>2022-01-05T12:38:15.416Z</atom:updated>
            <content:encoded><![CDATA[<h4>How RSA works?</h4><p>Before dive into RSA library, I would like to talk about how RSA works theoretically.</p><p>If you would like to RSA encryption, you should generate and publish a public key depending on two large prime numbers, along with a helper value. You have to keep secret your prime numbers. Anyone can send encrypted messages, via the public key, but can only be decoded by someone who knows the private keys which consist on prime numbers.</p><p>With RSA, you have to pick two distinct prime numbers (P and Q) at random, and then compute:</p><p><em>N=PQ</em></p><p>And then select <em>e </em>and <em>d (d is the </em><a href="https://en.wikipedia.org/wiki/Modular_multiplicative_inverse"><em>modular multiplicative inverse</em></a><em> of e)</em>. Your public key is:</p><p><em>Pub</em>=(<em>e</em>,<em>N</em>)</p><p>and your private key:</p><p><em>Priv</em>=(<em>d</em>,<em>N</em>)</p><p>If you have a message of <em>M</em>, then the encrypted content is:</p><p><em>Enc</em>=<em>M^e </em>(mod <em>N</em>)</p><p>and you can decrypt with:</p><p><em>Dec</em>=<em>Enc^d </em>(mod<em>N</em>)</p><p>Now you have basic concepts of Rsa public-private key cryptosystem, we can move forward more Rust codes.</p><p><strong>RSA Encryption in Rust</strong></p><p>Our lovely friend Bob has his own key pairs. Alice wants to send a private message to Bob. Thanks to RSA system, she can send a encrypted message using his public key pair.</p><pre>&lt;RSAKeyValue&gt;</pre><pre>&lt;Modulus&gt;&lt;/Modulus&gt;</pre><pre>&lt;Exponent&gt;&lt;/Exponent&gt;</pre><pre>&lt;/RSAKeyValue&gt;</pre><p>Above components are his public key components which is given as a string. &lt;Modulus&gt; represents the “N” value, &lt;Exponent&gt; represents the “e” value.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*cajvnJu9iIp0F_SX_C-dEw.png" /><figcaption><a href="https://docs.rs/openssl/0.10.10/openssl/rsa/struct.Rsa.html#method.from_public_components">rsa public key methods</a></figcaption></figure><p>As you can see the image, RSA key struct implements 5 different methods. Since we have all public components, I would use first method to generate public key. Before creating a RSA public key, we have to convert string components into BigNum format.</p><pre>let n  = &quot;&quot;;</pre><pre>let nb=BASE64.decode(n.as_bytes()).unwrap();<br>let big_n=  BigNum::from_slice(&amp;nb)?;</pre><pre>let e  = &quot;&quot;;<br>let ne= BASE64.decode(e.as_bytes()).unwrap();<br>let big_e= BigNum::from_slice(&amp;ne)?;</pre><p>Now we have “N” and exponent as BigNum format. Finally, we can create our public key.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/857/1*cosvxflHWXKA_Wk4JyH4Kg.png" /><figcaption><a href="https://docs.rs/openssl/0.10.10/openssl/rsa/struct.RsaRef.html#method.public_encrypt">method from rsa library</a></figcaption></figure><pre>let rsa = Rsa::from_public_components(big_n,big_e).unwrap();</pre><pre>// Encrypt with public key<br>let mut buf: Vec&lt;u8&gt; = vec![0; rsa.size() as usize];<br>let _enc = rsa.public_encrypt(message.as_bytes(), &amp;mut buf, Padding::PKCS1_OAEP).unwrap();</pre><pre>let b64_encoded_sig = BASE64.encode(buf.as_ref());<br>println!(&quot;Encrypted: {:?}&quot;, b64_encoded_sig);</pre><p>To sign our message using the public key I used <strong>public_encrypt</strong> method from RSA struct. Public encryption method accepts 3 arguments. First one is data to be encrypted. Public encryption method takes your message as bytes. Second is a buffer to collect returning encrypted bytes. Your buffer size should be same as the RSA key. Lastly you have to specify padding type to use. Padding is used to prevent attackers from estimating or knowing the precise length of a plaintext data that can cause to breaking encryption.</p><p>If you would like to take your encrypted data as string, you should encode your message. Now you have encrypted data which can only be decrypted by the corresponding private key!</p><p><strong>RSA Decryption in Rust</strong></p><p>Now we are ready to decrypt message sent from Alice<em>. As I said before Bob should keep secret his private key. So that nobody can decrypt his messages.</em></p><pre>&lt;RSAKeyValue&gt;</pre><pre>&lt;Modulus&gt;&lt;/Modulus&gt;</pre><pre>&lt;Exponent&gt;&lt;/Exponent&gt;</pre><pre>&lt;P&gt;&lt;/P&gt;</pre><pre>&lt;Q&gt;&lt;/Q&gt;</pre><pre>&lt;DP&gt;&lt;/DP&gt;</pre><pre>&lt;DQ&gt;&lt;/DQ&gt;</pre><pre>&lt;InverseQ&gt;&lt;/InverseQ&gt;</pre><pre>&lt;D&gt;&lt;/D&gt;</pre><pre>&lt;/RSAKeyValue&gt;</pre><p>Above components are his private key components which are given as a string. &lt;Modulus&gt; represents the “N” value, &lt;Exponent&gt; represents the “e” value. And I would like to give more detailed information about other parameters. You do not have to worry about what they mean in depth. You just need to post these parameters to the appropriate places.</p><blockquote>d: reference to the private exponent of the key.</blockquote><blockquote>p: reference to the private exponent of the key.</blockquote><blockquote>q: reference to the second factor of the exponent of the key.</blockquote><blockquote>dmp1: reference to the first exponent used for <a href="https://en.wikipedia.org/wiki/Chinese_remainder_theorem">CRT</a> calculations.</blockquote><blockquote>dmq1: reference to the second exponent used for CRT calculations.</blockquote><blockquote>Iqmp: reference to the coefficient used for CRT calculations.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*wPDLfAYVFySj6jcWvnbY3Q.png" /><figcaption><a href="https://docs.rs/openssl/0.10.10/openssl/rsa/struct.Rsa.html#method.from_private_components">rsa private key methods</a></figcaption></figure><p>As you can see from the image, RSA Private key struct implements different methods. Since I have all public/private key components I would use first method to generate private key struct. Again, we need to convert all components into BigNum format.</p><pre>let rsa = Rsa::from_private_components(</pre><pre>big_n,big_e,big_d,big_p,big_q,big_dmp1,big_dmq1,big_iqmp).unwrap();</pre><pre>// Decrypt with private key<br>let mut buf: Vec&lt;u8&gt; = vec![0; rsa.size() as usize];<br>let _b64_encoded_sig = BASE64.decode(enc_data.as_ref()).unwrap();</pre><pre>let _enc = rsa.private_decrypt(&amp;_b64_encoded_sig, &amp;mut buf, Padding::PKCS1_OAEP).unwrap();</pre><pre>let _b64_encoded_sig = BASE64.encode(buf.as_ref());<br>println!(&quot;Decrypted: {}&quot;, String::from_utf8(buf).unwrap());</pre><p>Private decryption method decrypts data using the private key. It takes 3 parameters. First one is encrypted data which is decoded with base64. Second one is our buffer to cumulate decrypted bytes. Last one is padding type which is used in encryption process.</p><p>End of the story! You are ready to encrypt/decrypt your messages using Rust OpenSSL library!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=22594e1db971" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>