<?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 CodeCraftSphere on Medium]]></title>
        <description><![CDATA[Stories by CodeCraftSphere on Medium]]></description>
        <link>https://medium.com/@codecraftsphere?source=rss-d21343f5d787------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*wSeO87-xeErwkkTO1fNmLQ.png</url>
            <title>Stories by CodeCraftSphere on Medium</title>
            <link>https://medium.com/@codecraftsphere?source=rss-d21343f5d787------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 22:03:25 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@codecraftsphere/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[How to only encrypt image content with Rust and AES on the example of BMP file type]]></title>
            <link>https://medium.com/@codecraftsphere/how-to-only-encrypt-image-content-with-rust-and-aes-on-the-example-of-bmp-file-type-231f6200d9ba?source=rss-d21343f5d787------2</link>
            <guid isPermaLink="false">https://medium.com/p/231f6200d9ba</guid>
            <category><![CDATA[rust]]></category>
            <category><![CDATA[security]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[CodeCraftSphere]]></dc:creator>
            <pubDate>Sat, 16 Sep 2023 08:50:36 GMT</pubDate>
            <atom:updated>2024-03-04T16:33:02.620Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*jeZ8aYQUAlh7y6eA" /><figcaption>Photo by <a href="https://unsplash.com/@towfiqu999999?utm_source=medium&amp;utm_medium=referral">Towfiqu barbhuiya</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Image content encryption with Rust and AES.</p><blockquote>If you are behind a paywall, consider reading this post on <a href="https://sgerdes.substack.com/p/how-to-only-encrypt-image-content-with-rust-and-aes-on-the-example-of-bmp-file-type-231f6200d9ba">Substack</a>.<br>Connect with me on <a href="http://www.linkedin.com/in/steffen-g-b24311140">LinkedIn</a>.</blockquote><p>As a programmer interested in the realms of security and cryptography, I got the idea to create a tool that does not encrypt the image file but rather only its content. In this guide, I will lead you through the process of creating a Rust-based application that you can use to encrypt the binary content of BMP images while preserving their original file format and visual appearance. Before we delve into the code, let’s lay the foundation with a brief primer on binary file formats, particularly focusing on the BMP format.</p><h4>Understanding Binary File Formats</h4><p>Binary file formats are used for digital data storage, enabling computers to represent various data types ranging from text documents to multimedia files. Unlike human-readable text files, binary formats are designed to be machine-readable, often comprising a sequence of bytes that hold specific meanings when interpreted by a program. This binary structure facilitates efficient storage and retrieval of data.</p><h4>BMP (Bitmap) Images: A Canvas of Pixels</h4><p>Among the various binary file formats, BMP, short for Bitmap, stands out for its simplicity. BMP images are akin to digital canvases, where each pixel is represented as a combination of colors, forming an intricate mosaic of visual information. This straightforward format organizes pixels in a grid, making it an ideal starting point for our exploration into image encryption.</p><p>Now, let’s dive into it and see how we leverage the binary structure of BMP images to encrypt their content while preserving their inherent characteristics.</p><h4>Project Setup</h4><p>Our journey begins with the creation of a new Rust project. Let’s lay the foundation by executing the following terminal commands:</p><pre>cargo new image-sec <br>cd image-sec</pre><h4>Dependencies</h4><p>To use AES encryption, I incorporated the aes-gcm crate as a dependency in our project’s Cargo.toml file:</p><pre>[package]<br>name = &quot;image-sec&quot;<br>version = &quot;0.1.0&quot;<br>authors = [&quot;espectro93&quot;]<br>edition = &quot;2018&quot;<br><br># See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html<br><br>[dependencies]<br>clap = { version = &quot;3.0.0-beta.2&quot;, features = [&quot;yaml&quot;] }<br>aes-gcm = &quot;0.9.2&quot;</pre><h4>Main.rs</h4><pre>use std::error::Error;<br>use std::path::Path;<br>use clap::{App, load_yaml};<br><br>use image_sec::{encrypt_image, decrypt_image};<br><br>fn main() -&gt; Result&lt;(), Box&lt;dyn Error&gt;&gt; {<br>    let yaml = load_yaml!(&quot;cli.yml&quot;);<br>    let matches = App::from(yaml).get_matches();<br><br>    let encrypt = matches.value_of(&quot;encrypt&quot;);<br>    match encrypt {<br>        Some(dir) =&gt; match encrypt_image(Path::new(dir)) {<br>            Ok(_) =&gt; println!(&quot;Image was successfully encrypted!&quot;),<br>            Err(_) =&gt; eprintln!(&quot;Error encrypting image&quot;)<br>        },<br>        None =&gt; ()<br>    }<br><br>    let decrypt = matches.value_of(&quot;decrypt&quot;);<br>    match decrypt {<br>        Some(dir) =&gt; match decrypt_image(Path::new(dir)) {<br>            Ok(_) =&gt; println!(&quot;Image was successfully encrypted!&quot;),<br>            Err(_) =&gt; eprintln!(&quot;Error decrypting image&quot;)<br>        },<br>        None =&gt; ()<br>    }<br>    Ok(())<br>}</pre><p>Here we parse the cli input and delegate accordingly to encrypt or decrypt the image.</p><h4>Command Line Interface (CLI)</h4><p>To simplify the usage of the tool I am using the clap crate. This CLI empowers users to effortlessly encrypt and decrypt BMP images. Here’s a snippet of the code that brings this functionality to life:</p><pre>name: image-sec<br>version: &quot;0.0.1&quot;<br>author: espectro93<br>about: Encrypts and decrypts images<br>settings: ArgRequiredElseHelp<br>args:<br>  - encrypt:<br>      short: e<br>      long: encrypt<br>      value_name: ENCRYPT<br>      about: Specifies the image that we want to encrypt<br>      takes_value: true<br>  - decrypt:<br>      short: d<br>      long: decrypt<br>      value_name: DECRYPT<br>      about: Specifies the image that we want to decrypt<br>      takes_value: true</pre><h4>Encryption Code</h4><p>The core functionality revolves around its encryption and decryption functions. So the whole encryption and decryption process is focussed on the BMP image binary structure, these functions encapsulate the main part of our tool. While we embrace the AES-GCM encryption method in this showcase, it’s important to note that the key and nonce management employed here remain intentionally basic. This serves as a starting point for exploration and can be further refined for real-world applications. Let’s take a glimpse at the code:</p><pre>use aes_gcm::{Aes256Gcm, Key, Nonce};<br>use aes_gcm::aead::{Aead, NewAead};<br><br>pub fn encrypt(to_encrypt: &amp;[u8]) -&gt; Vec&lt;u8&gt; {<br>    let key = Key::from_slice(b&quot;an example very very secret key.&quot;);<br>    let cipher = Aes256Gcm::new(key);<br>    let nonce = Nonce::from_slice(b&quot;unique nonce&quot;);<br><br>    return cipher.encrypt(nonce, to_encrypt.as_ref()).expect(&quot;Err&quot;);<br>}<br><br>pub fn decrypt(to_decrypt: &amp;[u8]) -&gt; Vec&lt;u8&gt;{<br>    let key = Key::from_slice(b&quot;an example very very secret key.&quot;);<br>    let cipher = Aes256Gcm::new(key);<br>    let nonce = Nonce::from_slice(b&quot;unique nonce&quot;);<br><br>    return cipher.decrypt(nonce, to_decrypt.as_ref()).expect(&quot;decryption failure&quot;);<br>}</pre><p>Now we are going to look at the lib.rs file and it’s functionality. We define some structs, enums and a trait.</p><pre>mod crypt;<br><br>use std::path::{Path, PathBuf};<br>use std::fs::{OpenOptions, File};<br>use std::error::Error;<br>use std::ffi::OsStr;<br>use std::io::{Read, Write};<br>use crate::crypt::{encrypt, decrypt};<br>use std::env;<br><br>pub fn encrypt_image(path: &amp;Path) -&gt; Result&lt;(), Box&lt;dyn Error&gt;&gt; {<br>    let img_input = extract_image_input(path)?;<br>    check_extension(img_input.extension.as_str())?;<br>    write_to_disk(Image::from_image_input(img_input, ActionType::Encrypt));<br>    Ok(())<br>}<br><br>pub fn decrypt_image(path: &amp;Path) -&gt; Result&lt;(), Box&lt;dyn Error&gt;&gt; {<br>    let img_input = extract_image_input(path)?;<br>    check_extension(img_input.extension.as_str())?;<br>    write_to_disk(Image::from_image_input(img_input, ActionType::Decrypt));<br>    Ok(())<br>}<br><br>struct ImageInput {<br>    file: File,<br>    name: String,<br>    extension: String,<br>}<br><br>pub enum ActionType {<br>    Encrypt,<br>    Decrypt,<br>}<br><br>struct Image {<br>    name: String,<br>    data: Vec&lt;u8&gt;,<br>    encrypted: bool,<br>}<br><br>trait FromImageInput {<br>    fn from_image_input(img_input: ImageInput, action_type: ActionType) -&gt; Image;<br>}</pre><p>Afterwards, we are gonna check the piece of code where the magic happens.</p><pre>pub fn encrypt_image(path: &amp;Path) -&gt; Result&lt;(), Box&lt;dyn Error&gt;&gt; {<br>    let img_input = extract_image_input(path)?;<br>    check_extension(img_input.extension.as_str())?;<br>    write_to_disk(Image::from_image_input(img_input, ActionType::Encrypt));<br>    Ok(())<br>}<br><br>pub fn decrypt_image(path: &amp;Path) -&gt; Result&lt;(), Box&lt;dyn Error&gt;&gt; {<br>    let img_input = extract_image_input(path)?;<br>    check_extension(img_input.extension.as_str())?;<br>    write_to_disk(Image::from_image_input(img_input, ActionType::Decrypt));<br>    Ok(())<br>}<br><br>impl FromImageInput for Image {<br>    fn from_image_input(mut img_input: ImageInput, action_type: ActionType) -&gt; Image {<br>        match action_type {<br>            ActionType::Encrypt =&gt; {<br>                let mut buffer = Vec::new();<br>                match img_input.file.read_to_end(&amp;mut buffer) {<br>                    Ok(_) =&gt; {<br>                        let bmp_header = &amp;buffer[..54];<br>                        let pixel_data = &amp;buffer[54..];<br>                        let mut encrypted_buffer = encrypt(pixel_data.as_slice());<br>                        let mut result_buffer = Vec::new();<br>                        result_buffer.extend_from_slice(&amp;bmp_header);<br>                        result_buffer.append(&amp;mut pixel_data);<br>                        Image {<br>                            name: img_input.name,<br>                            data: result_buffer,<br>                            encrypted: true,<br>                        }<br>                    }<br>                    Err(_) =&gt; panic!(&quot;Error reading image&quot;)<br>                }<br>            }<br>            ActionType::Decrypt =&gt; {<br>                let mut buffer = Vec::new();<br>                match img_input.file.read_to_end(&amp;mut buffer) {<br>                    Ok(_) =&gt; {<br>                        let to_decrypt = &amp;buffer[54..];<br>                        Image {<br>                            name: img_input.name,<br>                            data: decrypt(to_decrypt),<br>                            encrypted: false,<br>                        }<br>                    }<br>                    Err(_) =&gt; panic!(&quot;Error reading image&quot;)<br>                }<br>            }<br>        }<br>    }<br>}</pre><p>Here it is important to mention that <strong><em>let bmp_header = &amp;buffer[..54]; </em></strong>extract the binary byte headers so that we only encrypt the content of the image. Furthermore, we have some helper functions to check the file type and write to disk.</p><pre>fn write_to_disk(image: Image) {<br>    let mut new_file_path: String = env::current_dir().expect(&quot;&quot;).to_str().expect(&quot;&quot;).to_string();<br>    new_file_path.push_str(&quot;/&quot;);<br>    new_file_path.push_str(image.name.as_str());<br>    match image.encrypted {<br>        true =&gt; new_file_path.push_str(&quot;_encrypted.bmp&quot;),<br>        _ =&gt; new_file_path.push_str(&quot;.bmp&quot;)<br>    }<br>    let mut f = File::create(PathBuf::from(new_file_path)).expect(&quot;Unable to create file&quot;);<br>    f.write_all(&amp;*image.data).expect(&quot;Unable to write data&quot;);<br>}<br><br>fn check_extension(extension: &amp;str) -&gt; Result&lt;(), Box&lt;dyn Error&gt;&gt; {<br>    match extension {<br>        &quot;BMP&quot; =&gt; Ok(()),<br>        &quot;bmp&quot; =&gt; Ok(()),<br>        _ =&gt; { panic!(&quot;Currently only bitmap images are supported&quot;); }<br>    }<br>}<br><br>fn extract_image_input(path: &amp;Path) -&gt; Result&lt;ImageInput, Box&lt;dyn Error&gt;&gt; {<br>    let file_extension = path<br>        .extension()<br>        .and_then(OsStr::to_str)<br>        .expect(&quot;Error parsing file extension&quot;);<br><br>    let file = OpenOptions::new()<br>        .read(true)<br>        .write(true)<br>        .open(path)?;<br><br>    let name = path.file_name()<br>        .expect(&quot;Cannot determine file name&quot;)<br>        .to_str()<br>        .expect(&quot;Cannot convert file name to str&quot;);<br><br>    Ok(ImageInput {<br>        file,<br>        name: name.to_string(),<br>        extension: file_extension.to_string(),<br>    })<br>}</pre><p><strong>Building the project</strong></p><p>Execute the following command to create a binary executable:</p><p><em>cargo build — release</em></p><p>Now you can encrypt and decrypt images</p><p><em>./target/release/image-sec -encrypt &lt;file_path&gt;.bmp</em></p><p><em>./target/release/image-sec -decrypt &lt;file_path_encrypted&gt;.bmp</em></p><h4>Result</h4><p>Let us check the result based on an example image:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*ZijOTX4o8jV0p0yY" /><figcaption><a href="https://unsplash.com/de/fotos/F5HtPjpBb9k">Alex Vasey Unsplash</a></figcaption></figure><p>that picture turns into the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/609/1*0r77Y5uaYIGPtYqOm7NJ5w.png" /></figure><blockquote>Connect with me on <a href="https://www.linkedin.com/in/steffen-gerdes-b24311140/">LinkedIn</a></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=231f6200d9ba" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to empower your Java Maven Project with Git Hooks for automated Code Formatting and Semantic…]]></title>
            <link>https://medium.com/@codecraftsphere/how-to-empower-your-java-maven-project-with-git-hooks-for-automated-code-formatting-and-semantic-c2dfdf7680ef?source=rss-d21343f5d787------2</link>
            <guid isPermaLink="false">https://medium.com/p/c2dfdf7680ef</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[git]]></category>
            <dc:creator><![CDATA[CodeCraftSphere]]></dc:creator>
            <pubDate>Mon, 29 Aug 2022 16:39:54 GMT</pubDate>
            <atom:updated>2024-03-05T08:45:28.648Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gcX_IgI1drKm5KIcxw40xA.jpeg" /></figure><h3>How to empower your Java Maven Project with Git Hooks for automated Code Formatting and Semantic Versioning</h3><p>Keep your codebase clean with automated formatting, semantic versioning, and Git hooks.</p><blockquote>If you are behind a paywall, consider reading this post on <a href="https://codecraftsphere.substack.com/p/how-to-empower-your-java-maven-project-with-git-hooks-for-automated-code-formatting-and-semantic-c2dfdf7680ef">Substack</a>.<br>Connect with me on <a href="http://www.linkedin.com/in/steffen-g-b24311140">LinkedIn</a>.</blockquote><p>Have you ever stumbled upon a messy codebase that was missing some basic clean code principles? (Short clean code insights here) I already had the pleasure of seeing a codebase whose style was mixed up with different IntelliJ formatting styles. Furthermore, commit messages were messed up as well which made understanding changes from the past more difficult. I am always trying to keep a linear git history even though this is not always possible. In my opinion, <a href="https://www.conventionalcommits.org/en/v1.0.0/">conventional commits</a> are a good fit to keep a git commit history that is understandable, and on top, you can automate changelog creation and semantic versioning for example by specifying breaking changes through your commit message.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VnO9wuy5g_JvGvbZ7K4VaQ.png" /><figcaption>changelog based on conventional commits</figcaption></figure><p>To overcome this I was searching for a simple solution that checks code formatting and the commit message. (Serverside hooks were not an option for those projects but Github Actions is a good fit if suitable) That is why I ended up with git hooks.</p><blockquote><a href="https://www.atlassian.com/git/tutorials/git-hooks">Git hooks are scripts that run automatically every time a particular event occurs in a Git repository. They let you customize Git’s internal behavior and trigger customizable actions at key points in the development life cycle.</a></blockquote><p>Essentially we are hooking into the commit lifecycle, where we have several useful hooks. For our use case, the <strong><em>pre-commit</em></strong> and <strong><em>commit-msg</em></strong> hooks are of particular interest.</p><p>So if you want to follow along, make sure you have:</p><ul><li>Java 17</li><li>Maven</li><li>Node</li></ul><p>In your pom.xml file in the root directory, you have to set up the plugins. This one is responsible for copying your hooks into the default git hooks folder and has the maven install as a goal (This is where maven builds a dependency tree based on our <strong><em>pom.xml</em></strong> and fetches all needed components, otherwise we could not build our project). We specified a custom hook for the <strong><em>commit-msg</em></strong> and the <strong><em>pre-commit</em></strong>. You could also change the whole default hooks directory in that configuration. I will show you later where the hooks folder resides and what the code looks like.</p><pre>&lt;plugin&gt;<br>    &lt;groupId&gt;com.rudikershaw.gitbuildhook&lt;/groupId&gt;<br>    &lt;artifactId&gt;git-build-hook-maven-plugin&lt;/artifactId&gt;<br>    &lt;version&gt;3.1.0&lt;/version&gt;<br>    &lt;configuration&gt;<br>        &lt;installHooks&gt;<br>            &lt;commit-msg&gt;hooks/commit-msg&lt;/commit-msg&gt;<br>            &lt;pre-commit&gt;hooks/pre-commit&lt;/pre-commit&gt;<br>        &lt;/installHooks&gt;<br>    &lt;/configuration&gt;<br>    &lt;executions&gt;<br>        &lt;execution&gt;<br>            &lt;goals&gt;<br>                &lt;goal&gt;install&lt;/goal&gt;<br>            &lt;/goals&gt;<br>        &lt;/execution&gt;<br>    &lt;/executions&gt;<br>&lt;/plugin&gt;</pre><p>For more options see: <a href="https://github.com/rudikershaw/git-build-hook">https://github.com/rudikershaw/git-build-hook</a></p><p>This plugin is responsible for the formatting of your code. I have used prettier but you could also use <em>google-java-format</em>, <em>eclipse jdt</em> or <em>palantir-java-format</em>. You have several options for your formatting, see <a href="https://github.com/diffplug/spotless/tree/main/plugin-maven">spotless maven</a>. You could also let your builds fail if the formatting is not correct.</p><pre>&lt;plugin&gt;<br>    &lt;groupId&gt;com.diffplug.spotless&lt;/groupId&gt;<br>    &lt;artifactId&gt;spotless-maven-plugin&lt;/artifactId&gt;<br>    &lt;version&gt;2.25.0&lt;/version&gt;<br>    &lt;configuration&gt;<br>        &lt;formats&gt;<br>            &lt;!-- prettier with java-plugin --&gt;<br>            &lt;format&gt;<br>                &lt;includes&gt;<br>                    &lt;include&gt;src/*/java/**/*.java&lt;/include&gt;<br>                &lt;/includes&gt;<br><br>                &lt;prettier&gt;<br>                    &lt;devDependencies&gt;<br>                        &lt;prettier&gt;2.0.5&lt;/prettier&gt;<br>                        &lt;prettier-plugin-java&gt;0.8.0&lt;/prettier-plugin-java&gt;<br>                    &lt;/devDependencies&gt;<br>                    &lt;config&gt;<br>                        &lt;tabWidth&gt;4&lt;/tabWidth&gt;<br>                        &lt;parser&gt;java&lt;/parser&gt;<br>                    &lt;/config&gt;<br>                &lt;/prettier&gt;<br>            &lt;/format&gt;<br>        &lt;/formats&gt;<br>    &lt;/configuration&gt;<br>    &lt;executions&gt;<br>        &lt;execution&gt;<br>            &lt;phase&gt;verify&lt;/phase&gt;<br>            &lt;goals&gt;<br>                &lt;goal&gt;check&lt;/goal&gt;<br>            &lt;/goals&gt;<br>        &lt;/execution&gt;<br>    &lt;/executions&gt;<br>&lt;/plugin&gt;</pre><p>So the following picture shows our simple directory structure and where we manage our hooks. A plus is that the hooks are also versioned by git if you do it this way (If you want to use it in several projects you could create a maven library for your hooks and integrate them in the <em>git-build-hook-maven-plugin</em>):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/352/1*FwimatHgD1X7AV9tzMYodQ.png" /></figure><p>Also make sure to execute:</p><ul><li><em>chmod +x hooks/pre-commit</em></li><li><em>chmod +x hooks/commit-msg</em></li></ul><p>Because the used maven plugin <strong><em>git-build-hook-maven-plugin</em></strong> copies them into the default git hooks directory and if they have no permission to execute we cannot run our hooks.</p><p>Essentially the <strong><em>commit-msg</em></strong> hook checks if the message starts with one of the allowed words and exits with an error if it does not. The whole script was copied from <a href="https://dwmkerr.com/conventional-commits-and-semantic-versioning-for-java/">here</a>, where the author wrote a nice article on that topic, but without the automatic inclusion as the hook was manually copied into the hooks directory.</p><pre>#!/usr/bin/env bash<br><br># Create a regex for a conventional commit.<br>convetional_commit_regex=&quot;^(build|chore|ci|docs|feat|fix|perf|refactor|revert|style|test)(\([a-z \-]+\))?!?: .+$&quot;<br><br># Get the commit message (the parameter we&#39;re given is just the path to the<br># temporary file which holds the message).<br>commit_message=$(cat &quot;$1&quot;)<br><br># Check the message, if we match, all good baby.<br>if [[ &quot;$commit_message&quot; =~ $convetional_commit_regex ]]; then<br>   echo -e &quot;\e[32mCommit message meets Conventional Commit standards...\e[0m&quot;<br>   exit 0<br>fi<br><br># Uh-oh, this is not a conventional commit, show an example and link to the spec.<br>echo -e &quot;\e[31mThe commit message does not meet the Conventional Commit standard\e[0m&quot;<br>echo &quot;An example of a valid message is: &quot;<br>echo &quot;  feat(login): add the &#39;remember me&#39; button&quot;<br>echo &quot;More details at: https://www.conventionalcommits.org/en/v1.0.0/#summary&quot;<br>exit 1</pre><p>The <strong><em>pre-commit</em></strong> hook looks like this and simply applies the code style:</p><pre><strong>#!/usr/bin/env bash<br></strong>mvn spotless:apply</pre><p>Now we are almost set up, but the part around releasing new versions and automatic version bumps is still missing. The author of the commit-msg script also released an npm package that helps with automatic versioning and new releases. Initially, you have to run</p><pre>npx dwmkerr/standard-version --first-release --packageFiles pom.xml --bumpFiles pom.xml</pre><p>And for each new release after that just omit the first-release option from the command. By running</p><pre>git push --follow-tags</pre><p>You push the newly created tag to your repository along with your changelog and the updated version number.</p><p>You can see my example repository on <a href="https://github.com/espectro93/hooks-versioning">Github</a>.</p><blockquote>Connect with me on <a href="https://www.linkedin.com/in/steffen-gerdes-b24311140/">LinkedIn</a></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c2dfdf7680ef" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to create your own traceroute with GeoIP information]]></title>
            <link>https://medium.com/@codecraftsphere/how-to-create-your-own-traceroute-with-geoip-information-470ed88afccd?source=rss-d21343f5d787------2</link>
            <guid isPermaLink="false">https://medium.com/p/470ed88afccd</guid>
            <category><![CDATA[linux]]></category>
            <category><![CDATA[traceroute]]></category>
            <category><![CDATA[computer-networking]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[rust]]></category>
            <dc:creator><![CDATA[CodeCraftSphere]]></dc:creator>
            <pubDate>Wed, 03 Nov 2021 20:06:59 GMT</pubDate>
            <atom:updated>2024-03-04T16:33:29.490Z</atom:updated>
            <content:encoded><![CDATA[<p>We see how traceroute works and add geo information to the output.</p><blockquote>If you are behind a paywall, consider reading this post on <a href="https://sgerdes.substack.com/p/how-to-create-your-own-traceroute-with-geoip-information-470ed88afccd">Substack</a>.<br>Connect with me on <a href="http://www.linkedin.com/in/steffen-g-b24311140">LinkedIn</a>.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*eOsrZBXbkWlQePeU" /><figcaption>Photo by <a href="https://unsplash.com/@macroman?utm_source=medium&amp;utm_medium=referral">Immo Wegmann</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Back when I was young and started to fiddle around with the terminal and basic commands like ping I came across traceroute/tracert. I found it quite fascinating to see all those intermediary destinations of my packet on its way to <a href="http://www.google.de./">www.google.com.</a></p><p>This year I started learning the programming language <a href="https://www.rust-lang.org/">Rust</a> and I was thinking about some projects I could do. That was when I was watching a video called <a href="https://www.youtube.com/watch?v=75yKT3OuE44">“How Traceroute Works (Building a Movie Scene ‘Trace’ Map)- Computerphile”</a>. The protagonist builds a python app that is using traceroute and the IP of the corresponding hop to do a GeoIP lookup and prints the location and route on a 2D map. I was very fond of that idea but would rather like to print the address of that location into the terminal beside the IP.</p><p>If you want to follow along you need to install Rust: <a href="https://www.rust-lang.org/tools/install">https://www.rust-lang.org/tools/install</a></p><p><strong><em>P.S.</em></strong> I have created the program on a Linux machine so I am not sure if it works on Mac or Windows.</p><p>Traceroute operates on Layer3 of the OSI-Model (or at least relies on it as some implementations use UDP or TCP), thus is using one of it’s protocols, the Internet Control Message Protocol (ICMP). We start by sending an ICMP echo request packet that possesses a Time-To-Live (TTL) value. When a packet arrives at a hop the TTL is decreased by 1 upon reaching 0. When that happens information including the IP address of that hop is returned to the sender. So we basically increase the TTL till we reach our destination while printing information of all those replies to the terminal. To do that we need the IP of our target but as I would like to use the program by DNS we need to resolve that first.</p><pre>fn main() {<br>    let dns_addr = env::args().nth(1).unwrap_or_else(|| {<br>        eprintln!(&quot;[!] Usage: traceroute &lt;domain&gt;&quot;);<br>        process::exit(1);<br>    });<br><br>    println!(&quot;traceroute to {}&quot;, dns_addr);<br><br>    let ip_destination = dns_resolve_ip(dns_addr.as_str());<br>    trace_route(Config { destination: ip_destination, tries_per_hop: 5, timeout: 1 });<br>}</pre><p>So we parse the DNS Address from the args and behind dns_resolve_ip() we use the Crate <a href="https://docs.rs/dns-lookup/1.0.8/dns_lookup/#">dns_lookup</a> which under the hood uses the host systems ability to do a DNS lookup. After that, we jump into our trace_route() functionality with a Config struct that defines our destination, a timeout for requests and how many tries we wanna start per hop.</p><pre>#[derive(Clone, Debug)]<br>pub struct TraceHop {<br>    hop_addr: IpAddr,<br>    reply_time: Duration,<br>    reply_type: IcmpType,<br>    sequence_number: u16,<br>}</pre><p>Our TraceHop struct holds the address of that hop, the reply time and the reply type. The reply type or IcmpType is important as it allows us to determine if we have successfully received an echo reply. The type EchoReply means we have reached our destination, TimeExceeded means we have been at a hop and the TTL value reached zero. In addition to that, we use the sequence number to filter out packets or requests with no corresponding reply.</p><pre>let mut ttl: usize = 1;<br><br>let (mut tx, mut rx) = transport_channel(<br>    1024,<br>    Layer3(IpNextHeaderProtocols::Icmp))<br>    .expect(&quot;Creating transport channel failed!&quot;);<br><br>let mut rx = icmp_packet_iter(&amp;mut rx);<br><br><br>let mut buf_ip = [0u8; 64];<br>let mut buf_icmp = [0u8; 40];</pre><p>For the networking calls and establishing the connection, we use the Crate <a href="https://crates.io/crates/pnet">pnet</a>. The transport_channel() call allows sending(tx) and receiving(rx) packets. We then send those packets according to our tries_per_hop. To send an ICMP Packet we create an IP Packet and an ICMP packet. We do it like this cause ICMP is part of the IP protocol and contained within an IP packet.</p><pre>icmp_packet.set_icmp_type(IcmpTypes::EchoRequest);    icmp_packet.set_sequence_number(sequence_number);<br>let checksum = checksum(&amp;icmp_packet.packet_mut(), 1);     icmp_packet.set_checksum(checksum);    ipv4_packet.set_payload(icmp_packet.packet_mut());</pre><p>After sending those packets we check the amount, if we have specified 5 tries per hop and received 5 replies we are eligible to compute the average response time. Otherwise, we do not show that information.</p><pre>thread::spawn(move || {<br>println!(&quot;{:&gt;3}.   {:&lt;20} {:&lt;15} {:^15}&quot;,<br>ttl.clone(),<br>ip_clone.to_string(),  get_location_for(ip_clone).unwrap_or(&quot;N.a.&quot;.to_string()),    avg_time.as_millis());<br>});</pre><p>We are starting a separate thread to avoid blocking behavior because of the network call within get_location_for_ip(). The println!() call consists of some padding for a clean output.</p><pre><em>pub fn </em>get_location_for(ip: IpAddr) -&gt; Result&lt;String, Box&lt;<em>dyn </em>Error&gt;&gt; {<br>    <em>let </em>geo_ip_data = reqwest::blocking::get(&quot;http://ip-api.com/json/&quot;.to_owned() + ip.to_string().as_str())?<br>        .json::&lt;serde_json::Value&gt;()?;<br><br>    <em>let mut </em>display = geo_ip_data.get(&quot;city&quot;).unwrap_or(&amp;Value::String(String::from(&quot;No city&quot;))).as_str().unwrap_or(&quot;No city&quot;).to_owned();<br>    <em>let </em>country = geo_ip_data.get(&quot;country&quot;).unwrap_or(&amp;Value::String(String::from(&quot;No country&quot;))).as_str().unwrap_or(&quot;No country&quot;).to_owned();<br><br>    display.push_str(&quot;, &quot;);<br>    display.push_str(country.as_str());<br><br>    Ok(display)<br>}</pre><p>So now we can build the project and run (as we operate on Layer3 we need root privileges):</p><pre>sudo -E cargo run www.google.de</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/522/1*kQPO_KaE5LSt0B1JU6MRmA.png" /></figure><p>No information on the first one is because it is the private IP of my router standard gateway. Now we can see there are quite a few hops till our packet reaches it’s destination. Still, the result of our requests is dependant on the GeoIP Location API. Furthermore, firewalls could block those requests and would cause a timeout.</p><p><a href="https://github.com/espectro93/xtraceroute">GitHub</a></p><blockquote>Connect with me on <a href="https://www.linkedin.com/in/steffen-gerdes-b24311140/">LinkedIn</a></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=470ed88afccd" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>