<?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 Web3 Developer on Medium]]></title>
        <description><![CDATA[Stories by Web3 Developer on Medium]]></description>
        <link>https://medium.com/@web3developer?source=rss-be7c00f02569------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*G21Ky33hxhEK6KULlRHsNA.jpeg</url>
            <title>Stories by Web3 Developer on Medium</title>
            <link>https://medium.com/@web3developer?source=rss-be7c00f02569------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 27 Nov 2026 13:14:39 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@web3developer/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[An Example ECDH Key Exchange with HKDF and Authenticated Encryption in Rust]]></title>
            <link>https://medium.com/@web3developer/an-example-ecdh-key-exchange-with-hkdf-and-authenticated-encryption-in-rust-ec9b25c4ebb9?source=rss-be7c00f02569------2</link>
            <guid isPermaLink="false">https://medium.com/p/ec9b25c4ebb9</guid>
            <category><![CDATA[rust]]></category>
            <category><![CDATA[ecdh]]></category>
            <category><![CDATA[authenticated-encryption]]></category>
            <category><![CDATA[cryptography]]></category>
            <category><![CDATA[ring]]></category>
            <dc:creator><![CDATA[Web3 Developer]]></dc:creator>
            <pubDate>Fri, 25 Aug 2023 16:46:17 GMT</pubDate>
            <atom:updated>2023-12-03T16:52:01.063Z</atom:updated>
            <content:encoded><![CDATA[<p>I recently created an example project which implements an ephemeral key exchange between a client and server over TCP. The program uses the Ring cryptography library to compute a shared secret using the X25519 algorithm. Two session keys are derived from the output of the key exchange using HKDF and then messages are encrypted and authenticated between the client and server using AES-GCM with a hash transcript to verify that both the client and the server are seeing exactly the same messages in the same order. In this post I walk through how I built the project and explain the reasoning and design considerations at each step.</p><p>Note that the key exchange used in this project is unauthenticated on both sides because the keys are ephemeral and so there is no way for the client to know if it is communicating with the intended server, and vice versa. The means that a man in the middle attacker could intercept the encrypted communications by doing an ephemeral key exchange with the client and server at the same time and forwarding messages between them. In order to authenticate the server to the client we would need to have some root of trust that we can use to trust the server such as using certificates or static public keys which are verified as trusted out of band.</p><h3>Create a TCP Server</h3><p>I started the project by creating the server which listens on a TCP socket and waits for connections from clients. When a new client connection comes in the server accepts the connection and then proceeds to send and receive messages over the TcpStream. In the example below we simply start the server and then once a connection is created we wait for the client to send a message, print it and then reply to the client with a response message. Note that this example TCP server is single threaded and so would only be able to accept connections from one client at a time.</p><pre>const HOST: &amp;str = &quot;127.0.0.1&quot;;<br>const PORT: &amp;str = &quot;7654&quot;;<br>const BUFFER_SIZE: usize = 50;<br><br>fn main() {<br>    // Create a new socket<br>    let listener = TcpListener::bind(format!(&quot;{}:{}&quot;, HOST, PORT)).unwrap();<br>    <br>    loop {<br>        // Create a new connection with the client<br>        let (mut stream, address) = listener.accept().unwrap();<br>        println!(&quot;Connection established with client at {:?}&quot;, address);<br>        <br>        loop {<br>            // Read and write using the connection<br>            handle_connection(&amp;mut stream);<br>        }<br>    }<br>}<br><br>fn handle_connection(stream: &amp;mut TcpStream) {<br>    let mut buffer = [0; BUFFER_SIZE];<br>    <br>    // read from stream<br>    stream.read(&amp;mut buffer).unwrap();<br>    println!(&quot;Server received request: {:?}&quot;, String::from_utf8(buffer.to_vec()).unwrap());<br>    <br>    // write to stream<br>    let response = &quot;Response data\n&quot;;<br>    stream.write(response.as_bytes()).unwrap();<br>}</pre><h3>Create a TCP Client</h3><p>Next we create the TCP client which connects to the server and once connected, sends a request to the server and then waits for the response which it then prints to the console. So far nothing is encrypted and the client and server are both assuming the data can be parsed as UTF-8 strings. The client sends the data over the TcpStream once every 5 seconds.</p><pre>const HOST: &amp;str = &quot;127.0.0.1&quot;;<br>const PORT: &amp;str = &quot;7654&quot;;<br>const BUFFER_SIZE: usize = 50;<br><br>fn main() {<br>    let mut stream = TcpStream::connect(format!(&quot;{}:{}&quot;, HOST, PORT)).unwrap();<br>    let mut buffer = [0; BUFFER_SIZE];<br>    <br>    loop {<br>        // write to stream<br>        let request = &quot;Request data\n&quot;;<br>        stream.write(request.as_bytes()).unwrap();<br>        <br>        // read from stream<br>        stream.read(&amp;mut buffer).unwrap();<br>        println!(&quot;Client received response: {:?}&quot;, String::from_utf8(buffer.to_vec()).unwrap());<br>        sleep(Duration::new(5, 0));<br>    }<br>}</pre><h3>Implementing the ECDH Key Exchange</h3><p>For this part I created a helper type called EcdhEphemeralKeyExchange which is used by both the client and server programs and which internally uses the Ring cryptography library to implement the key exchange. An enum type Actor is used to determine if the instance is being called from the client or server. The type creates a new SystemRandom instance which is used as a source of entropy to generate the ephemeral keys used in the key exchange. During the key exchange the public keys are stored in the pub_key and peer_pub_key variables which are used later as input into the hash transcript. The run method executes the key change over the TcpStream which is passed in as a parameter by sending and receiving the public keys to and from the peer.</p><pre>#[derive(Debug)]<br>enum Actor {<br>    CLIENT, SERVER<br>}<br><br>pub struct EcdhEphemeralKeyExchange {<br>    actor: Actor,<br>    rand: SystemRandom,<br>    pub_key: Option&lt;Vec&lt;u8&gt;&gt;,<br>    peer_pub_key: Option&lt;Vec&lt;u8&gt;&gt;,<br>}<br><br>impl EcdhEphemeralKeyExchange {<br>    pub fn new_client() -&gt; Self {<br>        Self::new(CLIENT)<br>    }<br><br>    pub fn new_server() -&gt; Self {<br>        Self::new(SERVER)<br>    }<br><br>    fn new(actor: Actor) -&gt; Self {<br>        EcdhEphemeralKeyExchange {<br>            actor,<br>            rand: SystemRandom::new(),<br>            pub_key: None,<br>            peer_pub_key: None<br>        }<br>    }<br><br>    pub fn client_pub_key(&amp;self) -&gt; Option&lt;Vec&lt;u8&gt;&gt; {<br>        match self.actor {<br>            CLIENT =&gt; return self.pub_key.clone(),<br>            SERVER =&gt; return self.peer_pub_key.clone()<br>        }<br>    }<br><br>    pub fn server_pub_key(&amp;self) -&gt; Option&lt;Vec&lt;u8&gt;&gt; {<br>        match self.actor {<br>            CLIENT =&gt; self.peer_pub_key.clone(),<br>            SERVER =&gt; self.pub_key.clone()<br>        }<br>    }<br><br>    pub fn run(&amp;mut self, stream: &amp;mut TcpStream) -&gt; Result&lt;(Vec&lt;u8&gt;, Vec&lt;u8&gt;), Unspecified&gt; {<br>        let alg = &amp;X25519;<br>        <br>        let my_private_key: EphemeralPrivateKey = EphemeralPrivateKey::generate(alg, &amp;self.rand)?;<br>        let my_public_key: PublicKey = my_private_key.compute_public_key()?;<br>        println!(&quot;{:?}: public_key = {}&quot;, self.actor, hex::encode(my_public_key.as_ref()));<br>        <br>        // Send our public key to the peer<br>        stream.write_all(my_public_key.as_ref()).unwrap();<br>        <br>        // Receive a public key from the peer<br>        let mut peer_public_key = [0u8; 32];<br>        stream.read_exact(&amp;mut peer_public_key).unwrap();<br>        println!(&quot;{:?}: peer_public_key = {}&quot;, self.actor, hex::encode(peer_public_key.as_ref()));<br>        <br>        // The peer public key needs to be parsed before use so wrap it creating as an instance of UnparsedPublicKey<br>        let peer_public_key = UnparsedPublicKey::new(alg, peer_public_key);<br>        <br>        // Store public keys for usage in the HashTranscript<br>        self.pub_key = Some(my_public_key.as_ref().to_vec());<br>        self.peer_pub_key = Some(peer_public_key.bytes().to_vec());<br>        <br>        // run ECDH to agree on a shared secret<br>        agree_ephemeral(my_private_key,<br>                        &amp;peer_public_key,<br>                        |shared_secret| self.kdf(shared_secret))<br>    }</pre><h3>Using HKDF to Derive Session Keys</h3><p>The output of ECDH should not directly be used as a session key to encrypt messages because the bits are not uniformly distributed. For this reason it is best practice to run the ECDH output through a key derivation function such as HKDF which will produce a uniformly distributed output which is cryptographically indistinguishable from random.</p><p>In the code below I’ve added a kdf method to the EcdhEphemeralKeyExchange type which is called just after the key change. In this method we use the HKDF extract and expand functions implemented by the Ring cryptography library to derive the session keys. The HKDF extract function is used to produce the uniformly distributed output and HKDF expand is used to stretch the key material to double the length so that we can create two session keys, one for the client to server communication and the other for the server to client communication. Having two session keys limits the scope of a compromise in the event that one of the session keys are recovered by an attacker.</p><pre>fn kdf(&amp;self, shared_secret: &amp;[u8]) -&gt; (Vec&lt;u8&gt;, Vec&lt;u8&gt;) {<br>        // As recommended in RFC 7748 we should apply a KDF on the key material here<br>        let salt = Salt::new(HKDF_SHA256, b&quot;&quot;); // salt is optional<br>        let pseudo_rand_key: Prk = salt.extract(shared_secret);<br>        <br>        let mut context = self.client_pub_key().unwrap();<br>        context.append(&amp;mut self.server_pub_key().unwrap());<br>        let context_data = [context.as_slice()];<br>        <br>        const SESSION_KEY_LEN: usize = 2 * SHA256_OUTPUT_LEN;<br>        struct SessionKeyType;<br>        impl KeyType for SessionKeyType {<br>            fn len(&amp;self) -&gt; usize {<br>                SESSION_KEY_LEN<br>            }<br>        }<br><br>        let output_key_material = pseudo_rand_key.expand(&amp;context_data, SessionKeyType).unwrap();<br>        let mut result = [0u8; SESSION_KEY_LEN];<br>        output_key_material.fill(&amp;mut result).unwrap();<br>        <br>        let session_key = result.split_at(SESSION_KEY_LEN / 2);<br>        (session_key.0.to_vec(), session_key.1.to_vec())<br>    }</pre><h3>Using Authenticated Encryption to Send &amp; Receive Encrypted Messages</h3><p>Next we create two helper types AeadEncrypter and AeadDecrypter which handle the encryption and decryption for each session. Both the client and the server will each create an instance of both types, one for each direction of the communication. For example the client will create an AeadEncrypter to send messages to the server and an AeadDecrypter to receive messages from the server. Each type gets constructed with the respective session key. These types both use AES-GCM from the Ring cryptography library which we use for authenticated encryption. AES-GCM requires passing a nonce to each encryption operation in order to randomise the encryption. The nonce must be unique and so we need to take care to never use repeated nonces for the same encryption key. The nonce doesn’t need to be unpredictable so we simply use a counter starting from one which is incremented for each encryption operation.</p><p>In the code below we implement the NonceSequence interface as required by the library which takes the starting index as a parameter and increments the number to be used as the nonce with each call to the encryption and decryption operations.</p><pre>pub struct CounterNonceSequence(u32);<br><br>impl NonceSequence for CounterNonceSequence {<br>    // called once for each seal operation<br>    fn advance(&amp;mut self) -&gt; Result&lt;Nonce, Unspecified&gt; {<br>        let mut nonce_bytes = vec![0; NONCE_LEN];<br>        nonce_bytes[8..].copy_from_slice(&amp;self.0.to_be_bytes());<br>        //println!(&quot;nonce_bytes = {}&quot;, hex::encode(&amp;nonce_bytes));<br>        <br>        self.0 += 1; // advance the counter<br>        Nonce::try_assume_unique_for_key(&amp;nonce_bytes)<br>    }<br>}</pre><p>The AeadEncrypter type contains a SealingKey which is constructed by passing in the session key and the nonce sequence. This allows us to use the same encryption key for the entire session. If we need to use a new key for another session we create another instance of AeadEncrypter. The encrypt method takes the data to be encrypted and the associated data as parameters. The associated data is not encrypted but rather is used to bind and authenticate some context data to the encryption.</p><pre>pub struct AeadEncrypter {<br>    sealing_key: SealingKey&lt;CounterNonceSequence&gt;<br>}<br><br>impl AeadEncrypter {<br>    pub fn new(key: &amp;[u8]) -&gt; Self {<br>        let unbound_key = UnboundKey::new(&amp;AES_256_GCM, &amp;key).unwrap();<br>        <br>        AeadEncrypter {<br>            sealing_key: SealingKey::new(unbound_key, CounterNonceSequence(1))<br>        }<br>    }<br><br>    pub fn encrypt(&amp;mut self, data: &amp;[u8], associated_data: &amp;[u8]) -&gt; Result&lt;Vec&lt;u8&gt;, Unspecified&gt; {<br>        let associated_data = Aad::from(associated_data);<br>        let mut in_out = data.to_vec();<br>        let tag = self.sealing_key.seal_in_place_separate_tag(associated_data, &amp;mut in_out)?;<br>        <br>        Ok([&amp;in_out, tag.as_ref()].concat())<br>    }<br>}</pre><p>The AeadDecrypter type is implemented similarly to the AeadEncrypter and contains an OpeningKey type which is constructed using the session key and nonce sequence as input. The decrypt method takes the ciphertext and associated data as parameters. If the associated_data passed in does not match the data used in the encryption operation then the decryption will fail. This prevents attackers from tampering with the ciphertext while it is in transit.</p><pre>pub struct AeadDecrypter {<br>    opening_key: OpeningKey&lt;CounterNonceSequence&gt;<br>}<br><br>impl AeadDecrypter {<br>    pub fn new(key: &amp;[u8]) -&gt; Self {<br>        let unbound_key = UnboundKey::new(&amp;AES_256_GCM, &amp;key).unwrap();<br>        <br>        AeadDecrypter {<br>            opening_key: OpeningKey::new(unbound_key, CounterNonceSequence(1))<br>        }<br>    }<br><br>    pub fn decrypt(&amp;mut self, ciphertext: &amp;[u8], associated_data: &amp;[u8]) -&gt; Result&lt;Vec&lt;u8&gt;, Unspecified&gt; {<br>        let associated_data = Aad::from(associated_data);<br>        let mut in_out = ciphertext.to_vec();<br>        <br>        Ok(self.opening_key.open_in_place(associated_data, &amp;mut in_out)?.to_vec())<br>    }<br>}</pre><h3>Hash Transcript</h3><p>A hash transcript is used to authenticate each AEAD decryption operation (similar to the design used in Noise Protocol Framework). We append the public keys and every message sent and received to the hash transcript in order to enforce that both the client and server are seeing the exact same messages in the same order. The hash transcript is implemented by using SHA-256 to hash new messages with the previous transcript hash which creates a kind of hash chain.</p><p>Here is the HashTranscript type which has an append method which hashes a new value with the previous hash to produce the updated transcript hash. This type is used by both the client and the server to record the full transcript of messages sent and received and the public keys used in the key exchange. The as_bytes method returns the transcript hash which is passed in as authenticated data to the AeadEncrypter::encrypt and AeadDecrypter::decrypt methods respectively.</p><pre>pub struct HashTranscript {<br>    hash: Hash<br>}<br><br>impl HashTranscript {<br>    pub fn new() -&gt; Self {<br>        HashTranscript{ hash: Sha256.hash(b&quot;&quot;) }<br>    }<br><br>    pub fn append(&amp;mut self, bytes: &amp;[u8]) {<br>        let mut ctx = Sha256.new_context();<br>        ctx.update(self.hash.as_bytes());<br>        ctx.update(bytes);<br><br>        self.hash = ctx.finish();<br>    }<br><br>    pub fn as_bytes(&amp;self) -&gt; &amp;[u8] {<br>        println!(&quot;transcript = {}&quot;, self.hash.to_hex());<br>        self.hash.as_bytes()<br>    }<br>}</pre><h3>Putting it All Together</h3><p>Finally I updated the client and server to use these helper types to run the key exchange, and send and receive the encrypted messages.</p><p>Here is the handle_session function defined in the client. Once we have a connection, we run the key exchange to create the two session keys, then we append the public keys to the HashTranscript. Next, new AeadEncrypter and AeadDecrypter instances are created which are then used to encrypt and decrypt messages every 5 seconds. After each encryption and decryption operation we append each plaintext message to the hash transcript.</p><pre>fn handle_session(mut stream: TcpStream) -&gt; io::Result&lt;usize&gt; {<br>    // Run the ephemeral to ephemeral key exchange as the client and return the session keys.<br>    let mut ecdh = EcdhEphemeralKeyExchange::new_client();<br>    let (client_to_server, server_to_client) = ecdh.run(&amp;mut stream)<br>        .map_err(|_e| Error::new(ErrorKind::Other, &quot;Key exchange failed&quot;))?;<br><br>    let mut transcript = HashTranscript::new();<br>    transcript.append(&amp;ecdh.client_pub_key().unwrap());<br>    transcript.append(&amp;ecdh.server_pub_key().unwrap());<br>    <br>    let mut encrypter = AeadEncrypter::new(&amp;client_to_server);<br>    let mut decrypter = AeadDecrypter::new(&amp;server_to_client);<br>    <br>    let mut counter: u32 = 0;<br>    loop {<br>        counter += 1;<br>        <br>        // write to stream<br>        let request = format!(&quot;Hello {}&quot;, counter);<br>        let ciphertext = encrypter.encrypt(request.as_bytes(), transcript.as_bytes())<br>            .map_err(|_e| Error::new(ErrorKind::Other, &quot;Encryption failed&quot;))?;<br>        transcript.append(request.as_bytes());<br>        let bytes_written = stream.write(&amp;ciphertext)?;<br>        println!(&quot;Client sent request {:?} bytes&quot;, bytes_written);<br>        <br>        // read from stream<br>        let mut buffer = [0; BUFFER_SIZE];<br>        let bytes_read = stream.read(&amp;mut buffer)?;<br>        let plaintext = decrypter.decrypt(&amp;buffer[..bytes_read], transcript.as_bytes())<br>            .map_err(|_e| Error::new(ErrorKind::Other, &quot;Decryption failed&quot;))?;<br>        transcript.append(&amp;plaintext);<br>        println!(&quot;Client received response: {:?}&quot;, String::from_utf8(plaintext)<br>            .map_err(|e| Error::new(ErrorKind::Other, e.to_string()))?);<br>        <br>        sleep(Duration::new(5, 0));<br>    }</pre><p>To see how all these code samples fit together you can view the full code example on Github <a href="https://github.com/web3-developer/ecdh-key-exchange-example">here</a>.</p><h3>Running the Code</h3><p>To start the server run:</p><pre>cargo run --bin ecdh-server</pre><p>To start the client run:</p><pre>cargo run --bin ecdh-client</pre><h3>Conclusion</h3><p>In this post I showed how to create a simple project which implements a ECDH key exchange using Rust and the Ring cryptography library. We created helper types which use the ring::agreement, ring::hkdf and ring::aead modules for each of the required cryptography primitives. We covered how to create a tcp client and server, how to implement the ECDH key exchange, how to derive session keys using HKDF and how to encrypt and decrypt using AES-GCM with a hash transcript for message authentication.</p><p>This article was originally posted on Web3Developer.io: <a href="https://web3developer.io/an-example-ecdh-key-exchange-with-hkdf-and-authenticated-encryption-in-rust/">https://web3developer.io/an-example-ecdh-key-exchange-with-hkdf-and-authenticated-encryption-in-rust/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ec9b25c4ebb9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Group Theory Continued — Rings & Fields]]></title>
            <link>https://medium.com/@web3developer/group-theory-continued-rings-fields-b3d96a214edd?source=rss-be7c00f02569------2</link>
            <guid isPermaLink="false">https://medium.com/p/b3d96a214edd</guid>
            <category><![CDATA[rust]]></category>
            <category><![CDATA[cryptography]]></category>
            <category><![CDATA[field]]></category>
            <category><![CDATA[group-theory]]></category>
            <category><![CDATA[mathematics]]></category>
            <dc:creator><![CDATA[Web3 Developer]]></dc:creator>
            <pubDate>Sat, 12 Aug 2023 04:41:47 GMT</pubDate>
            <atom:updated>2023-08-12T04:42:56.772Z</atom:updated>
            <content:encoded><![CDATA[<h3>Group Theory Continued — Rings &amp; Fields</h3><p>In my previous <a href="https://web3developer.io/mathematics-for-cryptography-introduction-to-group-theory/">post</a> I introduced the idea of a group, which is an abstract mathematical concept that is defined as a set with a binary operation fulfilling a few mathematical properties. Many cryptography primitives are based on the mathematics of groups such as asymmetric encryption, digital signatures and zero knowledge proofs, which we will cover later. In this post I introduce rings and fields and explain how they relate to groups.</p><h3>Definition of a Ring</h3><p>A <a href="https://en.wikipedia.org/wiki/Ring_(mathematics)">ring</a> is an an algebraic type that is defined over addition, subtraction and multiplication but not division. It is also a group and therefore is also a set with a binary operation (specifically over addition). More precisely a ring is an abelian group over addition and a monoid under multiplication and distributive for multiplication with respect to addition. It fulfils the mathematical properties defined in the comments below. In the sample code below I define a Rust trait Ring which extends AbelianGroup and Monoid and which defines the add, substract and multiply methods. Each method takes an element type E which represents an element in the set and returns another element after applying the operation.</p><pre>/// A Ring is an abelian group over addition, a monoid under multiplication and distributive<br>/// for multiplication with respect to addition.<br>///<br>/// It has the following properties over multiplication:<br>/// Closure - a x b = c where a, b, and c are in the set<br>/// Associativity - a x (b x c) = (a x b) x c<br>/// Identity - a x I = a<br>///<br>/// Multiplication is distributive with respect to addition:<br>/// Left distributive - a x (b + c) = (a x b) + (a x c)<br>/// Right distributive - (b + c) x a = (b x a) + (c x a)<br>trait Ring&lt;E&gt;: AbelianGroup&lt;Addition, E&gt; + Monoid&lt;Multiplication, E&gt; {<br>    /// Supports addition<br>    fn add(&amp;self, e1: E, e2: E) -&gt; E;<br>    /// Supports subtraction which is the same as adding the inverse<br>    fn subtract(&amp;self, e1: E, e2: E) -&gt; E;<br>    /// Supports multiplication<br>    fn multiply(&amp;self, e1: E, e2: E) -&gt; E;<br>}</pre><h3>Example of a Ring</h3><p>Here is an example of a ring, the natural numbers mod n. The natural numbers are basically the non-negative numbers and mod n means we are using modular arithmetic to restrict the numbers in the set to have elements less than n. You can read more about modular arithmetic <a href="https://brilliant.org/wiki/modular-arithmetic/?subtopic=modular-arithmetic&amp;chapter=operations">here</a> for a more detailed explanation. Note that we are not always able to divide the natural numbers mod n because when n is not prime some elements in the set may not have an inverse and so calculating a modular inverse would not always be possible.</p><p>In the code below we create a struct NaturalNumbersModN which has a single parameter representing the size of the ring n. Next we implement the Group trait for addition, setting the identity element to zero and the Monoid trait setting the identity element to 1. The add method is implemented by calling the Group apply method, substract is implemented similarly except we add the inverse. multiply is implemented by calling the Monoid apply method.</p><pre>/// The natural numbers mod n form a ring.<br>struct NaturalNumbersModN(u32);<br><br>impl AbelianGroup&lt;Addition, u32&gt; for NaturalNumbersModN {}<br><br>impl Group&lt;Addition, u32&gt; for NaturalNumbersModN {<br>    fn apply(&amp;self, e1: u32, e2: u32) -&gt; u32 {<br>        (e1 + e2) % self.0<br>    }<br><br>    fn identity(&amp;self) -&gt; u32 {<br>        0<br>    }<br><br>    fn inverse(&amp;self, e: u32) -&gt; u32 {<br>        self.0 - e % self.0<br>    }<br>}<br><br>impl Monoid&lt;Multiplication, u32&gt; for NaturalNumbersModN {<br>    fn apply(&amp;self, e1: u32, e2: u32) -&gt; u32 {<br>        (e1 * e2) % self.0<br>    }<br><br>    fn identity(&amp;self) -&gt; u32 {<br>        1<br>    }<br>}<br><br>impl Ring&lt;u32&gt; for NaturalNumbersModN {<br>    fn add(&amp;self, e1: u32, e2: u32) -&gt; u32 {<br>        &lt;dyn AbelianGroup&lt;Addition, u32&gt;&gt;::apply(self, e1, e2)<br>    }<br><br>    fn subtract(&amp;self, e1: u32, e2: u32) -&gt; u32 {<br>        &lt;dyn AbelianGroup&lt;Addition, u32&gt;&gt;::apply(self, e1, self.inverse(e2))<br>    }<br><br>    fn multiply(&amp;self, e1: u32, e2: u32) -&gt; u32 {<br>        Monoid::apply(self, e1, e2)<br>    }<br>}</pre><p>Next we test out the code using the natural numbers mod 4, which means our ring has a set with elements 0, 1, 2 and 3. The code below tests the add, substract and multiply methods. Notice that when we add 3 and 2 we get 1 instead of 5 because the numbers wrap around. The substract and multiply methods work similarly always returning an element in the set between 0 and 3.</p><pre>#[cfg(test)]<br>mod tests {<br><br>    use super::*;<br><br>    #[test]<br>    fn run_natural_numbers_modn() {<br>        let ring = NaturalNumbersModN(4);<br><br>        let result = ring.add(3, 2);<br>        assert_eq!(1, result);<br><br>        let result = ring.subtract(3, 3);<br>        assert_eq!(0, result);<br><br>        let result = ring.multiply(2, 3);<br>        assert_eq!(2, result);<br>    }<br>}</pre><p>So now you have a basic idea of what a ring is and the operations it defines. Next I introduce fields and explain how they relate to rings and groups.</p><h3>Definition of a Field</h3><p>A <a href="https://en.wikipedia.org/wiki/Field_(mathematics)">field</a> is an an algebraic type that is defined over addition, subtraction, multiplication and division. It is also a group and therefore is also a set but in this case with two binary operations (specifically over addition and multiplication). Put another way, a field is a ring which is also defined over division. More precisely a field is an abelian group over addition and an abelian group over multiplication and is distributive for multiplication with respect to addition.</p><p>It fulfils the mathematical properties defined for a group under both addition and multiplication. In the sample code below I define a Rust trait Field which extends AbelianGroup for both the Addition and Multiplication operations and which defines the add, substract, multiply and divide methods. Each method takes an element type E which represents an element in the set and returns another element after applying the operation.</p><pre>/// A Field is an abelian group over addition and multiplication and distributive<br>/// for multiplication with respect to addition.<br>trait Field&lt;E&gt;: AbelianGroup&lt;Addition, E&gt; + AbelianGroup&lt;Multiplication, E&gt; {<br>    /// Supports addition<br>    fn add(&amp;self, e1: E, e2: E) -&gt; E;<br>    /// Supports subtraction which is the same as addition with the inverse<br>    fn subtract(&amp;self, e1: E, e2: E) -&gt; E;<br>    /// Supports multiplication<br>    fn multiply(&amp;self, e1: E, e2: E) -&gt; E;<br>    /// Supports division where the divisor is not equal to zero<br>    fn divide(&amp;self, e1: E, e2: E) -&gt; E;<br>}</pre><h3>Example of a Field</h3><p>In this example we create a prime field using the natural numbers mod p where p is a prime. This is an example of a finite field because the number of elements in the set are bounded. It just so happens that if a prime number is selected for the modulus we have a field. This is because division is always defined due to every element in the set having an multiplicative inverse. In the code below I define a new struct PrimeField which has a single parameter for the modulus p. The new method is used to construct new instances of the type and uses a library to check if the number is a prime.</p><p>Next we implement the Group traits for addition and multiplication. The inverse method for multiplication is defined using a trial and error approach which is not efficient, where we check if each inverse candidate multiplied by the number is equal to 1 until we get a match. In a future post I will show a better way to calculate multiplicative inverses using the Extended Euclidean algorithm. We then implement the add, subtract, multiply and divide methods for the Field trait which each call their respective additive and multiplicative group operations which have already been defined.</p><pre>/// The natural numbers mod p where p is a prime form a field.<br>struct PrimeField(u32);<br><br>impl PrimeField {<br>    fn new(modulus: u32) -&gt; Self {<br>        if !primes::is_prime(modulus.into()) {<br>            panic!(&quot;modulus is not a prime&quot;)<br>        }<br><br>        PrimeField(modulus)<br>    }<br>}<br><br>impl AbelianGroup&lt;Addition, u32&gt; for PrimeField {}<br><br>impl Group&lt;Addition, u32&gt; for PrimeField {<br>    fn apply(&amp;self, e1: u32, e2: u32) -&gt; u32 {<br>        (e1 + e2) % self.0<br>    }<br><br>    fn identity(&amp;self) -&gt; u32 {<br>        0<br>    }<br><br>    fn inverse(&amp;self, e: u32) -&gt; u32 {<br>        self.0 - e % self.0<br>    }<br>}<br><br>impl AbelianGroup&lt;Multiplication, u32&gt; for PrimeField {}<br><br>impl Group&lt;Multiplication, u32&gt; for PrimeField {<br>    fn apply(&amp;self, e1: u32, e2: u32) -&gt; u32 {<br>        (e1 * e2) % self.0<br>    }<br><br>    fn identity(&amp;self) -&gt; u32 {<br>        1<br>    }<br><br>    fn inverse(&amp;self, e: u32) -&gt; u32 {<br>        if e % self.0 == 0 {<br>            panic!(&quot;Cannot calculate inverse for zero&quot;)<br>        }<br>        // This trial and error method to calculate the inverse is not efficient.<br>        // In another post we will use the Extended Euclidean Algorithm to solve this instead.<br>        for i in 0..self.0 {<br>            if (e * i) % self.0 == 1 {<br>                return i;<br>            }<br>        }<br>        panic!(&quot;No inverse found&quot;);<br>    }<br>}<br><br>impl Field&lt;u32&gt; for PrimeField {<br>    fn add(&amp;self, e1: u32, e2: u32) -&gt; u32 {<br>        &lt;dyn AbelianGroup&lt;Addition, u32&gt;&gt;::apply(self, e1, e2)<br>    }<br><br>    fn subtract(&amp;self, e1: u32, e2: u32) -&gt; u32 {<br>        let inverse = &lt;dyn AbelianGroup&lt;Addition, u32&gt;&gt;::inverse(self,e2);<br>        &lt;dyn AbelianGroup&lt;Addition, u32&gt;&gt;::apply(self, e1, inverse)<br>    }<br><br>    fn multiply(&amp;self, e1: u32, e2: u32) -&gt; u32 {<br>        &lt;dyn AbelianGroup&lt;Multiplication, u32&gt;&gt;::apply(self, e1, e2)<br>    }<br><br>    fn divide(&amp;self, e1: u32, e2: u32) -&gt; u32 {<br>        let inverse = &lt;dyn AbelianGroup&lt;Multiplication, u32&gt;&gt;::inverse(self,e2);<br>        &lt;dyn AbelianGroup&lt;Multiplication, u32&gt;&gt;::apply(self, e1, inverse)<br>    }<br>}</pre><p>In the sample code below we test out the PrimeField using 11 as the prime modulus. We test the add, substract, multiply and divide methods which each behave as expected and return elements in the set after applying the respective group operation under addition or multiplication. Finally we test that we can divide by any number in the field by looping through all possible divisors from 1 to 10 and verify that the code doesn’t panic with ‘No inverse found’, which would occur if a particular element had no multiplicative inverse.</p><pre>#[cfg(test)]<br>mod tests {<br><br>    use super::*;<br><br>    #[test]<br>    fn run_prime_field() {<br>        let field = PrimeField::new(11);<br><br>        let result = field.add(3, 10);<br>        assert_eq!(2, result);<br><br>        let result = field.subtract(1, 3);<br>        assert_eq!(9, result);<br><br>        let result = field.multiply(2, 10);<br>        assert_eq!(9, result);<br><br>        let result = field.divide(10, 2);<br>        assert_eq!(5, result);<br><br>        // Every element in the field apart from zero has an inverse<br>        for i in 1..11 {<br>            let _result = field.divide(10, i);<br>        }<br>    }<br>}</pre><h3>Conclusion</h3><p>In this post we continued on the topic of group theory by introducing two new algebraic types; rings and fields. We defined a Ring trait to help explain the concept of a ring and created an example implementation using the natural numbers mod n which is always defined over addition, subtraction and multiplication. We then defined a Field trait while explaining the definition of a field and how it relates to groups and rings. We then created an example field over the natural numbers mod p by defining a new type PrimeField which implements the respective group operations over addition and multiplication. In a future post I will show how prime fields are used to implement certain cryptographic primitives such as the Diffie-Hellman key exchange so stay tuned for more updates.</p><p>This article was originally posted on Web3Developer.io: <a href="https://web3developer.io/group-theory-continued-rings-fields/">https://web3developer.io/group-theory-continued-rings-fields/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b3d96a214edd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mathematics for Cryptography — Introduction to Group Theory]]></title>
            <link>https://medium.com/@web3developer/mathematics-for-cryptography-introduction-to-group-theory-9dd572217593?source=rss-be7c00f02569------2</link>
            <guid isPermaLink="false">https://medium.com/p/9dd572217593</guid>
            <category><![CDATA[mathematics]]></category>
            <category><![CDATA[rust]]></category>
            <category><![CDATA[groups]]></category>
            <category><![CDATA[cryptography]]></category>
            <category><![CDATA[group-theory]]></category>
            <dc:creator><![CDATA[Web3 Developer]]></dc:creator>
            <pubDate>Mon, 31 Jul 2023 02:19:16 GMT</pubDate>
            <atom:updated>2023-07-31T02:27:23.243Z</atom:updated>
            <content:encoded><![CDATA[<h3>Mathematics for Cryptography — Introduction to Group Theory</h3><p>I’m planning to do a set of posts on the mathematics used in cryptography and so I will be covering topics such as group theory, number theory, modular arithmetic, polynomials and eventually elliptic curves. This is the first post in the series which will give a very basic introduction to group theory and groups.</p><h3>What is Group Theory?</h3><p>Group theory is a branch of mathematics in the area of abstract algebra that studies the symmetries that recur throughout mathematics. A group is a very abstract concept and a generalisation of some other algebraic types such as rings and fields which I will explain more in a future post. It turns out that the patterns and laws described by group theory show up in number theory, algebraic equations and geometry. Most importantly cryptography relies on group theory and finite fields for primitives such as the Diffe-Helman key exchange, RSA encryption and also for zero knowledge proofs.</p><p>So what is a group?</p><h3>Definition of a Group</h3><p>A group is defined as a set with a binary operation that satisfies a few properties; closure, associativity, identity and invert-ability. A set is just a collection of elements and the binary operation is not yet defined. It could be addition or multiplication but the definition of a group is more abstract than that and so it could also be geometric rotations over a shape for example.</p><p>In the sample code below I define a Rust trait Group which models a group. It takes a type T which must implement the Operation marker trait. The comments describe the properties which much be satisfied by the group. I represent the binary operation as ‘.’ in the comments which is implemented by the apply method which takes two elements and returns another element. The identity method should return the identity element for the group and the inverse method should return the inverse of the given element.</p><pre>/// A group is a set and a binary operation (denoted by &#39;.&#39;) which satisfies the following properties:<br>/// Closure - a . b = c where a, b, and c are in the set<br>/// Associativity - a . (b . c) = (a . b) . c<br>/// Identity - a . I = a<br>/// Inverse - a . a^-1 = I<br>pub trait Group&lt;T: Operation, E&gt; {<br>    /// The binary operation which takes elements e1 and e2 of type E and returns the result<br>    fn apply(&amp;self, e1: E, e2: E) -&gt; E;<br><br>    /// Returns the identity element<br>    fn identity(&amp;self) -&gt; E;<br><br>    /// Returns the inverse of element e<br>    fn inverse(&amp;self, e: E) -&gt; E;<br>}</pre><h3>Definition of an Abelian Group</h3><p>An abelian group is a group that also supports the commutativity property (in addition to the other group properties) which basically means the binary operation can be applied in any order to the elements a and b and the result will be the same. I define it here as a marker trait for completeness which extends the Group trait even though no additional methods are required.</p><pre>/// A type which supports commutativity in addition to the standard group properties:<br>/// Commutativity - a . b = b . a<br>pub trait AbelianGroup&lt;T: Operation, E&gt;: Group&lt;T, E&gt; {}</pre><h3>Definition of a Monoid</h3><p>A monoid is similar to a group except that elements may not have an inverse and it only supports the associativity and identity properties. It once again is a very abstract concept having a set and a binary operation. I define the Monoid trait below with an apply and identity method but no inverse method. I will be using this type later when defining a trait for a ring in a future post.</p><pre>/// A monoid is a set and a binary operation (denoted by &#39;.&#39;) which satisfies the following properties:<br>/// Associativity - a . (b . c) = (a . b) . c<br>/// Identity - a . I = a<br>pub trait Monoid&lt;T: Operation, E&gt; {<br>    /// The binary operation which takes elements e1 and e2 of type E and returns the result<br>    fn apply(&amp;self, e1: E, e2: E) -&gt; E;<br><br>    /// Returns the identity element<br>    fn identity(&amp;self) -&gt; E;<br>}</pre><h3>Example Operations</h3><p>Next I define the Operation marker trait and implement Addition and Multiplication types to be used as markers. This is required so that a type can implement the trait over multiple operations. For example we might want to implement the Group trait under both Addition and Multiplcation.</p><pre>/// Marks the Monoid and Group traits with a type<br>pub trait Operation {}<br>pub struct Addition;<br>pub struct Multiplication;<br>impl Operation for Addition {}<br>impl Operation for Multiplication {}</pre><h3>Example of a Group</h3><p>Finally here is a very simple example of a group, the set of integers under addition. In mathematics the set of integers is defined as the whole numbers, positive and negative, including zero. With addition the set of integers forms a group because all the group properties are for-filled. The identity element is zero and the inverse is the negation of the given element. We also implement the AbelianGroup trait for our new AdditiveIntegers type because integer addition is commutative. You can check for yourself to verify that each of the group properties are for-filled with this implementation.</p><pre>/// Integers under addition form a group where plus (+) is the group operation, zero is the identity<br>/// and negation (-) can be used to get the inverse of an element<br>struct AdditiveIntegers();<br><br>impl Group&lt;Addition, i32&gt; for AdditiveIntegers {<br>    fn apply(&amp;self, a: i32, b: i32) -&gt; i32 {<br>        a + b<br>    }<br>    fn identity(&amp;self) -&gt; i32 {<br>        0<br>    }<br>    fn inverse(&amp;self, a: i32) -&gt; i32 {<br>        -a<br>    }<br>}<br><br>// Integers under addition supports commutativity<br>impl AbelianGroup&lt;Addition, i32&gt; for AdditiveIntegers {}</pre><p>Next we test out the code by creating a new instance of the AdditiveIntegers group. Then we test each of the methods to confirm that they each work as expected and for-fill the required properties, closure, associativity, identity, invert-ability and commutativity.</p><pre>#[cfg(test)]<br>mod tests {<br><br>use super::*;<br>    #[test]<br>    fn run_additive_integers() {<br>        let group = AdditiveIntegers();<br><br>        let a: i32 = 10;<br>        let b: i32 = 20;<br>        let c: i32 = 30;<br><br>        // Closure - a . b = c where a, b, and c are in the set<br>        let result: i32 = group.apply(a, b);<br>        assert_eq!(c, result); // result is an integer so in the set<br>        <br>        // Associativity - a . (b . c) = (a . b) . c<br>        assert_eq!(group.apply(a, group.apply(b, c)),<br>                   group.apply(group.apply(a , b), c));<br>        // Identity - a . I = a<br>        assert_eq!(group.apply(a, group.identity()), a);<br>        <br>        // Inverse - a . a^-1 = I<br>        assert_eq!(group.apply(a, group.inverse(a)), group.identity());<br>        <br>        // Commutativity - a . b = b . a<br>        assert_eq!(group.apply(a, b), group.apply(b, a));<br>    }<br>}</pre><h3>Conclusion</h3><p>This post introduced group theory and explained the definition of a group, abelian group and monoid. We then created an example group, the integers over addition and showed an example usage. Future posts will cover topics such as rings and fields which will help explain why I’ve created these group types and will further explain these group theory concepts.</p><p>This article was originally posted on Web3Developer.io: <a href="https://web3developer.io/mathematics-for-cryptography-introduction-to-group-theory/">https://web3developer.io/mathematics-for-cryptography-introduction-to-group-theory/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9dd572217593" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Authenticated Encryption in Rust using Ring]]></title>
            <link>https://medium.com/@web3developer/authenticated-encryption-in-rust-using-ring-2a40d11a586c?source=rss-be7c00f02569------2</link>
            <guid isPermaLink="false">https://medium.com/p/2a40d11a586c</guid>
            <category><![CDATA[ring]]></category>
            <category><![CDATA[authenticated-encryption]]></category>
            <category><![CDATA[aead]]></category>
            <category><![CDATA[rust]]></category>
            <category><![CDATA[cryptography]]></category>
            <dc:creator><![CDATA[Web3 Developer]]></dc:creator>
            <pubDate>Mon, 12 Jun 2023 16:25:32 GMT</pubDate>
            <atom:updated>2023-06-12T16:31:00.933Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Authenticated Encryption with Associated Data</strong> (<a href="https://en.wikipedia.org/wiki/Authenticated_encryption"><strong>AEAD</strong></a>) is a modern cryptography primitive that enables secure encryption and decryption of data using a symmetric key in a way that prevents it from being altered or tampered with. The Ring cryptography library implements the AES-GCM and ChaCha20-Poly1305 authenticated encryption algorithms which are two of the most commonly used schemes on the internet. In this post I show you how to use the ring::aead module to generate an encryption key, encrypt some data and then decrypt using the provided UnboundKey, SealingKey and OpeningKey types.</p><h3>Introduction to AEAD</h3><p>Basic encryption (without authentication) only protects against a passive man in the middle attacker who can observe the data as it travels over an insecure channel but it doesn’t prevent active attacks where the encrypted ciphertext can still be altered. Allowing the ciphertext to be altered without detection can lead to a number of vulnerabilities and so modern systems generally use authenticated encryption to prevent this. For example the AES-CBC-HMAC scheme uses HMAC authentication tags to verify the integrity of the ciphertext after encryption.</p><p>AEAD is a type of authenticated encryption which supports data integrity verification and additionally allows you to bind some plaintext associated data to the ciphertext which must be supplied as a part of the decryption. The decryption will fail if either the ciphertext or the associated data was altered as both are part of the integrity checks. The associated data is not encrypted but is authenticated and is useful for sending contextual information related to the encryption.</p><p><strong>AES with the Galois/Counter mode (AES-GCM)</strong> is the most widely used AEAD. It has hardware support on many devices and internally uses GMAC which is a high performance MAC algorithm which is used for the integrity checks. It is based on AES-CTR which uses a nonce combined with an incrementing counter to produce a key stream which is then XORed with the plaintext to produce the ciphertext. This is why the algorithm requires supplying a nonce as a part of the encryption and decryption as you will see later in this post.</p><p><strong>ChaCha20-Poly1305</strong> is an AEAD designed by Daniel J. Bernstein which was standardised by Google in 2013. It is faster than AES-GCM when AES hardware support is not available and so it is generally preferred for low end devices. Similar to AES-CTR, ChaCha20 is used to encrypt a nonce and counter to produce a key stream which is XORed with the plaintext to produce the ciphertext. Poly1305 is a high performance MAC algorithm much like GMAC which is used to verify the integrity of messages.</p><h3>AEAD Usage Guidelines</h3><ul><li>For both AES-GCM and ChaCha20-Poly1305 a unique nonce must be supplied for each encryption operation. Repeated nonce usage can lead to vulnerabilities and so care must be taken to ensure that that there are no duplicate nonce values used with the same encryption key.</li><li>Each nonce needs to be unique but doesn’t need to be unpredictable.</li><li>The nonce has a size of 12 bytes which can hold up to 2⁹⁶ — 1 distinct values.</li><li>An incrementing counter could be used as the nonce but requires keeping track of the state of the last counter used which can be error prone. If using a counter for the nonce the maximum number of encryption operations per key is 2⁹⁶ — 1.</li><li>Alternatively a randomised nonce can be used which randomly generates a new nonce for each encryption operation. If using a random nonce no more than 2³⁰ encryption operations should be used to prevent increasing the probability of randomly generating a duplicate nonce.</li><li>Encryption keys should be rotated periodically if encrypting a larger amount a data.</li><li>Use ChaCha20-Poly1305 instead of AES-GCM when hardware support for AES is not available.</li></ul><h3>Summary of Types</h3><p>The ring::aead module contains the following types and functions:</p><p><strong>trait BoundKey </strong>— An AEAD key bound to a nonce sequence. Both SealingKey and OpeningKey implement this trait.</p><p><strong>trait NonceSequence </strong>— A sequence of unique nonces. We will create a type which implements this trait for generating nonces as the library doesn’t implement this for us.</p><p><strong>struct Algorithm </strong>— An AEAD algorithm. AES_128_GCM, AES_256_GCM and CHACHA20_POLY1305 algorithms are supported.</p><p><strong>struct UnboundKey </strong>— An AEAD key without a designated role or nonce sequence.</p><p><strong>struct SealingKey </strong>— An AEAD key for encrypting and signing (“sealing”), bound to a nonce sequence.</p><p><strong>struct Nonce </strong>— A nonce for a single AEAD opening or sealing operation. Returned by the NonceSequence type.</p><p><strong>struct Aad </strong>— The additionally authenticated data (AAD) for an opening or sealing operation. This data is authenticated but is <strong>not</strong> encrypted.</p><p><strong>struct Tag </strong>— An authentication tag. Used for integrity checking the ciphertext during decryption.</p><p><strong>struct OpeningKey </strong>— An AEAD key for authenticating and decrypting (“opening”), bound to a nonce sequence.</p><h3>Rust Imports</h3><p>Let’s start by importing the required types into our project.</p><pre>use ring::error::Unspecified;<br>use ring::rand::SecureRandom;<br>use ring::rand::SystemRandom;<br>use ring::aead::Algorithm;<br>use ring::aead::AES_128_GCM;<br>use ring::aead::AES_256_GCM;<br>use ring::aead::CHACHA20_POLY1305;<br>use ring::aead::UnboundKey;<br>use ring::aead::BoundKey;<br>use ring::aead::SealingKey;<br>use ring::aead::OpeningKey;<br>use ring::aead::Aad;<br>use ring::aead::Tag;<br>use ring::aead::NonceSequence;<br>use ring::aead::NONCE_LEN;<br>use ring::aead::Nonce;</pre><h3>Generate an Encryption Key</h3><p>We start by generating a symmetric encryption key by using a new instance of SystemRandom from the rand module. We collect 32 bytes of random data and use it as our secret key which is passed in to create a new instance of UnboundKey which wraps the key value.</p><pre>// Create a new instance of SystemRandom to be used as the single source of entropy<br>let rand = SystemRandom::new();<br><br>// Generate a new symmetric encryption key<br>let mut key_bytes = vec![0; AES_256_GCM.key_len()];<br>rand.fill(&amp;mut key_bytes)?;<br>println!(&quot;key_bytes = {}&quot;, hex::encode(&amp;key_bytes)); // don&#39;t print this in production code<br><br>// Create a new AEAD key without a designated role or nonce sequence<br>let unbound_key = UnboundKey::new(&amp;AES_256_GCM, &amp;key_bytes)?;</pre><h3>Create a NonceSequence &amp; SealingKey</h3><p>Next we create a NonceSequence by implementing the trait. In this example I am using a simple incrementing counter as the method to generate nonces. We then create a new instance of the NonceSequence starting from one and then pass it along with the UnboundKey to create a new SealingKey which is a type that binds the key to the nonce sequence. The first nonce value used will be one and so on. Note that the UnboundKey and NonceSequence instances are moved when creating the new SealingKey. This design help to prevent reuse of the these sensitive values.</p><pre>struct CounterNonceSequence(u32);<br><br>impl NonceSequence for CounterNonceSequence {<br>    // called once for each seal operation<br>    fn advance(&amp;mut self) -&gt; Result&lt;Nonce, Unspecified&gt; {<br>        let mut nonce_bytes = vec![0; NONCE_LEN];<br>        let bytes = self.0.to_be_bytes();<br>        nonce_bytes[8..].copy_from_slice(&amp;bytes);<br>        println!(&quot;nonce_bytes = {}&quot;, hex::encode(&amp;nonce_bytes));<br>        self.0 += 1; // advance the counter<br>        Nonce::try_assume_unique_for_key(&amp;nonce_bytes)<br>    }<br>}<br><br>// Create a new NonceSequence type which generates nonces<br>let nonce_sequence = CounterNonceSequence(1);<br><br>// Create a new AEAD key for encrypting and signing (&quot;sealing&quot;), bound to a nonce sequence<br>// The SealingKey can be used multiple times, each time a new nonce will be used<br>let mut sealing_key = SealingKey::new(unbound_key, nonce_sequence);</pre><h3>Prepare Data &amp; Encrypt Using SealingKey</h3><p>We prepare the data to be encrypted, the associated data, and then create a copy of the data so it can be encrypted in place. The original copy of the data will simply be used for comparison later. We then use the SealingKey::seal_in_place_separate_tag method to encrypt the data, bind the associated data to it, and return the authentication tag. After returning, the in_out variable will contain the ciphertext. The SealingKey instance can be used to encrypt data multiple times using the same key.</p><pre>// This data will be authenticated but not encrypted<br>//let associated_data = Aad::empty(); // is optional so can be empty<br>let associated_data = Aad::from(b&quot;additional public data&quot;);<br><br>// Data to be encrypted<br>let data = b&quot;hello world&quot;;<br>println!(&quot;data = {}&quot;, String::from_utf8(data.to_vec()).unwrap());<br><br>// Create a mutable copy of the data that will be encrypted in place<br>let mut in_out = data.clone();<br><br>// Encrypt the data with AEAD using the AES_256_GCM algorithm<br>let tag = sealing_key.seal_in_place_separate_tag(associated_data, &amp;mut in_out)?;</pre><h3>Create an OpeningKey for Decryption</h3><p>We need to create new instances of some of the types because they were previously moved during use. We then create a new instance of OpeningKey which binds the UnboundKey to the NonceSequence ready for decryption. Note that the NonceSequence needs to generate the same nonce values that were used during the encryption. In this example I’m starting the nonce counter from one again.</p><pre>// Recreate the previously moved variables<br>let unbound_key = UnboundKey::new(&amp;AES_256_GCM, &amp;key_bytes)?;<br>let nonce_sequence = CounterNonceSequence(1);<br><br>//let associated_data = Aad::empty(); // supplying the wrong data causes the decryption to fail<br>let associated_data = Aad::from(b&quot;additional public data&quot;);<br><br>// Create a new AEAD key for decrypting and verifying the authentication tag<br>let mut opening_key = OpeningKey::new(unbound_key, nonce_sequence);</pre><h3>Decrypt the Ciphertext</h3><p>Finally we decrypt the ciphertext using the OpeningKey::open_in_place method, passing in the associated data and the ciphertext concatenated with the authentication tag. If the integrity checks using the authentication tag succeed then the decrypted data is returned from the method otherwise an error::Unspecified is returned.</p><pre>// Decrypt the data by passing in the associated data and the cyphertext with the authentication tag appended<br>let mut cypher_text_with_tag = [&amp;in_out, tag.as_ref()].concat();<br><br>let decrypted_data = opening_key.open_in_place(associated_data, &amp;mut cypher_text_with_tag)?;<br>println!(&quot;decrypted_data = {}&quot;, String::from_utf8(decrypted_data.to_vec()).unwrap());<br><br>assert_eq!(data, decrypted_data);</pre><h3>Full Sample Code</h3><p>Here is the full code sample for reference.</p><pre>use ring::error::Unspecified;<br>use ring::rand::SecureRandom;<br>use ring::rand::SystemRandom;<br>use ring::aead::Algorithm;<br>use ring::aead::AES_128_GCM;<br>use ring::aead::AES_256_GCM;<br>use ring::aead::CHACHA20_POLY1305;<br>use ring::aead::UnboundKey;<br>use ring::aead::BoundKey;<br>use ring::aead::SealingKey;<br>use ring::aead::OpeningKey;<br>use ring::aead::Aad;<br>use ring::aead::Tag;<br>use ring::aead::NonceSequence;<br>use ring::aead::NONCE_LEN;<br>use ring::aead::Nonce;<br><br>struct CounterNonceSequence(u32);<br><br>impl NonceSequence for CounterNonceSequence {<br>    // called once for each seal operation<br>    fn advance(&amp;mut self) -&gt; Result&lt;Nonce, Unspecified&gt; {<br>        let mut nonce_bytes = vec![0; NONCE_LEN];<br><br>        let bytes = self.0.to_be_bytes();<br>        nonce_bytes[8..].copy_from_slice(&amp;bytes);<br>        println!(&quot;nonce_bytes = {}&quot;, hex::encode(&amp;nonce_bytes));<br><br>        self.0 += 1; // advance the counter<br>        Nonce::try_assume_unique_for_key(&amp;nonce_bytes)<br>    }<br>}<br><br>fn main() -&gt; Result&lt;(), Unspecified&gt; {<br>    // Create a new instance of SystemRandom to be used as the single source of entropy<br>    let rand = SystemRandom::new();<br>    <br>    // Generate a new symmetric encryption key<br>    let mut key_bytes = vec![0; AES_256_GCM.key_len()];<br>    rand.fill(&amp;mut key_bytes)?;<br>    println!(&quot;key_bytes = {}&quot;, hex::encode(&amp;key_bytes)); // don&#39;t print this in production code<br>    <br>    // Create a new AEAD key without a designated role or nonce sequence<br>    let unbound_key = UnboundKey::new(&amp;AES_256_GCM, &amp;key_bytes)?;<br>    <br>    // Create a new NonceSequence type which generates nonces<br>    let nonce_sequence = CounterNonceSequence(1);<br>    <br>    // Create a new AEAD key for encrypting and signing (&quot;sealing&quot;), bound to a nonce sequence<br>    // The SealingKey can be used multiple times, each time a new nonce will be used<br>    let mut sealing_key = SealingKey::new(unbound_key, nonce_sequence);<br><br>    // This data will be authenticated but not encrypted<br>    //let associated_data = Aad::empty(); // is optional so can be empty<br>    let associated_data = Aad::from(b&quot;additional public data&quot;);<br>    <br>    // Data to be encrypted<br>    let data = b&quot;hello world&quot;;<br>    println!(&quot;data = {}&quot;, String::from_utf8(data.to_vec()).unwrap());<br>    <br>    // Create a mutable copy of the data that will be encrypted in place<br>    let mut in_out = data.clone();<br>    <br>    // Encrypt the data with AEAD using the AES_256_GCM algorithm<br>    let tag = sealing_key.seal_in_place_separate_tag(associated_data, &amp;mut in_out)?;<br>    <br>    // Recreate the previously moved variables<br>    let unbound_key = UnboundKey::new(&amp;AES_256_GCM, &amp;key_bytes)?;<br>    let nonce_sequence = CounterNonceSequence(1);<br>    //let associated_data = Aad::empty(); // supplying the wrong data causes the decryption to fail<br>    let associated_data = Aad::from(b&quot;additional public data&quot;);<br>    <br>    // Create a new AEAD key for decrypting and verifying the authentication tag<br>    let mut opening_key = OpeningKey::new(unbound_key, nonce_sequence);<br>    <br>    // Decrypt the data by passing in the associated data and the cypher text with the authentication tag appended<br>    let mut cypher_text_with_tag = [&amp;in_out, tag.as_ref()].concat();<br>    let decrypted_data = opening_key.open_in_place( associated_data, &amp;mut cypher_text_with_tag)?;<br>    println!(&quot;decrypted_data = {}&quot;, String::from_utf8(decrypted_data.to_vec()).unwrap());<br>    <br>    assert_eq!(data, decrypted_data);<br>    Ok(())<br>}<br></pre><h3>Conclusion</h3><p>In this post I introduced the concept of authenticated encryption and explained what it is used for and how it works. I also provided an overview of the two most commonly used AEAD algorithms AES-GCM and ChaCha20-Poly1305 and explained how they both require a nonce as input which must to be unique in order to ensure the security of the encryption scheme. We then walked through an example where we randomly generated a symmetric key then used the UnboundKey, SealingKey and OpeningKey to securely encrypt the data and then later decrypt by supplying the authentication tag and associated data along with the key.</p><p>This article was originally posted on Web3Developer.io: <a href="https://web3developer.io/authenticated-encryption-in-rust-using-ring/">https://web3developer.io/authenticated-encryption-in-rust-using-ring/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2a40d11a586c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Ring by Example — Sample Code Cheatsheet]]></title>
            <link>https://medium.com/@web3developer/ring-by-example-sample-code-cheatsheet-c67debd7fc4c?source=rss-be7c00f02569------2</link>
            <guid isPermaLink="false">https://medium.com/p/c67debd7fc4c</guid>
            <category><![CDATA[cheatsheet]]></category>
            <category><![CDATA[ring]]></category>
            <category><![CDATA[rust]]></category>
            <category><![CDATA[cryptography]]></category>
            <dc:creator><![CDATA[Web3 Developer]]></dc:creator>
            <pubDate>Wed, 31 May 2023 10:03:50 GMT</pubDate>
            <atom:updated>2023-12-03T16:36:13.885Z</atom:updated>
            <content:encoded><![CDATA[<h3>Ring by Example — Sample Code Cheatsheet</h3><p>I have been writing about the <a href="https://docs.rs/ring/latest/ring/">Ring</a> cryptography library for a while now and so in this post I am sharing a resource which I think will be a useful reference for developers implementing applications or protocols using the library.</p><p>This is basically a cheatsheet of example code showing how to use each of the cryptography primitives supported by Ring. I’ve tried to keep the examples as simple as possible in order to make the code samples easy to read through and as re-usable as possible. For a more detailed explanation on how to use each of the modules you can see my previous posts on each topic which are linked in the relevant sections below.</p><h3>Summary of Modules</h3><p>The Ring cryptography library contains the following modules for working with various cryptography primitives:</p><ul><li><a href="https://docs.rs/ring/latest/ring/digest/index.html">ring::digest</a> - Cryptographic hash functions</li><li><a href="https://docs.rs/ring/latest/ring/rand/index.html">ring::rand</a> - Cryptographically secure pseudo-random number generation</li><li><a href="https://docs.rs/ring/latest/ring/hmac/index.html">ring::hmac</a> - Signing and verification with HMAC</li><li><a href="https://docs.rs/ring/latest/ring/hkdf/index.html">ring::hkdf</a> - Key derivation with HKDF</li><li><a href="https://docs.rs/ring/latest/ring/pbkdf2/index.html">ring::pbkdf2</a> - Password hashing and verification with PBKDF2</li><li><a href="https://docs.rs/ring/latest/ring/agreement/index.html">ring::agreement</a> - Key exchange with ECDH</li><li><a href="https://docs.rs/ring/latest/ring/signature/index.html">ring::signature</a> - Signing and verification with digital signatures</li><li><a href="https://docs.rs/ring/latest/ring/aead/index.html">ring::aead</a> - Authenticated encryption using AEAD</li></ul><p>The modules support primitives such as hash functions, random numbers, message authentication codes, key derivation, key agreement, digital signatures and authenticated encryption. The code samples below show how to use the APIs defined in each of these modules. Note that this post was written using version 0.16.20 of the library.</p><p><strong>Disclaimer: Make sure you understand what the code is doing before copying into any real world application.</strong></p><h3>Cryptographic Hashes Using the Digest Module</h3><p>See the full post on using the ring::digest module <a href="https://web3developer.io/hash-functions-in-rust-using-ring/">here</a>.</p><pre>use ring::digest;<br>use ring::digest::Digest;<br>use ring::digest::Context;<br>use ring::digest::SHA256;<br><br>fn main() {<br>    // Calculate a hash using the digest function<br>    let _digest: Digest = digest::digest(&amp;SHA256, b&quot;hello, world&quot;);<br><br>    // Calculate a hash using the Context struct<br>    let mut ctx = Context::new(&amp;SHA256);<br>    ctx.update(b&quot;hello, &quot;);<br>    ctx.update(b&quot;world&quot;);<br>    let _digest = ctx.finish();<br>}</pre><h3>Generating Random Numbers Using the Rand Module</h3><p>See the full post on using the ring::rand module <a href="https://web3developer.io/generating-random-numbers-in-rust-using-ring/">here</a>.</p><pre>use ring::error::Unspecified;<br>use ring::rand;<br>use ring::rand::SecureRandom;<br>use ring::rand::SystemRandom;<br>use ring::rand::Random;<br><br>fn main() -&gt; Result&lt;(), Unspecified&gt; {<br>    const NUM_SIZE_BYTES: usize = 32;<br>    let rand = SystemRandom::new();<br><br>    // Generate random number using the SecureRandom::fill method<br>    let mut rand_bytes = [0u8; NUM_SIZE_BYTES];<br>    rand.fill(&amp;mut rand_bytes)?;<br><br>    // Generate random number using the rand::generate function<br>    let result: Random&lt;[u8; NUM_SIZE_BYTES]&gt; = rand::generate(&amp;rand)?;<br>    let _rand_bytes = result.expose();<br><br>    Ok(())<br>}</pre><h3>Signing and Verification Using the HMAC Module</h3><p>See the full post on using the ring::hmac module <a href="https://web3developer.io/signing-and-verifying-messages-with-hmac-in-rust-using-ring/">here</a>.</p><pre>use ring::error::Unspecified;<br>use ring::rand::SystemRandom;<br>use ring::hmac;<br>use ring::hmac::Key;<br>use ring::hmac::Context;<br>use ring::hmac::HMAC_SHA256;<br><br>fn main() -&gt; Result&lt;(), Unspecified&gt; {<br>    let rand = SystemRandom::new();<br>    let key = Key::generate(HMAC_SHA256, &amp;rand)?;<br><br>    // Sign a message and then verify using the hmac::sign function<br>    let tag = hmac::sign(&amp;key, b&quot;hello, world&quot;);<br>    hmac::verify(&amp;key, b&quot;hello, world&quot;, tag.as_ref())?;<br><br>    // Sign a message and then verify using the Context struct<br>    let mut ctx = Context::with_key(&amp;key);<br>    ctx.update(b&quot;hello, &quot;);<br>    ctx.update(b&quot;world&quot;);<br>    let tag = ctx.sign();<br><br>    hmac::verify(&amp;key, b&quot;hello, world&quot;, tag.as_ref())<br>}</pre><h3>Key Derivation Using the HKDF Module</h3><p>See the full post on using the ring::hkdf module <a href="https://web3developer.io/deriving-cryptographic-keys-with-hkdf-in-rust-using-ring/">here</a>.</p><pre>use ring::error::Unspecified;<br>use ring::digest::SHA256_OUTPUT_LEN;<br>use ring::hkdf::Salt;<br>use ring::hkdf::Prk;<br>use ring::hkdf::Okm;<br>use ring::hkdf::Algorithm;<br>use ring::hkdf::HKDF_SHA256;<br><br>fn main() -&gt; Result&lt;(), Unspecified&gt; {<br>    // Derive a single output key using Salt::extract and Prk::expand<br><br>    let input_key_material = b&quot;secret key&quot;;<br>    let salt = Salt::new(HKDF_SHA256, b&quot;salt bytes&quot;);<br>    let pseudo_rand_key: Prk = salt.extract(input_key_material);<br>    <br>    let context_data = [&quot;context field 1&quot;.as_bytes(), &quot;context field 2&quot;.as_bytes()];<br>    let output_key_material: Okm&lt;Algorithm&gt; = pseudo_rand_key.expand(&amp;context_data, HKDF_SHA256)?;<br>    <br>    let mut result = [0u8; SHA256_OUTPUT_LEN];<br>    output_key_material.fill(&amp;mut result)<br>}</pre><h3>Password Hashing Using the PBKDF2 Module</h3><p>See the full post on using the ring::pbkdf2 module <a href="https://web3developer.io/password-hashing-with-pbkdf2-in-rust-using-ring/">here</a>.</p><pre>use ring::error::Unspecified;<br>use std::num::NonZeroU32;<br>use ring::digest::SHA256_OUTPUT_LEN;<br>use ring::pbkdf2;<br>use ring::pbkdf2::PBKDF2_HMAC_SHA256;<br><br>fn main() -&gt; Result&lt;(), Unspecified&gt; {<br>    // Derive a password hash and verify using pbkdf2::derive and pbkdf2::verify<br>    <br>    let iterations = NonZeroU32::new(600_000).unwrap();<br>    let salt = b&quot;random salt&quot;;<br>    let secret = b&quot;strong password&quot;;<br>    <br>    let mut password_hash = [0u8; SHA256_OUTPUT_LEN];<br>    pbkdf2::derive(PBKDF2_HMAC_SHA256, iterations, salt, secret, &amp;mut password_hash);<br>    pbkdf2::verify(PBKDF2_HMAC_SHA256, iterations, salt, secret, &amp;password_hash)  <br>}</pre><h3>Key Exchange Using the Agreement Module</h3><p>See the full post on using the ring::agreement module <a href="https://web3developer.io/ecdh-key-agreement-in-rust-using-ring/">here</a>.</p><pre>use ring::error::Unspecified;<br>use ring::rand::SystemRandom;<br>use ring::agreement;<br>use ring::agreement::Algorithm;<br>use ring::agreement::X25519;<br>use ring::agreement::EphemeralPrivateKey;<br>use ring::agreement::PublicKey;<br>use ring::agreement::UnparsedPublicKey;<br><br>fn main() -&gt; Result&lt;(), Unspecified&gt; {<br>    // Derived a shared secret using ECDH<br><br>    let rng = SystemRandom::new();<br>    let alg: &amp;Algorithm = &amp;X25519;<br>    let my_private_key: EphemeralPrivateKey = EphemeralPrivateKey::generate(alg, &amp;rng)?;<br>    let _my_public_key: PublicKey = my_private_key.compute_public_key()?;<br><br>    // Send our public key to the peer here<br>    let peer_public_key: PublicKey = { // Simulate receiving a public key from the peer<br>        let peer_private_key = EphemeralPrivateKey::generate(alg, &amp;rng)?;<br>        peer_private_key.compute_public_key()?<br>    };<br><br>    let peer_public_key = UnparsedPublicKey::new(alg, peer_public_key);<br>    agreement::agree_ephemeral(my_private_key,<br>                    &amp;peer_public_key,<br>                    |_shared_secret: &amp;[u8]| {<br>                        // use the shared secret<br>                    })<br>}</pre><h3>Signing and Verification Using the Signature Module</h3><p>See the full post on using the ring::signature module <a href="https://web3developer.io/signing-verifying-messages-with-digital-signatures-in-rust-using-ring/">here</a>.</p><pre>use ring::error::Unspecified;<br>use ring::rand::SystemRandom;<br>use ring::signature::ED25519;<br>use ring::signature::KeyPair;<br>use ring::signature::Ed25519KeyPair;<br>use ring::signature::UnparsedPublicKey;<br><br>fn main() -&gt; Result&lt;(), Unspecified&gt; {<br>    // Sign and verify a message using EdDSA<br><br>    let rand = SystemRandom::new();<br>    let pkcs8_bytes = Ed25519KeyPair::generate_pkcs8(&amp;rand)?;<br>    let key_pair = Ed25519KeyPair::from_pkcs8(pkcs8_bytes.as_ref()).map_err(|_| Unspecified)?;<br>    <br>    const MESSAGE: &amp;[u8] = b&quot;hello, world&quot;;<br>    let sig = key_pair.sign(MESSAGE);<br>    <br>    let peer_public_key_bytes = key_pair.public_key().as_ref();<br>    let peer_public_key = UnparsedPublicKey::new(&amp;ED25519, peer_public_key_bytes);<br>    peer_public_key.verify(MESSAGE, sig.as_ref())<br>}</pre><h3>Authenticated Encryption Using the AEAD Module</h3><p>See the full post on using the ring::aead module here.</p><pre>use ring::error::Unspecified;<br>use ring::rand::SecureRandom;<br>use ring::rand::SystemRandom;<br>use ring::aead::AES_256_GCM;<br>use ring::aead::UnboundKey;<br>use ring::aead::BoundKey;<br>use ring::aead::SealingKey;<br>use ring::aead::OpeningKey;<br>use ring::aead::Aad;<br>use ring::aead::NonceSequence;<br>use ring::aead::NONCE_LEN;<br>use ring::aead::Nonce;<br><br>// Always returns the same nonce value for simplicity, don&#39;t use for more than 1 sealing operation!<br>struct SingleNonceSequence([u8; NONCE_LEN]);<br><br>impl NonceSequence for SingleNonceSequence {<br>    fn advance(&amp;mut self) -&gt; Result&lt;Nonce, Unspecified&gt; {<br>        Nonce::try_assume_unique_for_key(&amp;self.0)<br>    }<br>}<br><br>fn main() -&gt; Result&lt;(), Unspecified&gt; {<br>    // Encrypt and decrypt some data using AES-GCM-256<br><br>    let rand = SystemRandom::new();<br><br>    let mut key_bytes = vec![0; AES_256_GCM.key_len()];<br>    rand.fill(&amp;mut key_bytes)?;<br>    let mut nonce_value = [0; NONCE_LEN];<br>    rand.fill(&amp;mut nonce_value)?;<br><br>    let unbound_key = UnboundKey::new(&amp;AES_256_GCM, &amp;key_bytes)?;<br>    let nonce_sequence = SingleNonceSequence(nonce_value);<br>    let mut sealing_key = SealingKey::new(unbound_key, nonce_sequence);<br><br>    let associated_data = Aad::from(b&quot;additional public data&quot;);<br>    let data = b&quot;hello world&quot;;<br>    let mut in_out = data.clone();<br><br>    let tag = sealing_key.seal_in_place_separate_tag(associated_data, &amp;mut in_out)?;<br>    <br>    let unbound_key = UnboundKey::new(&amp;AES_256_GCM, &amp;key_bytes)?;<br>    let nonce_sequence = SingleNonceSequence(nonce_value);<br>    let mut opening_key = OpeningKey::new(unbound_key, nonce_sequence);<br><br>    let associated_data = Aad::from(b&quot;additional public data&quot;);<br>    let mut cypher_text_with_tag = [&amp;in_out, tag.as_ref()].concat();<br>    <br>    let decrypted_data = opening_key.open_in_place(associated_data, &amp;mut cypher_text_with_tag)?;<br>    assert_eq!(data, decrypted_data);<br><br>    Ok(())<br>}</pre><h3>Conclusion</h3><p>In this example code cheatsheet we covered how to use each of the Ring modules to implement cryptography primitives such as hash functions, random numbers, message authentication codes, key derivation, key agreement, digital signatures and authenticated encryption. If you want to read more about any of the topics check out the linked resources above as well.</p><p>Thanks for reading. I hope you find this resource useful. If you have any questions about using the Ring cryptography library, feel free to reach out.</p><p>This article was originally posted on Web3Developer.io: <a href="https://web3developer.io/ring-by-example-sample-code-cheatsheet/">https://web3developer.io/ring-by-example-sample-code-cheatsheet/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c67debd7fc4c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Signing & Verifying Messages with Digital Signatures in Rust using Ring]]></title>
            <link>https://medium.com/@web3developer/signing-verifying-messages-with-digital-signatures-in-rust-using-ring-41f76febd7e7?source=rss-be7c00f02569------2</link>
            <guid isPermaLink="false">https://medium.com/p/41f76febd7e7</guid>
            <category><![CDATA[cryptography]]></category>
            <category><![CDATA[ecdsa]]></category>
            <category><![CDATA[eddsa]]></category>
            <category><![CDATA[rust]]></category>
            <category><![CDATA[digital-signatures]]></category>
            <dc:creator><![CDATA[Web3 Developer]]></dc:creator>
            <pubDate>Fri, 26 May 2023 16:27:21 GMT</pubDate>
            <atom:updated>2023-12-03T16:33:14.568Z</atom:updated>
            <content:encoded><![CDATA[<p>The <a href="https://docs.rs/ring/latest/ring/">Ring</a> cryptography library supports signing and verifying the integrity of messages using digital signatures. In this post I introduce digital signatures and explain how to use the sign and verify methods defined in the ring::signature module to create and then verify signatures for any given message.</p><h3>Introduction to Digital Signatures</h3><p>Digital signatures are similar to message authentication codes in that they provide a way to check the integrity and authenticity of messages (see my post on HMAC <a href="https://web3developer.io/signing-and-verifying-messages-with-hmac-in-rust-using-ring/">here</a>) but they additionally provide non-repudiation. This is because MACs use a symmetric key as the secret where as digital signatures use a public/private key pair. The signature is produce by using the private key to sign a message and then later the signature can be checked against the message using the public key to determine if the signature is valid for that message.</p><p>If a signature successfully verifies then we can be sure that the message has not been modified and that it originated from the owner of the private key which is associated with the public key. This means that the owner of the private key cannot deny sending the message because of the valid signature associated with the message and hence we have non-repudiation.</p><p>The interface of a digital signature <strong>sign</strong> function looks something like this:</p><pre>signature = sign(private_key, message)</pre><p>The interface of a digital signature <strong>verify</strong> function looks something like this:</p><pre>result = verify(public_key, message, signature)</pre><p>Result is a boolean where true means that the signature is valid over the message and false means that the signature verification has failed.</p><p>Internally digital signature algorithms use asymmetric cryptography where public/private key pairs are used for encryption and decryption. To generate a signature the message to be signed is first hashed using a cryptographically secure hash function and then the hash is encrypted using the private key. To verify the signature the encrypted hash is decrypted using the public key and the message is hashed to verify that it matches the decrypted hash value. Messages are hashed in this way because asymmetric encryption can only encrypt values of limited size and it is also much slower then symmetric encryption in terms of performance.</p><h3>Introduction to ECDSA &amp; EdDSA</h3><p>In the code examples below I will show how to sign and verify messages using both <strong>ECDSA</strong> and <strong>EdDSA</strong> digital signature algorithms so lets start with a bit of background.</p><p><strong>Elliptic Curve Digital Signature Algorithm </strong><a href="https://en.wikipedia.org/wiki/Elliptic_Curve_Digital_Signature_Algorithm"><strong>(ECDSA)</strong></a> is a cryptographically secure digital signature scheme based on elliptic-curve cryptography (ECC). It relies on the math of the cyclic groups of elliptic curves over finite fields and on the difficulty of the elliptic-curve discrete logarithm problem. The signature algorithm uses a random nonce as an input which must not be re-used and must be completely unpredictable. In order to get 128 bits of security (relative to symmetric cryptography) we can use 256 bit key pairs which will generate 64 byte signatures.</p><p><strong>Edwards-curve Digital Signature Algorithm </strong><a href="https://en.wikipedia.org/wiki/EdDSA"><strong>(EdDSA)</strong></a> is a digital signature scheme that uses a variant of Schnorr signature based on twisted Edwards curves. It is designed to be faster than existing digital signature schemes without sacrificing security. EdDSA signatures use the Edwards form of elliptic curves and the algorithm relies on the difficulty of the elliptic-curve discrete logarithm problem. As was the case above, EdDSA provides 128 bits of security when used with 256 bit keys (such as Ed25519) which generate 64 byte signatures.</p><h3>Summary of Types</h3><p>The ring::signature module contains the following types and functions:</p><p><strong>trait KeyPair</strong> — Key pairs for signing messages (private key and public key). Each of the key pairs for the various digital signature algorithms implement this trait.</p><p><strong>trait VerificationAlgorithm</strong> — A signature verification algorithm. Each of the various signature verification algorithms implement this trait.</p><p><strong>struct Signature</strong> — A public key signature returned from a signing operation. This is basically a wrapper around the signature byte array.</p><p><strong>struct UnparsedPublicKey</strong> — An unparsed, possibly malformed, public key for signature verification. The message and signature is passed into the verify message which is a method on the public key type. This design enforces validation/parsing of the public key before verifying a signature which is an important security consideration to prevent certain vulnerabilities.</p><p>For a full listing of all types see the module documentation <a href="https://docs.rs/ring/latest/ring/signature">here</a>.</p><h3>Rust Imports</h3><p>Let’s start by importing the required types into our project.</p><pre>use ring::error::Unspecified;<br>use ring::rand::SystemRandom;<br>use ring::signature;<br>use ring::signature::KeyPair;<br>use ring::signature::UnparsedPublicKey;<br>use ring::signature::EcdsaKeyPair;<br>use ring::signature::Ed25519KeyPair;<br>use ring::signature::ECDSA_P256_SHA256_ASN1;<br>use ring::signature::ECDSA_P256_SHA256_ASN1_SIGNING;<br>use ring::signature::ED25519;</pre><h3>Signing &amp; Verifying a Message using ECDSA</h3><p>In the example below we use the ECDSA_P256_SHA256_ASN1_SIGNING algorithm for signing a message and the ECDSA_P256_SHA256_ASN1 algorithm for verifying the signature.</p><p>First start by generating a new ECDSA key pair using an instance of SystemRandom as the source of entropy (for more background on generating random numbers in Rust see <a href="https://web3developer.io/generating-random-numbers-in-rust-using-ring/">here</a>). First create the key pair in pkcs8 document format which can be used to persist the key if needed and then we convert it into an EcdsaKeyPair.</p><pre>// generate a new ECDSA key pair<br>let rand = SystemRandom::new();<br>let pkcs8_bytes = EcdsaKeyPair::generate_pkcs8(&amp;ECDSA_P256_SHA256_ASN1_SIGNING, &amp;rand)?; // pkcs8 format used for persistent storage<br>let key_pair = EcdsaKeyPair::from_pkcs8(&amp;ECDSA_P256_SHA256_ASN1_SIGNING, pkcs8_bytes.as_ref(), &amp;rand).map_err(|_| Unspecified)?;</pre><p>We then create a message and sign it by passing in the message to the sign method which returns the the signature on success. Note that the SystemRandom is used in the sign method to generate a random nonce for each signature. The nonce must be random and never re-used so you should make sure that only a single instance of SystemRandom is used throughout the program in order to prevent the possibility of using the same source of entropy multiple times.</p><pre>// create a message and sign using the key pair<br>const MESSAGE: &amp;[u8] = b&quot;hello, world&quot;;<br>let sig = key_pair.sign(&amp;rand, MESSAGE)?;</pre><p>The public key is then passed into a new instance of UnparsedPublicKey. Next the verify method is called on the UnparsedPublicKey instance passing in the message and signature bytes. The verify method returns () on success and error::Unspecified otherwise.</p><pre>// get the public key as bytes<br>let peer_public_key_bytes = key_pair.public_key().as_ref();<br><br>// verify the signature using the public key and message<br>let peer_public_key = UnparsedPublicKey::new(&amp;ECDSA_P256_SHA256_ASN1, peer_public_key_bytes);<br>peer_public_key.verify(MESSAGE, sig.as_ref())?;</pre><h3>Signing &amp; Verifying a Message using EdDSA</h3><p>Here is another example which is similar to the above scenario but instead this time we use EdDSA for signing and verification. Note that the signing method doesn’t require passing in the SystemRandom instance in this case. We use the default EdDSA signing algorithm and the ED25519 verification algorithm.</p><pre>// generate a new Ed25519 key pair<br>let rand = SystemRandom::new();<br>let pkcs8_bytes = Ed25519KeyPair::generate_pkcs8(&amp;rand)?; // pkcs8 format used for persistent storage<br>let key_pair = Ed25519KeyPair::from_pkcs8(pkcs8_bytes.as_ref()).map_err(|_| Unspecified)?;<br><br>// create a message and sign using the key pair<br>const MESSAGE: &amp;[u8] = b&quot;hello, world&quot;;<br>let sig = key_pair.sign(MESSAGE);<br><br>// get the public key as bytes<br>let peer_public_key_bytes = key_pair.public_key().as_ref();<br><br>// verify the signature using the public key and message<br>let peer_public_key = UnparsedPublicKey::new(&amp;ED25519, peer_public_key_bytes);<br>peer_public_key.verify(MESSAGE, sig.as_ref())</pre><h3>Full Sample Code</h3><p>Here is the full code sample for reference.</p><pre>use ring::error::Unspecified;<br>use ring::rand::SystemRandom;<br>use ring::signature;<br>use ring::signature::KeyPair;<br>use ring::signature::UnparsedPublicKey;<br>use ring::signature::EcdsaKeyPair;<br>use ring::signature::Ed25519KeyPair;<br>use ring::signature::ECDSA_P256_SHA256_ASN1;<br>use ring::signature::ECDSA_P256_SHA256_ASN1_SIGNING;<br>use ring::signature::ED25519;<br><br>fn main() -&gt; Result&lt;(), Unspecified&gt; {<br>    // generate a new ECDSA key pair<br>    let rand = SystemRandom::new();<br>    let pkcs8_bytes = EcdsaKeyPair::generate_pkcs8(&amp;ECDSA_P256_SHA256_ASN1_SIGNING, &amp;rand)?; // pkcs8 format used for persistent storage<br>    let key_pair = EcdsaKeyPair::from_pkcs8(&amp;ECDSA_P256_SHA256_ASN1_SIGNING, pkcs8_bytes.as_ref(), &amp;rand).map_err(|_| Unspecified)?;<br>    <br>    // create a message and sign using the key pair<br>    const MESSAGE: &amp;[u8] = b&quot;hello, world&quot;;<br>    let sig = key_pair.sign(&amp;rand,MESSAGE)?;<br>    <br>    // get the public key as bytes<br>    let peer_public_key_bytes = key_pair.public_key().as_ref();<br>    // verify the signature using the public key and message<br>    let peer_public_key = UnparsedPublicKey::new(&amp;ECDSA_P256_SHA256_ASN1, peer_public_key_bytes);<br>    peer_public_key.verify(MESSAGE, sig.as_ref())?;<br>    <br>    // generate a new Ed25519 key pair<br>    let pkcs8_bytes = Ed25519KeyPair::generate_pkcs8(&amp;rand)?; // pkcs8 format used for persistent storage<br>    let key_pair = Ed25519KeyPair::from_pkcs8(pkcs8_bytes.as_ref()).map_err(|_| Unspecified)?;<br>    <br>    // create a message and sign using the key pair<br>    let sig = key_pair.sign(MESSAGE);<br>    <br>    // get the public key as bytes<br>    let peer_public_key_bytes = key_pair.public_key().as_ref();<br>    <br>    // verify the signature using the public key and message<br>    let peer_public_key = UnparsedPublicKey::new(&amp;ED25519, peer_public_key_bytes);<br>    peer_public_key.verify(MESSAGE, sig.as_ref())<br>}</pre><h3>Conclusion</h3><p>In this post I gave a brief introduction to digital signatures, introduced the signature module in the Ring cryptography library and gave a few examples showing how to create and verify signatures. I demonstrated how to use the sign method defined on the key pair types to return an instance of Signature and then how to use the verify method defined on the UnparsedPublicKey type to check signatures for validity.</p><p>This article was originally posted on Web3Developer.io: <a href="https://web3developer.io/signing-verifying-messages-with-digital-signatures-in-rust-using-ring/">https://web3developer.io/signing-verifying-messages-with-digital-signatures-in-rust-using-ring/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=41f76febd7e7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ECDH Key Agreement in Rust using Ring]]></title>
            <link>https://medium.com/@web3developer/ecdh-key-agreement-in-rust-using-ring-eb8c728fcf15?source=rss-be7c00f02569------2</link>
            <guid isPermaLink="false">https://medium.com/p/eb8c728fcf15</guid>
            <category><![CDATA[ring]]></category>
            <category><![CDATA[cryptography]]></category>
            <category><![CDATA[rust]]></category>
            <category><![CDATA[key-exchange]]></category>
            <category><![CDATA[ecdh]]></category>
            <dc:creator><![CDATA[Web3 Developer]]></dc:creator>
            <pubDate>Wed, 17 May 2023 08:34:42 GMT</pubDate>
            <atom:updated>2023-12-03T16:27:28.399Z</atom:updated>
            <content:encoded><![CDATA[<p>In this post I show you how to implement an ECDH key exchange using the agreement module of the Rust cryptography library <a href="https://docs.rs/ring/latest/ring/">Ring</a>. We will go through generating a public/private key pair, exchanging public keys with a peer and then using the agree_ephemeral function to securely compute a shared secret.</p><h3>Introduction to ECDH</h3><p><a href="https://en.wikipedia.org/wiki/Elliptic-curve_Diffie%E2%80%93Hellman"><strong>Elliptic-curve Diffie-Hellman</strong></a><strong> (ECDH)</strong> is a key agreement protocol which allows two parties to compute a shared secret over an insecure channel using elliptic curve public/private key pairs. It is based on the earlier <a href="https://en.wikipedia.org/wiki/Diffie%E2%80%93Hellman_key_exchange"><strong>Diffie-Hellman</strong></a> protocol which uses modular exponentiation and whose security is based on the difficulty of solving the discrete logarithm problem. For more details on the classical Diffie-Hellman protocol see <a href="https://brilliant.org/wiki/diffie-hellman-protocol/">here</a>. ECDH is faster and considered more secure than classical Diffie-Hellman and therefore ECDH should generally be preferred for modern applications. It is usually used as one step in a larger protocol to establish a shared secret to be used in subsequent operations as a symmetric encryption key.</p><p>From a high level, Diffie-Hellman works as follows (for both classical Diffie-Hellman &amp; ECDH). Both parties in the key exchange do the following steps:</p><ol><li><strong>Generate a new private key</strong> — This key must be kept secret and never shared.</li><li><strong>Compute a new public key from the private key</strong> — There is a special mathematical relationship between the public key and private key which is based on the chosen key agreement algorithm.</li><li><strong>Share the public key with the peer</strong> — This peer could be a client or server.</li><li><strong>Receive the peer’s public key and validate</strong> — The peer’s public key needs to be validated for correctness before using.</li><li><strong>Use our private key and the peer’s validated public key to produce the shared secret</strong> — Due to the mathematics of the protocol our private key combined with our peers public key is equal to our peers private key combined with our public key. To understand the details of why this works you will need to read up on the mathematics of DH/ECDH but I won’t be covering that in this post.</li></ol><h3>ECDH Usage Guidelines</h3><ul><li>ECDH prevents a passive man-in-the-middle (MITM) attacker from being able to obtain the shared secret.</li><li>ECDH by default does not protect against an active MITM attacker from impersonating the peer during the key exchange, so additional authentication mechanisms are needed to authenticate each peer if we need to protect against an active MITM attacker. For example, we could have the server generate a long term public/private key pair and then have the client include a known copy of the public key. During the key exchange the client can check that the public key matches what it expects. This is called an authenticated key exchange. If both sides perform the same form of authentication to the peer than it is called a mutually authenticated key exchange.</li><li>The keys used on either side of a ECDH key exchange can be static (long term) or ephemeral and each configuration has pros and cons. The combinations are listed below with their pros and cons:</li><li>Ephemeral to ephemeral — Most common scenario for key agreement. Provides forward secrecy but no authenticity on either side of the exchange.</li><li>Static to static — Generates a long term shared secret so provides no forward secrecy. Provides authenticity on both sides.</li><li>Ephemeral to static — Provides no forward secrecy. Static side can be authenticated by the ephemeral side.</li><li>The current minimum recommended key length for classical Diffie-Hellman is 2,048-bits and for ECDH is 256-bits. Applications with higher security requirements can use DH keys with 3072-bits or ECDH keys with 384-bits.</li><li>ECDH can be used with a selection of standardised elliptic curves. Ring supports three curves that are considered secure and safe to use; P-256 and P-384 by NIST and X25519 by Daniel J. Bernstein. X25519 is a good default if you are unsure which to use.</li><li>As recommended in RFC 7748 you should apply a KDF to the computed shared secret before using as a session key or other in a real application.</li></ul><h3>Summary of Types</h3><p>The ring::agreement module contains the following types and functions:</p><p><strong>struct Algorithm </strong>— The type of ECDH algorithm. ECDH_P256, ECDH_P384 and X25519 algorithms are supported.</p><p><strong>struct EphemeralPrivateKey </strong>— An ephemeral private key for use (only) with agree_ephemeral. The signature of agree_ephemeral ensures that an EphemeralPrivateKey can be used for at most one key agreement.</p><p><strong>struct PublicKey </strong>— A public key for key agreement.</p><p><strong>struct UnparsedPublicKey </strong>— An unparsed, possibly malformed, public key for key agreement.</p><p><strong>fn agree_ephemeral </strong>— Performs a key agreement with an ephemeral private key and the given public key.</p><pre>pub fn agree_ephemeral&lt;B: AsRef&lt;[u8]&gt;, R&gt;(<br>    my_private_key: EphemeralPrivateKey,<br>    peer_public_key: &amp;UnparsedPublicKey&lt;B&gt;,<br>    kdf: impl FnOnce(&amp;[u8]) -&gt; R,<br>) -&gt; Result&lt;R, error::Unspecified&gt;</pre><p>See the ring::agreement module documentation <a href="https://docs.rs/ring/latest/ring/agreement">here</a>.</p><h3>Rust Imports</h3><p>Let’s start by importing the required types into our project.</p><pre>use ring::error::Unspecified;<br>use ring::rand::SystemRandom;<br>use ring::agreement::Algorithm;<br>use ring::agreement::ECDH_P256;<br>use ring::agreement::ECDH_P384;<br>use ring::agreement::X25519;<br>use ring::agreement::EphemeralPrivateKey;<br>use ring::agreement::PublicKey;<br>use ring::agreement::UnparsedPublicKey;<br>use ring::agreement::agree_ephemeral;</pre><h3>Generate our Public/Private Key Pair</h3><p>Here we start by creating an instance of SystemRandom which is used as a source of entropy for generating the private key. We then select the key agreement algorithm to use, in this case we are using X25519. We then call EphemeralPrivateKey::generate to generate the private key and then we compute the public key from the private key using EphemeralPrivateKey::compute_public_key.</p><pre>// Use a rand::SystemRandom as the source of entropy<br>let rng = SystemRandom::new();<br><br>// Select a key agreement algorithm. All agreement algorithms follow the same flow<br>let alg: &amp;Algorithm = &amp;X25519;<br><br>// Generate a private key and public key<br>let my_private_key: EphemeralPrivateKey = EphemeralPrivateKey::generate(alg, &amp;rng)?;<br>let my_public_key: PublicKey = my_private_key.compute_public_key()?;<br><br>// The EphemeralPrivateKey type doesn&#39;t allow us to directly access the private key as designed<br>println!(&quot;my_public_key = {}&quot;, hex::encode(my_public_key.as_ref()));</pre><h3>Exchange Public Keys with Peer</h3><p>In this first example we are simply simulating sending and receiving the public keys with a peer, just to show the steps. We then create an instance of UnparsedPublicKey which will be used to parse and validate the public key later.</p><pre>// Send our public key to the peer here<br><br>// Simulate receiving a public key from the peer<br>let peer_public_key: PublicKey = {<br>    let peer_private_key = EphemeralPrivateKey::generate(alg, &amp;rng)?;<br>    peer_private_key.compute_public_key()?<br>};<br>println!(&quot;peer_public_key = {}&quot;, hex::encode(peer_public_key.as_ref()));<br><br>// The peer public key needs to be parsed before use so wrap it creating as an instance of UnparsedPublicKey<br>let peer_public_key = UnparsedPublicKey::new(alg, peer_public_key);</pre><h3>Compute the Shared Secret</h3><p>Then the final step is to run the agree_ephemeral function which takes our private key, the peer&#39;s public key, the error to return on failure and a lambda which gets called with the computed shared secret passed as a parameter. Note that RFC 7748 recommends applying a KDF to the shared secret before usage.</p><pre>// run ECDH to agree on a shared secret<br>agree_ephemeral(my_private_key,<br>                &amp;peer_public_key,<br>                |shared_secret: &amp;[u8]| { // the result of the key agreement is passed to this lambda<br>                    println!(&quot;shared_secret = {}&quot;, hex::encode(shared_secret.as_ref())); // don&#39;t print this in production<br><br>                    // As recommended in RFC 7748 we should apply a KDF on the key material here before using in a real application<br>                    // We can return the derived key from the kdf here, otherwise we just return () if the key isn&#39;t needed outside this scope<br>                })</pre><p>Running the code gives the following output:</p><pre>my_public_key = 0b226d3e97b342d800a681cafbb79f0a151122562a306983f48e4841ea8dc714<br>peer_public_key = df5e6313fec0909914c686b63578b9aeee13ab3f49300c5e692bf3a204ed2475<br>shared_secret = cb210ba8b6909dd7a4d9c5a0c5e28329f142780cdfb556594e55efe390deb735</pre><h3>Client-Server Key Exchange over TCP</h3><p>In this second example we start a tcp server in another thread and then connect to it as a tcp client in the main thread. The call to server.join blocks the main thread until the child thread completes. The ecdh_x25519 function runs the full ECDH protocol as described above except the public keys are exchanged over the tcp stream after the connection is established.</p><pre>use std::thread;<br>use std::net::{TcpListener, TcpStream};<br>use std::io::{Read, Write};<br><br>fn main() {<br>    let server = thread::spawn(move || {<br>        let listener = TcpListener::bind(&quot;127.0.0.1:8080&quot;).unwrap();<br>        let mut stream = listener.accept().unwrap().0;<br><br>        ecdh_x25519(&quot;server&quot;, &amp;mut stream).unwrap();<br>    });<br><br>    let mut stream = TcpStream::connect(&quot;127.0.0.1:8080&quot;).unwrap();<br>    ecdh_x25519(&quot;client&quot;, &amp;mut stream).unwrap();<br><br>    server.join().unwrap();<br>}</pre><p>Running the code gives the following output. As you can see the server_shared_secret and server_shared_secret values match as expected:</p><pre>client_public_key = 648185523469cf6678912c9e9b24b243851b2137ed065729621e4ecba4ef1564<br>server_public_key = c7a92fe60880181d7c11ac688c98be671dff7892cfc51de10563be41f48d264d<br>server_peer_public_key = 648185523469cf6678912c9e9b24b243851b2137ed065729621e4ecba4ef1564<br>client_peer_public_key = c7a92fe60880181d7c11ac688c98be671dff7892cfc51de10563be41f48d264d<br>server_shared_secret = 3ab034715237b6d34ec14b3f65c66418cd715284febf3f9102553ec8f5aa8a4d<br>client_shared_secret = 3ab034715237b6d34ec14b3f65c66418cd715284febf3f9102553ec8f5aa8a4d</pre><h3>Full Sample Code</h3><p>Here is the full code sample for reference. Note that this example is not production ready code due to the usage of calls to unwrap and the limited error checking in the code that sends and receives the public keys over the TCP streams.</p><pre>use ring::error::Unspecified;<br>use ring::rand::SystemRandom;<br>use ring::agreement::Algorithm;<br>use ring::agreement::ECDH_P256;<br>use ring::agreement::ECDH_P384;<br>use ring::agreement::X25519;<br>use ring::agreement::EphemeralPrivateKey;<br>use ring::agreement::PublicKey;<br>use ring::agreement::UnparsedPublicKey;<br>use ring::agreement::agree_ephemeral;<br>use std::thread;<br>use std::net::{TcpListener, TcpStream};<br>use std::io::{Read, Write};<br><br><br>fn main() {<br>    let server = thread::spawn(move || {<br>        let listener = TcpListener::bind(&quot;127.0.0.1:8080&quot;).unwrap();<br>        let mut stream = listener.accept().unwrap().0;<br><br>        ecdh_x25519(&quot;server&quot;, &amp;mut stream).unwrap();<br>    });<br><br>    let mut stream = TcpStream::connect(&quot;127.0.0.1:8080&quot;).unwrap();<br>    ecdh_x25519(&quot;client&quot;, &amp;mut stream).unwrap();<br><br>    server.join().unwrap();<br>}<br><br>fn ecdh_x25519(actor: &amp;str, stream: &amp;mut TcpStream) -&gt; Result&lt;(), Unspecified&gt; {<br>    // Use a rand::SystemRandom as the source of entropy<br>    let rng = SystemRandom::new();<br>    <br>    // Select a key agreement algorithm. All agreement algorithms follow the same flow<br>    let alg: &amp;Algorithm = &amp;X25519;<br>    <br>    // Generate a private key and public key<br>    let my_private_key: EphemeralPrivateKey = EphemeralPrivateKey::generate(alg, &amp;rng)?;<br>    let my_public_key: PublicKey = my_private_key.compute_public_key()?;<br>    <br>    // The EphemeralPrivateKey doesn&#39;t allow us to directly access the private key as designed<br>    println!(&quot;{}_public_key = {}&quot;, actor, hex::encode(my_public_key.as_ref()));<br>    <br>    // Send our public key to the peer here<br>    stream.write_all(my_public_key.as_ref()).unwrap();<br>    <br>    // Simulate receiving a public key from the peer<br>    let mut peer_public_key = [0u8; 32];<br>    stream.read_exact(&amp;mut peer_public_key).unwrap();<br>    println!(&quot;{}_peer_public_key = {}&quot;, actor, hex::encode(peer_public_key.as_ref()));<br>    <br>    // The peer public key needs to be parsed before use so wrap it creating as an instance of UnparsedPublicKey<br>    let peer_public_key = UnparsedPublicKey::new(alg, peer_public_key);<br>    <br>    // run ECDH to agree on a shared secret<br>    agree_ephemeral(my_private_key,<br>                    &amp;peer_public_key,<br>                    |shared_secret: &amp;[u8]| { // the result of the key agreement is passed to this lambda<br>                        println!(&quot;{}_shared_secret = {}&quot;, actor, hex::encode(shared_secret.as_ref())); // don&#39;t print this in production<br>                        <br>                        // As recommended in RFC 7748 we should apply a KDF on the key material here before using in a real application<br>                        // We can return the derived key from the kdf here, otherwise we just return () if the key isn&#39;t needed outside this scope<br>                    })<br>}</pre><h3>Conclusion</h3><p>In this post I introduced the ECDH protocol, explained what it is used for and the high level algorithm which allows us to securely compute a shared secret over an insecure medium using public/private key cryptography. Then we covered how to use the agreement module of the Ring cryptography library to implement ECDH in our applications by using the EphemeralPrivateKey, PublicKey and UnparsedPublicKey types and then calling the agree_ephemeral function. We went through two examples, the first a very simple example which only simulates the key exchange with the peer and the second which actually connects to the peer over a tcp connection and does the full key exchange.</p><p>This article was originally posted on Web3Developer.io: <a href="https://web3developer.io/ecdh-key-agreement-in-rust-using-ring/">https://web3developer.io/ecdh-key-agreement-in-rust-using-ring/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=eb8c728fcf15" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Introducing Fluent Hash — A Rust Hashing Library with a Fluent Interface]]></title>
            <link>https://medium.com/@web3developer/introducing-fluent-hash-a-rust-hashing-library-with-a-fluent-interface-a7c2786439fb?source=rss-be7c00f02569------2</link>
            <guid isPermaLink="false">https://medium.com/p/a7c2786439fb</guid>
            <category><![CDATA[fluent-hash]]></category>
            <category><![CDATA[ring]]></category>
            <category><![CDATA[rust]]></category>
            <category><![CDATA[hash-function]]></category>
            <category><![CDATA[cryptography]]></category>
            <dc:creator><![CDATA[Web3 Developer]]></dc:creator>
            <pubDate>Wed, 10 May 2023 09:10:03 GMT</pubDate>
            <atom:updated>2023-12-03T15:44:38.749Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introducing Fluent Hash — A Rust Hashing Library with a Fluent Interface</h3><p>fluent-hash is a new open source Rust library which I recently published to crates.io (see <a href="https://crates.io/crates/fluent-hash">here</a>). I wanted to try creating and publishing a Rust library and so I thought I’d start with something simple and hopefully useful for other developers. It is a simple and lightweight hashing library which provides a fluent interface for creating and formatting hash values. It builds upon the foundations of the trusted cryptography library Ring (which is currently one of the most popular libraries in the Rust cryptography space), by providing a thin wrapper on top of Ring’s digest module. See the Github link for the new project <a href="https://github.com/web3-developer/fluent-hash">here</a>.</p><p>In this post I will show you how to import the library into your Rust project and how to use the Hashing, Hash and HashContext types for creating hashes from various data types. I also show you how to format Hash values as bytes or hexadecimal using the provided convenience methods.</p><p><strong>Note that this library is new and has not been audited or formally verified so use at your own risk.</strong></p><h3>What is a Fluent Interface?</h3><p>From Wikipedia: ‘In software engineering, a fluent interface is an object-oriented API whose design relies extensively on method chaining. Its goal is to increase code legibility by creating a domain-specific language (DSL).’</p><p>This basically means we can make a library easier to use and make the code more readible by designing the library in a way that allows the user to chain simple method calls together. As you will see in this post, fluent-hash uses this design pattern.</p><h3>Summary of Types</h3><p>The fluent-hash library contains the following types:</p><p><strong>enum Hashing </strong>— The hashing algorithm. Supports selecting from the following algorithms: Sha1, Sha256, Sha384, Sha512 and Sha512_256. Implements convenience methods such as hash, hash_vec, hash_str and hash_file for producing digests from various data types. These convenience methods return an instance of the Hash struct.</p><p><strong>struct Hash </strong>— A hash value which holds the digest produced by one of the Hashing algorithms. Supports formatting as a byte array, byte vector or a hexadecimal string.</p><p><strong>struct HashContext</strong> — A context to be used for multi-step hash calculations. Useful when hashing a data structure with multiple fields or when hashing larger inputs.</p><p>See the full Rust library documentation <a href="https://docs.rs/fluent-hash">here</a>.</p><h3>Getting Started</h3><p>To get started using fluent-hash, add the library as a dependancy to your Rust Cargo.toml file.</p><pre>[dependencies]<br>fluent-hash = &quot;0.2.3&quot;</pre><h3>Rust Imports</h3><p>Let’s start by importing the required types into our project. In this example we are importing all the fluent-hash types including the Hashing enum values.</p><pre>use fluent_hash::Hashing::Sha1;<br>use fluent_hash::Hashing::Sha256;<br>use fluent_hash::Hashing::Sha384;<br>use fluent_hash::Hashing::Sha512;<br>use fluent_hash::Hashing::Sha512_256;<br>use fluent_hash::Hashing;<br>use fluent_hash::HashContext;<br>use fluent_hash::Hash;</pre><h3>Hashing a Byte Array</h3><p>In this example we are using the SHA-1 hashing algorithm and hashing the bytes of the string ‘hello, world’.</p><pre>let hash: Hash = Sha1.hash(b&quot;hello, world&quot;);</pre><h3>Hashing a Byte Vector</h3><p>Here we run the SHA-256 hashing algorithm on a vector of bytes from the string ‘hello, world’.</p><pre>let hash: Hash = Sha256.hash_vec(b&quot;hello, world&quot;.to_vec());</pre><h3>Hashing a String</h3><p>Here we run the SHA-384 hashing algorithm on the string ‘hello, world’.</p><pre>let hash: Hash = Sha384.hash_str(&quot;hello, world&quot;);</pre><h3>Hashing a File</h3><p>In this example we create a text file containing the string ‘hello, world’ and then run it through the SHA-512 hashing algorithm.</p><pre>let mut file = File::create(&quot;file.txt&quot;)?;<br>file.write_all(b&quot;hello, world&quot;)?;<br>file.sync_all()?;<br>let hash: Hash = Sha512.hash_file(&quot;file.txt&quot;)?;</pre><p>The hash_file method also supports error handling.</p><pre>let error: Error = match Sha512.hash_file(&quot;notfound.txt&quot;) {<br>    Ok(_) =&gt; panic!(&quot;Expecting std::io::Error&quot;),<br>    Err(e) =&gt; e<br>};</pre><h3>Using the HashContext</h3><p>Here we use the lower level HashContext type to manually pass data into the hash function in chunks. This can be useful when hashing a data structure with multiple fields or when hashing larger inputs.</p><pre>let mut ctx: HashContext = Sha512_256.new_context();<br>ctx.update(b&quot;hello, world&quot;);<br>ctx.update(b&quot;more data&quot;);<br>let hash = ctx.finish();</pre><h3>Formatting the Hash</h3><p>fluent-hash supports formatting hash values as bytes or hexadecimal using the convenience methods provided on the Hash type.</p><pre>let bytes: &amp;[u8] = hash.as_bytes();<br>let bytes_vec: Vec&lt;u8&gt; = hash.to_vec();<br>let hex: String = hash.to_hex();<br>println!(&quot;bytes = {:?}&quot;, bytes);<br>println!(&quot;bytes_vec = {:?}&quot;, bytes_vec);<br>println!(&quot;hex = {}&quot;, hex);</pre><h3>Fluent Interface Method Chaining</h3><p>The fluent interface allows you to use method chaining to easily calculate a hash for a given algorithm returning it in the desired format. The resulting code is clean and readable.</p><pre>let result = Hashing::Sha256<br>    .hash(b&quot;hello, world&quot;)<br>    .to_hex();<br>println!(&quot;result = {}&quot;, result);</pre><h3>Full Sample Code</h3><p>Here is the full code sample for reference.</p><pre>use std::fs::File;<br>use std::io::Write;<br>use std::io::Error;<br>use fluent_hash::Hashing::Sha1;<br>use fluent_hash::Hashing::Sha256;<br>use fluent_hash::Hashing::Sha384;<br>use fluent_hash::Hashing::Sha512;<br>use fluent_hash::Hashing::Sha512_256;<br>use fluent_hash::Hashing;<br>use fluent_hash::HashContext;<br>use fluent_hash::Hash;<br><br><br>fn main() -&gt; Result&lt;(), Error&gt; {<br>    // Hashing a byte array<br>    let hash: Hash = Sha1.hash(b&quot;hello, world&quot;);<br><br>    // Hashing a byte vector<br>    let hash: Hash = Sha256.hash_vec(b&quot;hello, world&quot;.to_vec());<br><br>    // Hashing a string<br>    let hash: Hash = Sha384.hash_str(&quot;hello, world&quot;);<br><br>    // Hashing a file<br>    let mut file = File::create(&quot;file.txt&quot;)?;<br>    file.write_all(b&quot;hello, world&quot;)?;<br>    file.sync_all()?;<br>    let hash: Hash = Sha512.hash_file(&quot;file.txt&quot;)?;<br><br>    // Hashing a file supports error handling<br>    let error: Error = match Sha512.hash_file(&quot;notfound.txt&quot;) {<br>        Ok(_) =&gt; panic!(&quot;Expecting std::io::Error&quot;),<br>        Err(e) =&gt; e<br>    };<br><br>    // Using the HashContext<br>    let mut ctx: HashContext = Sha512_256.new_context();<br>    ctx.update(b&quot;hello, world&quot;);<br>    ctx.update(b&quot;more data&quot;);<br>    let hash = ctx.finish();<br><br>    // Format the hash<br>    let bytes: &amp;[u8] = hash.as_bytes();<br>    let bytes_vec: Vec&lt;u8&gt; = hash.to_vec();<br>    let hex: String = hash.to_hex();<br>    println!(&quot;bytes = {:?}&quot;, bytes);<br>    println!(&quot;bytes_vec = {:?}&quot;, bytes_vec);<br>    println!(&quot;hex = {}&quot;, hex);<br><br>    // Fluent interface supports method chaining<br>    let result = Hashing::Sha256<br>        .hash(b&quot;hello, world&quot;)<br>        .to_hex();<br>    println!(&quot;result = {}&quot;, result);<br>    Ok(())<br>}</pre><h3>Conclusion</h3><p>In this post I introduced the fluent-hash library and showed how you can use it to generate SHA-1 and SHA-2 hashes by using the provided Hashing, Hash and HashContext types. I also explained the fluent interface design pattern and showed how fluent-hash uses method chaining to provide an easy to use interface and supports creating clean and readable code.</p><p>Here are the links to the library and documentation for reference:</p><p><a href="https://github.com/web3-developer/fluent-hash">https://github.com/web3-developer/fluent-hash</a></p><p><a href="https://crates.io/crates/fluent-hash">https://crates.io/crates/fluent-hash</a></p><p><a href="https://docs.rs/fluent-hash">https://docs.rs/fluent-hash</a></p><p>This article was originally posted on Web3Developer.io: <a href="https://web3developer.io/introducing-fluent-hash/">https://web3developer.io/introducing-fluent-hash/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a7c2786439fb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Password Hashing with PBKDF2 in Rust using Ring]]></title>
            <link>https://medium.com/@web3developer/password-hashing-with-pbkdf2-in-rust-using-ring-3e033bf08cf4?source=rss-be7c00f02569------2</link>
            <guid isPermaLink="false">https://medium.com/p/3e033bf08cf4</guid>
            <category><![CDATA[cryptography]]></category>
            <category><![CDATA[ring]]></category>
            <category><![CDATA[pbkdf2]]></category>
            <category><![CDATA[rust]]></category>
            <dc:creator><![CDATA[Web3 Developer]]></dc:creator>
            <pubDate>Thu, 27 Apr 2023 17:00:04 GMT</pubDate>
            <atom:updated>2023-04-28T02:05:52.436Z</atom:updated>
            <content:encoded><![CDATA[<p>The <a href="https://docs.rs/ring/latest/ring/">Ring</a> cryptography library provides an implementation of <a href="https://en.wikipedia.org/wiki/PBKDF2"><strong>PBKDF2</strong></a>, a standardised key derivation function that can be used to securely hash passwords. Using the ring::pbkdf2 module, we can derive a password hash and then also verify whether or not a hash matches a given password.</p><h3>Introduction to PBKDF2</h3><p><strong>Password Based Key Derivation Function 2</strong> (PBKDF2) is specified in <a href="https://tools.ietf.org/html/rfc2898#section-5.2">RFC 2898 Section 5.2</a>. PBKDF2 is not a very modern algorithm but it is still considered secure as long as it is used correctly with carefully chosen parameters. PBKDF2 applies a pseudorandom function (such as a HMAC) to the input password and salt value and repeats the process a number of times to produce a derived key which can then be used as a cryptographic key in subsequent operations. The added computational work of the numerous iterations makes password cracking very difficult. PBKDF2 is also recommended by NIST and has implementations conforming to FIPS-140.</p><p>The RFC document defines the the PBKDF2 function as follows:</p><pre>PBKDF2 (P, S, c, dkLen) -&gt; DK</pre><p>These are the PBKDF2 function parameters:</p><pre>Options:        PRF        underlying pseudorandom function (hLen<br>                           denotes the length in octets of the<br>                           pseudorandom function output)<br><br>Input:          P          password, an octet string<br>                S          salt, an octet string<br>                c          iteration count, a positive integer<br>                dkLen      intended length in octets of the derived<br>                           key, a positive integer, at most<br>                           (2^32 - 1) * hLen<br>Output:         DK         derived key, a dkLen-octet string</pre><h3>PBKDF2 Usage Guidelines</h3><ul><li>Weak passwords can be vulnerable to brute force attacks so users should be required to set strong passwords that are long and contain sufficient entropy.</li><li>Using a low entropy salt can make the hash (derived key) vulnerable to pre-computation attacks using rainbow tables. The salt parameter improves the security of PBKDF2 by changing the output of the hash for any given input password. The salt should be unpredictable and be selected to be unique per user and per database (this part is sometimes called a pepper).</li><li>Using a low number of iterations can also make the hash vulnerable to brute force attacks. The larger the number of iterations selected, the longer it takes to run the PBKDF2 function and therefore requires more work to successfully crack passwords. The number of iterations which you should select is a moving target and increases over time as cpu power increases. OWASP provides a good resource on the recommend parameters <a href="https://cheatsheetseries.owasp.org/cheatsheets/Password_Storage_Cheat_Sheet.html#pbkdf2">here</a>. Currently for PBKDF2-HMAC-SHA256 the recommend iteration count is 600000 and for PBKDF2-HMAC-SHA512 it is 210000.</li><li>The output key length needs to be long enough to prevent brute force attacks and so a minimum key length of at least 128 bits is recommend. Generally the output length should be set to be equal to the length of the chosen hash function.</li><li>When PBKDF2 is used with a HMAC, manual pre-hashing of the password may be required in some cases to prevent certain denial of service vulnerabilities. This can occur when the input password is longer than the block size of the hash function. See here for more <a href="https://cheatsheetseries.owasp.org/cheatsheets/Password_Storage_Cheat_Sheet.html#pbkdf2-pre-hashing">details</a>.</li></ul><h3>Summary of Types</h3><p>The ring::pbkdf2 module contains the following types and functions:</p><p><strong>struct Algorithm </strong>— The type of PBKDF2 algorithm. PBKDF2_HMAC_SHA1, PBKDF2_HMAC_SHA256, PBKDF2_HMAC_SHA384 and PBKDF2_HMAC_SHA512 algorithms are supported.</p><p><strong>fn derive </strong>— The PBKDF2 algorithm used to derive a password hash from a given password. We pass in the chosen algorithm, the number of iterations to use, a salt and the secret (password). The hash value is stored in the given byte array, out. The size of the out array determines the size of the hash value returned.</p><pre>pub fn derive(<br>    algorithm: Algorithm, <br>    iterations: NonZeroU32, <br>    salt: &amp;[u8], <br>    secret: &amp;[u8], <br>    out: &amp;mut [u8]<br>)</pre><p><strong>fn verify </strong>— Checks if a given secret (password) matches a previously derived hash. We pass in the algorithm, the number of iterations, the salt, the secret to check and the hash which was previously derived using the pbkdf2::derive function.</p><pre>pub fn verify(<br>    algorithm: Algorithm, <br>    iterations: NonZeroU32, <br>    salt: &amp;[u8], <br>    secret: &amp;[u8], <br>    previously_derived: &amp;[u8]<br>) -&gt; Result&lt;(), Unspecified&gt;</pre><h3>Rust Imports</h3><p>Let’s start by importing the required types into our project.</p><pre>use std::num::NonZeroU32;<br>use ring::digest::SHA256_OUTPUT_LEN;<br>use ring::digest::SHA512_OUTPUT_LEN;<br>use ring::pbkdf2;<br>use ring::pbkdf2::Algorithm;<br>use ring::pbkdf2::PBKDF2_HMAC_SHA1;<br>use ring::pbkdf2::PBKDF2_HMAC_SHA256;<br>use ring::pbkdf2::PBKDF2_HMAC_SHA384;<br>use ring::pbkdf2::PBKDF2_HMAC_SHA512;</pre><h3>Prepare Iterations, Salt &amp; Secret</h3><p>In the code below we declare the parameters to be passed into the pbkdf2::derive function. In this example we are using the PBKDF2_HMAC_SHA256 algorithm and so iterations is set to 600000 as recommend by OWASP. The iterations variable is a NonZeroU32 type from the Rust standard library which prevents setting an iteration count of zero.</p><pre>const PBKDF2_HMAC_SHA256_ITERATIONS: u32 = 600_000; // number recommended by OWASP for PBKDF2 with SHA256<br><br>let iterations = NonZeroU32::new(PBKDF2_HMAC_SHA256_ITERATIONS).unwrap();<br>let salt = b&quot;random salt&quot;; // this should be randomly generated, using some user specific component and database specific component<br>let secret = b&quot;strong password&quot;; // select a strong password<br>println!(&quot;Secret/password value: {}&quot;, hex::encode(secret)); // don&#39;t print this in production</pre><h3>Derive the Password Hash &amp; Store</h3><p>Next we call the pbkdf2::derive function with our chosen parameters and store the hash in a byte array. In this example the size of the output hash will be the same length as the output of SHA256 but we could make this longer if required. The length is set by choosing the size of the password_hash array.</p><pre>let mut password_hash = [0u8; SHA256_OUTPUT_LEN]; // initialise with zeros<br>pbkdf2::derive(PBKDF2_HMAC_SHA256, iterations, salt, secret, &amp;mut password_hash);<br>println!(&quot;Password hash: {}&quot;, hex::encode(password_hash)); // don&#39;t print this in production</pre><h3>Verify a Password Matches the Password Hash</h3><p>Using the same input parameters as above we can call the pbkdf2::verify function to check if a given password matches the previously derived hash. If the password matches the hash then the verify function returns a Result::Ok type containing a (), otherwise it returns a Result::Err containing error::Unspecified (defined in the Ring error module).</p><pre>pbkdf2::verify(PBKDF2_HMAC_SHA256, iterations, salt, secret, &amp;password_hash).unwrap(); // success case<br>pbkdf2::verify(PBKDF2_HMAC_SHA256, iterations, salt, &quot;wrong password&quot;.as_bytes(), &amp;password_hash).unwrap(); // failure case</pre><h3>Full Sample Code</h3><p>Here is the full code sample for reference. The scenario 2 example below uses PBKDF2_HMAC_SHA512 with the recommended iteration count of 210000 and uses an output hash size equal to the size of SHA512.</p><pre>use std::num::NonZeroU32;<br>use ring::digest::SHA256_OUTPUT_LEN;<br>use ring::digest::SHA512_OUTPUT_LEN;<br>use ring::pbkdf2;<br>use ring::pbkdf2::Algorithm;<br>use ring::pbkdf2::PBKDF2_HMAC_SHA1;<br>use ring::pbkdf2::PBKDF2_HMAC_SHA256;<br>use ring::pbkdf2::PBKDF2_HMAC_SHA384;<br>use ring::pbkdf2::PBKDF2_HMAC_SHA512;<br><br>fn main() {<br>    // scenario 1 - PBKDF2_HMAC_SHA256<br>    const PBKDF2_HMAC_SHA256_ITERATIONS: u32 = 600_000; // number recommended by OWASP for PBKDF2 with SHA256<br>    <br>    // Prepare iterations, salt and secret<br>    let iterations = NonZeroU32::new(PBKDF2_HMAC_SHA256_ITERATIONS).unwrap();<br>    let salt = b&quot;random salt&quot;; // this should be randomly generated, using some user specific component and database specific component<br>    let secret = b&quot;strong password&quot;; // select a strong password<br>    println!(&quot;Secret/password value: {}&quot;, hex::encode(secret)); // don&#39;t print this in production<br>    <br>    // Derive the password hash and store<br>    let mut password_hash = [0u8; SHA256_OUTPUT_LEN]; // initialise with zeros<br>    pbkdf2::derive(PBKDF2_HMAC_SHA256, iterations, salt, secret, &amp;mut password_hash);<br>    println!(&quot;Password hash: {}&quot;, hex::encode(password_hash)); // don&#39;t print this in production<br>    <br>    // Verify whether or not a password matches the stored password hash<br>    pbkdf2::verify(PBKDF2_HMAC_SHA256, iterations, salt, secret, &amp;password_hash).unwrap(); // success case<br>    //pbkdf2::verify(PBKDF2_HMAC_SHA256, iterations, salt, &quot;wrong password&quot;.as_bytes(), &amp;password_hash).unwrap(); // failure case<br><br><br>    // scenario 2 - PBKDF2_HMAC_SHA512<br>    const PBKDF2_HMAC_SHA512_ITERATIONS: u32 = 210_000; // number recommended by OWASP for PBKDF2 with SHA512<br>    <br>    // Prepare iterations, salt and secret<br>    let iterations = NonZeroU32::new(PBKDF2_HMAC_SHA512_ITERATIONS).unwrap();<br>    let salt = b&quot;random salt&quot;; // this should be randomly generated, using some user specific component and database specific component<br>    let secret = b&quot;strong password&quot;; // select a strong password<br>    println!(&quot;Secret/password value: {}&quot;, hex::encode(secret)); // don&#39;t print this in production<br>    <br>    // Derive the password hash and store<br>    let mut password_hash = [0u8; SHA512_OUTPUT_LEN]; // initialise with zeros<br>    pbkdf2::derive(PBKDF2_HMAC_SHA512, iterations, salt, secret, &amp;mut password_hash);<br>    println!(&quot;Password hash: {}&quot;, hex::encode(password_hash)); // don&#39;t print this in production<br>    <br>    // Verify whether or not a password matches the stored password hash<br>    pbkdf2::verify(PBKDF2_HMAC_SHA512, iterations, salt, secret, &amp;password_hash).unwrap(); // success case<br>    //pbkdf2::verify(PBKDF2_HMAC_SHA512, iterations, salt, &quot;wrong password&quot;.as_bytes(), &amp;password_hash).unwrap(); // failure case<br>}</pre><h3>Conclusion</h3><p>In this post we introduced the PBKDF2 algorithm, explained how it works and described how to correctly choose the parameters for the PBKDF2 function. We then explained how to use the Ring pbkdf2 module to derive a password hash by using the pbkdf2::derive function and verify a password matches a password hash using the pbkdf2::verify function. The examples show two scenarios using the most commonly used PBKDF2 algorithms; PBKDF2_HMAC_SHA256 and PBKDF2_HMAC_SHA512.</p><p>This article was originally posted on Web3Developer.io:</p><p><a href="https://web3developer.io/password-hashing-with-pbkdf2-in-rust-using-ring/">https://web3developer.io/password-hashing-with-pbkdf2-in-rust-using-ring/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3e033bf08cf4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deriving Cryptographic Keys with HKDF in Rust using Ring]]></title>
            <link>https://medium.com/@web3developer/deriving-cryptographic-keys-with-hkdf-in-rust-using-ring-dfe8346e22b6?source=rss-be7c00f02569------2</link>
            <guid isPermaLink="false">https://medium.com/p/dfe8346e22b6</guid>
            <category><![CDATA[hkdf]]></category>
            <category><![CDATA[cryptography]]></category>
            <category><![CDATA[ring]]></category>
            <category><![CDATA[rust]]></category>
            <dc:creator><![CDATA[Web3 Developer]]></dc:creator>
            <pubDate>Mon, 24 Apr 2023 07:36:31 GMT</pubDate>
            <atom:updated>2023-08-21T02:45:28.781Z</atom:updated>
            <content:encoded><![CDATA[<p>Ring is a popular Rust cryptography library which has support for generating cryptographic keys from a single input key using HKDF, the HMAC-based Extract-and-Expand Key Derivation Function. As you will see in this post, we can use the ring::hkdf module to securely generate pseudorandom bytes using the Salt::extract and Prk::expand methods implemented in the library.</p><h3>Introduction to HKDF</h3><p>The <strong>HMAC-based Extract-and-Expand Key Derivation Function</strong> (HKDF) is defined in <a href="https://datatracker.ietf.org/doc/html/rfc5869">RFC 5869</a> by the IETF. It is a type of key derivation function (KDF) that is based on HMAC (see my post on HMACs in Rust <a href="https://web3developer.io/signing-and-verifying-messages-with-hmac-in-rust-using-ring/">here</a>). KDFs are a cryptography primitive designed to take some input key and derive from it one or more cryptographically strong keys. The generated keys are pseudorandom because they contain no additional entropy than the input key and are generated deterministically from the input.</p><p>HKDF as defined in the RFC has two stages; <strong>HKDF-Extract</strong> and then <strong>HKDF-Expand</strong>. The first stage takes the input key and extracts from it a fixed-length pseudorandom key. The second stage expands the generated pseudorandom key into several additional pseudorandom keys (the output of the KDF).</p><h4>HKDF-Extract</h4><p>Here is the definition of the <strong>HKDF-Extract</strong> function defined in the RFC document:</p><pre>HKDF-Extract(salt, IKM) -&gt; PRK</pre><p><strong>salt </strong>— The salt is an optional random value that can be set to provide domain separation between different calls to HKDF. It is recommend to use a salt to increase the security of HKDF.</p><p><strong>IKM (Input Keying Material) </strong>— This is the input key which is used as the initial source of entropy to the HKDF.</p><p><strong>PRK (Pseudo-Random Key) </strong>— This is the fixed length pseudorandom key returned as output. This key’s length is equal to the length of the hash function used by the chosen HMAC algorithm (see my post on hash functions in Rust <a href="https://web3developer.io/hash-functions-in-rust-using-ring/">here</a>).</p><h4>HKDF-Expand</h4><p>Here is the definition of the <strong>HKDF-Expand</strong> function defined in the RFC document:</p><pre>HKDF-Expand(PRK, info, L) -&gt; OKM</pre><p><strong>PRK (Pseudo-Random Key) </strong>— This is the fixed length pseudorandom key which was returned from the call to HKDF-Extract.</p><p><strong>info — </strong>This is an optional string of context data. This parameter once again can be used to provide a kind of domain separation. Changing the value in the info parameter will change the OKM value produced. This can be useful when using the same input key in multiple contexts.</p><p><strong>L </strong>— The length of the output keying material in bytes. This parameter defines how much key material to return in the HKDF-Expand step.</p><p><strong>OKM (Output Key Material) </strong>— This is the final output key material which is returned as a single output. Note that this final output key can be up to 255 times longer than the length of the hash function used by the HMAC (in bytes). This value can be segmented to create multiple output keys.</p><h3>Common Pitfalls &amp; Vulnerabilities</h3><p>Here are some common pitfalls and vulnerabilities to be aware of when using HKDF:</p><ul><li>HKDF requires a strong input key with enough entropy to generate secure keys. This means the input should be both random (unpredictable) and long. Using input key material with a shorter length can make the system vulnerable to brute force attacks.</li><li>A weak hash function can lead to insecure keys and make the system vulnerable to attacks so older legacy hash functions such as SHA1 should be avoided.</li><li>HKDF should not be used for other purposes such as message authentication or directly deriving keys from passwords, although it can be used in combination with password hashing algorithms.</li></ul><h3>Summary of Types</h3><p>The ring::hkdf module contains the following types and functions:</p><p><strong>trait KeyType </strong>— A type that defines a len method which determines the length of the final output key.</p><p><strong>struct Algorithm</strong> — The type of HKDF algorithm to be used. HKDF_SHA1_FOR_LEGACY_USE_ONLY, HKDF_SHA256, HKDF_SHA384 and HKDF_SHA512 HKDF algorithms are supported. Algorithm implements the KeyType trait so it can be passed in place of KeyType.</p><p><strong>struct Salt</strong> — Created by supplying an algorithm and salt value. Supports extracting the input key and returning a Prk (pseudorandom key).</p><p><strong>struct Prk</strong> — Represents a pseudorandom key. Supports expanding the pseudorandom key into the output key. Implements the expand function which returns Okm (output key material).</p><p><strong>struct Okm</strong> — Represents the output key material and defines a fill method which consumes the Okm and copies the key material into a buffer.</p><p><strong>fn Salt::extract </strong>— This is the implementation of the HKDF-Extract function as defined in the RFC document.</p><pre>pub fn extract(&amp;self, secret: &amp;[u8]) -&gt; Prk</pre><p><strong>fn Prk::expand </strong>— This is the implementation of the HKDF-Expand function as defined in the RFC document.</p><pre>pub fn expand&lt;&#39;a, L: KeyType&gt;(&amp;&#39;a self, info: &amp;&#39;a [&amp;&#39;a [u8]], len: L) -&gt; Result&lt;Okm&lt;&#39;a, L&gt;, error::Unspecified&gt;</pre><h3>Rust Imports</h3><p>Let’s get started by importing the required types.</p><pre>use ring::digest::SHA256_OUTPUT_LEN;<br>use ring::hkdf::HKDF_SHA1_FOR_LEGACY_USE_ONLY;<br>use ring::hkdf::HKDF_SHA256;<br>use ring::hkdf::HKDF_SHA384;<br>use ring::hkdf::HKDF_SHA512;<br>use ring::hkdf::KeyType;<br>use ring::hkdf::Algorithm;<br>use ring::hkdf::Salt;<br>use ring::hkdf::Prk;<br>use ring::hkdf::Okm;</pre><h3>Create an Instance of Salt</h3><p>We first create an instance of the Salt struct passing in the HKDF algorithm and salt value. Creating the Salt instance is relatively expensive so instances having the same salt value should be reused where possible instead of re-constructing. The salt value is optional but it is best practice to use a randomly generated salt to improve the security of the HKDF.</p><pre>let salt = Salt::new(HKDF_SHA256, b&quot;salt bytes&quot;);</pre><h3>Extract the Pseudorandom Key</h3><p>Next we call the Salt::extract method passing in the input key material to generate a Prk instance (the pseudorandom key). This is the HKDF-Extract operation.</p><pre>let input_key_material = b&quot;secret key&quot;; // use a long randomly generated key<br>println!(&quot;Input key material: {}&quot;, hex::encode(input_key_material)); // don&#39;t print this in production<br><br>let pseudo_rand_key: Prk = salt.extract(input_key_material);</pre><h3>Expand the Pseudorandom Key</h3><p>Then we call the Prk::expand method passing in some application specific context data and an instance of KeyType which is used to provide the length of the output key to be returned. In this case we are passing in the HKDF_SHA256 Algorithm instance which implements KeyType and returns SHA256_OUTPUT_LEN in the call to KeyType::len. The call will only fail if KeyType::len is over 255 times larger than the size of the Prk. This means we can generate up to 255 keys equal in length to the pseudorandom key.</p><p>Then we use the Okm::fill method to get the output key bytes. Note that the fill method consumes the Okm instance and therefore it can only be called once. This design helps to prevent reuse of the output key after it has already be used.</p><pre>let context_data = &amp;[&quot;context one&quot;.as_bytes()];<br>let output_key_material: Okm&lt;Algorithm&gt; = pseudo_rand_key.expand(context_data, HKDF_SHA256).unwrap();<br><br>let mut result = [0u8; SHA256_OUTPUT_LEN];<br>output_key_material.fill(&amp;mut result).unwrap();<br>println!(&quot;Derived output key material: {}&quot;, hex::encode(result)); // don&#39;t print this in production</pre><p>After running the code we get the following output:</p><pre>Input key material: 736563726574206b6579<br>Derived output key material: 811105f7ecc53c62b340bc116a94a57c740b33c4d306844d8a88a1431e8c7b6e</pre><h3>Supplying Context Data with Info</h3><p>Note that it is possible to issue multiple calls to Prk::expand using the same instance of Prk but because the function is deterministic, using the same context data in separate calls will produce the same output key material. For this reason we can reuse the Prk and supply different context data in the info parameter in separate calls to Prk::expand to generate different keys from the same Prk instance but make sure that you are aware of the security implications of doing so.</p><pre>let context_data = &amp;[&quot;context one&quot;.as_bytes()];<br>let output_key_material: Okm&lt;Algorithm&gt; = pseudo_rand_key.expand(context_data, HKDF_SHA256).unwrap();<br><br>let mut result = [0u8; SHA256_OUTPUT_LEN];<br>output_key_material.fill(&amp;mut result).unwrap();<br>println!(&quot;Derived output key material: {}&quot;, hex::encode(result));<br><br>// second call with different context data produces a different output<br>let context_data = &amp;[&quot;context two&quot;.as_bytes()];<br>let output_key_material: Okm&lt;Algorithm&gt; = pseudo_rand_key.expand(context_data, HKDF_SHA256).unwrap();<br><br>let mut result = [0u8; SHA256_OUTPUT_LEN];<br>output_key_material.fill(&amp;mut result).unwrap();<br>println!(&quot;Derived output key material: {}&quot;, hex::encode(result));</pre><p>After running the code we get the following output:</p><pre>Input key material: 736563726574206b6579<br>Derived output key material: 811105f7ecc53c62b340bc116a94a57c740b33c4d306844d8a88a1431e8c7b6e<br>Derived output key material: a0ed15560bbed56af00c380e985ef8f9162866332a6e107f823623861d1fc37f</pre><h3>Generating Multiple Output Keys</h3><p>In the above example the generated output key was equal in length to the size of the generated pseudorandom key (32 bytes in the case of SHA256) but we can also generate longer output keys in the expand step, up to 255 times the length of the pseudorandom key. This is useful if we need to generate more than one key. In this example we generate three output keys:</p><pre>const NUM_OF_KEYS: usize = 3;<br>const OUTPUT_KEY_SIZE: usize = NUM_OF_KEYS * SHA256_OUTPUT_LEN;<br><br>struct MyKeyType(usize);<br>impl KeyType for MyKeyType {<br>    fn len(&amp;self) -&gt; usize {<br>        self.0<br>    }<br>}<br><br>// Salt &amp; HDKF-Extract steps omitted for brevity<br><br>// The HKDF-Expand operation<br>let context_data = &amp;[&quot;context one&quot;.as_bytes()];<br>let output_key_material: Okm&lt;MyKeyType&gt; = pseudo_rand_key.expand(context_data, MyKeyType(OUTPUT_KEY_SIZE)).unwrap();<br><br>let mut result = [0u8; OUTPUT_KEY_SIZE];<br>output_key_material.fill(&amp;mut result).unwrap();<br>println!(&quot;Derived output key 1: {}&quot;, hex::encode(&amp;result[0..32]));<br>println!(&quot;Derived output key 2: {}&quot;, hex::encode(&amp;result[32..64]));<br>println!(&quot;Derived output key 3: {}&quot;, hex::encode(&amp;result[64..96]));</pre><p>After running the code we get the following output:</p><pre>Input key material: 736563726574206b6579<br>Derived output key 1: 811105f7ecc53c62b340bc116a94a57c740b33c4d306844d8a88a1431e8c7b6e<br>Derived output key 2: f4ad09555fb7c36a21ee7632f35c89ecb82c99c7dac499ce3b495789528749a3<br>Derived output key 3: e0897b8085fd74edfc868f850cabf8a4a1df7dbb038dbb0a385189bcefe0f234</pre><h3>Full Sample Code</h3><p>Here is the full code sample for reference.</p><pre>use ring::digest::SHA256_OUTPUT_LEN;<br>use ring::hkdf::HKDF_SHA1_FOR_LEGACY_USE_ONLY;<br>use ring::hkdf::HKDF_SHA256;<br>use ring::hkdf::HKDF_SHA384;<br>use ring::hkdf::HKDF_SHA512;<br>use ring::hkdf::KeyType;<br>use ring::hkdf::Algorithm;<br>use ring::hkdf::Salt;<br>use ring::hkdf::Prk;<br>use ring::hkdf::Okm;<br><br>fn main() {<br>    // scenario 1 - generate single output key<br><br>    let input_key_material = b&quot;secret key&quot;;<br>    println!(&quot;Input key material: {}&quot;, hex::encode(input_key_material));<br>    <br>    // Constructs a new Salt with the given value based on the given digest algorithm<br>    let salt = Salt::new(HKDF_SHA256, b&quot;salt bytes&quot;);<br>    <br>    // The HKDF-Extract operation<br>    let pseudo_rand_key: Prk = salt.extract(input_key_material);<br>    <br>    // The HKDF-Expand operation<br>    let context_data = &amp;[&quot;context one&quot;.as_bytes()];<br>    let output_key_material: Okm&lt;Algorithm&gt; = pseudo_rand_key.expand(context_data, HKDF_SHA256).unwrap();<br>    <br>    let mut result = [0u8; SHA256_OUTPUT_LEN];<br>    output_key_material.fill(&amp;mut result).unwrap();<br>    println!(&quot;Derived output key material: {}&quot;, hex::encode(result));<br>    <br>    // second call with different context data produces a different output<br>    let context_data = &amp;[&quot;context two&quot;.as_bytes()];<br>    let output_key_material: Okm&lt;Algorithm&gt; = pseudo_rand_key.expand(context_data, HKDF_SHA256).unwrap();<br>    <br>    let mut result = [0u8; SHA256_OUTPUT_LEN];<br>    output_key_material.fill(&amp;mut result).unwrap();<br>    println!(&quot;Derived output key material: {}&quot;, hex::encode(result));<br><br><br>    // scenario 2 - generate multiple output keys<br>    <br>    let input_key_material = b&quot;secret key&quot;;<br>    println!(&quot;Input key material: {}&quot;, hex::encode(input_key_material));<br>    <br>    // Constructs a new Salt with the given value based on the given digest algorithm<br>    let salt = Salt::new(HKDF_SHA256, b&quot;salt bytes&quot;);<br>    <br>    // The HKDF-Extract operation<br>    let pseudo_rand_key: Prk = salt.extract(input_key_material);<br>    <br>    const NUM_OF_KEYS: usize = 3;<br>    const OUTPUT_KEY_SIZE: usize = NUM_OF_KEYS * SHA256_OUTPUT_LEN;<br>    <br>    struct MyKeyType(usize);<br>    <br>    impl KeyType for MyKeyType {<br>        fn len(&amp;self) -&gt; usize {<br>            self.0<br>        }<br>    }<br><br>    // The HKDF-Expand operation<br>    let context_data = &amp;[&quot;context one&quot;.as_bytes()];<br>    let output_key_material: Okm&lt;MyKeyType&gt; = pseudo_rand_key.expand(context_data, MyKeyType(OUTPUT_KEY_SIZE)).unwrap();<br>    <br>    let mut result = [0u8; OUTPUT_KEY_SIZE];<br>    output_key_material.fill(&amp;mut result).unwrap();<br>    println!(&quot;Derived output key 1: {}&quot;, hex::encode(&amp;result[0..32]));<br>    println!(&quot;Derived output key 2: {}&quot;, hex::encode(&amp;result[32..64]));<br>    println!(&quot;Derived output key 3: {}&quot;, hex::encode(&amp;result[64..96]));<br>}</pre><h3>Conclusion</h3><p>In this post we introduced the HKDF cryptographic primitive and algorithm, explained how it works and the cryptographic properties it can provide. Then we explained how to use the Ring hkdf module to extract strong cryptographic keys from a single input key using both the Salt::extract and Prk::expand functions. We demonstrated a few scenarios; one using different context data provided in the info parameter to provide domain separation between calls to Prk::expand in different contexts, and another showing how to generate multiple output keys.</p><p>This article was originally posted on Web3Developer.io:</p><p><a href="https://web3developer.io/deriving-cryptographic-keys-with-hkdf-in-rust-using-ring/">https://web3developer.io/deriving-cryptographic-keys-with-hkdf-in-rust-using-ring/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dfe8346e22b6" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>