<?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 Ziad Alzarka on Medium]]></title>
        <description><![CDATA[Stories by Ziad Alzarka on Medium]]></description>
        <link>https://medium.com/@ziadalzarka?source=rss-c07fb8a8f629------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*4MfXfk4BlLSCaA428bEJ2A@2x.jpeg</url>
            <title>Stories by Ziad Alzarka on Medium</title>
            <link>https://medium.com/@ziadalzarka?source=rss-c07fb8a8f629------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 05:05:36 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ziadalzarka/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[TypeOrm is timing out with Jest Fake Timers]]></title>
            <link>https://medium.com/@ziadalzarka/typeorm-is-timing-out-with-jest-fake-timers-c11f8a350a78?source=rss-c07fb8a8f629------2</link>
            <guid isPermaLink="false">https://medium.com/p/c11f8a350a78</guid>
            <dc:creator><![CDATA[Ziad Alzarka]]></dc:creator>
            <pubDate>Thu, 30 Jan 2025 11:13:38 GMT</pubDate>
            <atom:updated>2025-01-30T11:13:38.711Z</atom:updated>
            <content:encoded><![CDATA[<p>I encountered an issue while writing some integration tests that any queries to TypeOrm causes the tests to time out whenever I’m using Jest fake timers.</p><p>To solve this issue, I did this:</p><pre>import.meta.jest.useFakeTimers({<br>  doNotFake: [&quot;nextTick&quot;, &quot;setImmediate&quot;, &quot;clearImmediate&quot;],<br>  timerLimit: 1000,<br>});</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c11f8a350a78" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Linking a Go static library to Rust and handling asynchronous calls]]></title>
            <link>https://medium.com/@ziadalzarka/linking-a-go-static-library-to-rust-and-handling-asynchronous-calls-5672932a966b?source=rss-c07fb8a8f629------2</link>
            <guid isPermaLink="false">https://medium.com/p/5672932a966b</guid>
            <category><![CDATA[async]]></category>
            <category><![CDATA[rust]]></category>
            <category><![CDATA[go]]></category>
            <category><![CDATA[ffi]]></category>
            <dc:creator><![CDATA[Ziad Alzarka]]></dc:creator>
            <pubDate>Fri, 02 Aug 2024 00:13:49 GMT</pubDate>
            <atom:updated>2024-08-02T14:19:50.410Z</atom:updated>
            <content:encoded><![CDATA[<p>I was working on a side project with <a href="https://tauri.app/">Tauri</a> (which will be an important detail later) and I wanted to use a Go library that provides access to some third-party API, but Tauri is built in Rust. I found this an opportunity to experiment with FFI in Go and Rust.</p><h3>Getting started with linking</h3><h4>Writing the Go code</h4><p>So I created a new Go project and started to implement some methods:</p><pre>func (wb *ThirdPartyBot) IsSignedIn() (ConnectionStatus, string) {<br> if wb.client == nil {<br>  return SignedOut, &quot;&quot;<br> }<br><br> if !wb.client.IsConnected() {<br>  return NotConnected, &quot;&quot;<br> }<br><br> if wb.client.Store.ID == nil {<br>  return SignedOut, &quot;&quot;<br> }<br><br> return SignedIn, &quot;&quot;<br>}</pre><p>Then we need to export this method in the final binary and we can do that by adding the //export flag. We will also have to use C types instead of Go types and that’s fairly easy since Go can compile its binaries using C code.</p><pre>// #include &lt;stdlib.h&gt;<br>// typedef struct {<br>//     char* connection_status;<br>//     char* error_message;<br>// } InfoResponse;<br>import &quot;C&quot;<br><br>//export get_info<br>func get_info() *C.InfoResponse {<br> connectionStatus, errorMessage := bot.IsSignedIn()<br><br> cConnectionStatus := C.CString(string(connectionStatus))<br> cErrorMessage := C.CString(string(errorMessage))<br><br> response := C.InfoResponse{<br>  connection_status: cConnectionStatus,<br>  error_message:     cErrorMessage,<br> }<br><br> // Allocate memory for the struct in C and copy the struct into it<br> pResponse := (*C.InfoResponse)(C.malloc(C.size_t(unsafe.Sizeof(response))))<br> *pResponse = response<br><br> return pResponse<br>}</pre><p>Let’s dissect this bit by bit:</p><ol><li>First, we define our return struct in a comment, this can essentially be treated as a header file</li></ol><pre>// #include &lt;stdlib.h&gt;<br>// typedef struct {<br>//     char* connection_status;<br>//     char* error_message;<br>// } InfoResponse;</pre><p>2. Import C to provide the needed functions to make this function C-comaptible</p><pre>import &quot;C&quot;</pre><p>3. Mark this function to be exported</p><pre>//export get_info<br>func get_info() *C.InfoResponse</pre><p>Notice that we define the return type as a pointer to the struct where C.InfoResponse is the struct we defined earlier.</p><p>4. Perform our logic</p><p>5. Convert the variable we want to return to C types</p><pre>cConnectionStatus := C.CString(string(connectionStatus))<br>cErrorMessage := C.CString(string(errorMessage))<br><br>// Create the struct<br>response := C.InfoResponse{<br>  connection_status: cConnectionStatus,<br>  error_message:     cErrorMessage,<br>}</pre><p>5. Allocate memory for the struct</p><p>We have to allocate memory for this struct manually or else the Go garbage collector might delete the “response” variable before Rust is done with it and cause a segmentation fault.</p><pre>// Allocate memory for the struct in C and copy the struct into it<br>pResponse := (*C.InfoResponse)(C.malloc(C.size_t(unsafe.Sizeof(response))))<br>*pResponse = response<br><br>return pResponse</pre><p>Then we can just return the pointer to Rust</p><h4>Writing the Rust code</h4><p>In Rust, we can <a href="https://github.com/rust-lang/rust-bindgen">rust-bindgen</a>. But I did this manually, I didn’t use a library because I wanted to understand what was going on myself.</p><ol><li>We need to define the structs</li></ol><pre>extern crate libc;<br><br>// Define the structs that will be used in C<br>#[repr(C)]<br>pub struct CInfoResponse {<br>    connection_status: *mut libc::c_char,<br>    error_message: *mut libc::c_char,<br>}</pre><p>In Rust, #[repr(C)] is an attribute that you can use to specify the memory layout of a struct, union, or enum to be compatible with C and we need it to be compatible with C to properly parse the data in the pointer returned by the Go code.</p><p>It also needs to be in the correct order, if in Go, the struct looks like this:</p><pre>// #include &lt;stdlib.h&gt;<br>// typedef struct {<br>//     char* connection_status;<br>//     char* error_message;<br>// } InfoResponse;</pre><p>And then in Rust, we change the order to this:</p><pre>#[repr(C)]<br>pub struct CInfoResponse {<br>    error_message: *mut libc::c_char,<br>    connection_status: *mut libc::c_char,<br>}</pre><p>What’s going to happen is that the 2 variables will be swapped. The order needs to be exactly the same and that’s why we need to use #[repr(C)]</p><p>In Rust, the compiler can rearrange the fields in a struct to minimize padding and optimize memory usage. To learn more about this check out this talk about <a href="https://en.wikipedia.org/wiki/Data-oriented_design">Data-Oriented Design</a> which explains padding and alignment perfectly well.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FIroPQ150F6c%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DIroPQ150F6c&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FIroPQ150F6c%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/5e8a3e25a0dca5a0b8f94140509daf09/href">https://medium.com/media/5e8a3e25a0dca5a0b8f94140509daf09/href</a></iframe><p>2. Define the functions to use from the external library</p><p>We need to define the name of the library linked to use its functions.</p><pre>#[link(name = &quot;thirdparty&quot;)]<br>extern &quot;C&quot; {<br>    fn get_info() -&gt; *mut CInfoResponse;<br>}</pre><p>3. Call the Go function in C</p><pre>extern crate libc;<br>use std::ffi::CStr;<br>use std::ffi::CString;<br><br>pub struct InfoResponse {<br>    pub connection_status: String,<br>    pub error_message: String,<br>}<br><br>pub fn get_info_response() -&gt; InfoResponse {<br>    unsafe {<br>        let response = get_info();<br><br>        if !response.is_null() {<br>            let connection_status = CStr::from_ptr((*response).connection_status)<br>                .to_str()<br>                .unwrap();<br>            let error_message = CStr::from_ptr((*response).error_message).to_str().unwrap();<br><br>            let info_response = InfoResponse {<br>                connection_status: connection_status.to_string(),<br>                error_message: error_message.to_string(),<br>            };<br><br>            libc::free((*response).connection_status as *mut libc::c_void);<br>            libc::free((*response).error_message as *mut libc::c_void);<br><br>            info_response<br>        } else {<br>            InfoResponse {<br>                connection_status: &quot;library_error&quot;.to_string(),<br>                error_message: &quot;Unhandled error while communicating with library&quot;<br>                    .to_string(),<br>            }<br>        }<br>    }<br>}</pre><p>We can use the FFI interface from Rust’s standard library to parse the C strings from a pointer.</p><pre>let connection_status = CStr::from_ptr((*response).connection_status)<br>    .to_str()<br>    .unwrap();</pre><p>Note that we have to manually free the memory allocated in the Go code because we can’t free it in Go before returning or there won’t be anything to return :D</p><pre>libc::free((*response).connection_status as *mut libc::c_void);</pre><h4>Passing parameters</h4><p>It works as you expect, you need to change the function’s definition:</p><pre>#[link(name = &quot;thirdparty&quot;)]<br>extern &quot;C&quot; {<br>    fn get_info(component: *const libc::c_char) -&gt; *mut CInfoResponse;<br>}</pre><p>In Go:</p><pre>func get_info(component *C.char) *C.InfoResponse {<br>  goComponent := C.GoString(component)<br>  ...<br>}</pre><p>However, you will need to parse the C string to a Go string so you can work with it.</p><p>When your function finishes execution, Rust will automatically drop component because of its ownership rules, which will be relevant later when we try to handle asynchronous code.</p><h3>Building</h3><p>Building is a tricky thing especially when cross-compiling. I struggled for days to get it working correctly and I can save you some time if you’re thinking about trying this yourself.</p><p>I use MacOS and building for MacOS was a breeze for me because it’s the system that I’m using, the problem arises when cross-compiling and when building for Windows while using Tauri.</p><p>Go environment variables when building:</p><p><em>GOOS — target OS, can be windows, linux or darwin</em></p><p><em>GOARCH — target architecture, can be arm64, amd64 or 386 (32-bit x86)</em></p><blockquote>It’s funny how GOARCH says 386 when it’s primarily building or i686. I don’t know whether the binary will actually support i386, it’s not like I have one of these lying around :D But I highly doubt it.</blockquote><h4>Building on MacOS</h4><p>Building the Go library is fairly easy, this command will build a static library with the (.a) extension.</p><pre>mkdir -p target/lib/darwin-arm64<br>CGO_ENABLED=1 GOOS=darwin GOARCH=arm64 go build -o target/lib/darwin-arm64/libthirdparty.a -buildmode=c-archive lib.go</pre><p>Notice how CGO is enabled and that allows us to use C code.</p><h4>Linking to Rust on MacOS</h4><p>We need to write a build.rs file that will print to stdout some flags for the compiler to use.</p><pre>#[cfg(all(target_arch = &quot;aarch64&quot;, target_os = &quot;macos&quot;))]<br>println!(&quot;cargo:warning=Compiling for Apple Silicon&quot;);</pre><p>In Rust, we can use #[cfg] to define which architecture to run a specific piece of code on. This line cargo:warning just outputs a warning log when building. Check out <a href="https://doc.rust-lang.org/cargo/reference/build-scripts.html">Rust’s build scripts</a> for more info.</p><p>This part is specific to MacOS only because of Apple’s ********:</p><pre>#[cfg(all(target_arch = &quot;aarch64&quot;, target_os = &quot;macos&quot;))]<br>println!(&quot;cargo:rustc-link-lib=framework=Security&quot;);<br><br>#[cfg(all(target_arch = &quot;aarch64&quot;, target_os = &quot;macos&quot;))]<br>println!(&quot;cargo:rustc-env=MACOSX_DEPLOYMENT_TARGET=11.0&quot;);</pre><p>Then we finally tell it to link the library, we give it a path to search for and the library’s name without any extensions or the lib prefix.</p><pre>println!(&quot;cargo:rustc-link-search=native={}&quot;, link_search_path);<br>println!(&quot;cargo:rustc-link-lib=static={}&quot;, &quot;thirdparty&quot;);</pre><p>And just like that! We have it working. Now let’s get into the juicy stuff where this bubble of happiness crumbles :D</p><h4>Linking to Rust on Windows</h4><p>Remember, I am cross compiling and I need this to work on Windows and Linux alike! Microsoft says no.</p><p>Why?</p><p>Because the trick to successfully linking the library is to use the same compiler on both ends and to build for Windows with Go, you have to use MingW since Microsoft deprecated MSVC on MacOS.</p><pre>brew install mingw-w64<br>mkdir -p target/lib/windows-x86_64<br>CGO_ENABLED=1 GOOS=windows GOARCH=amd64 CC=x86_64-w64-mingw32-gcc CXX=x86_64-w64-mingw32-g++ go build -o target/lib/windows-amd64/libthirdparty.a -buildmode=c-archive lib.go</pre><p>To use the full features of Tauri, we need to build with MSVC on Windows, not with MingW. Which makes it impossible to do this anymore without custom modifications to the C code Go generates.</p><p>Even worse, the commands the Go compiler uses are for gcc. If you try to build Go with MSVC you will see errors like -Werror -Wall and these are gcc flags, not cl flags where cl is the compiler for MSVC and it’s a mess that I didn’t want to deal with.</p><p>Just try to open “Developer Command Prompts for VS” and set the C compiler to cl</p><pre>set CC=cl<br>...try to compile</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*wb59j7A30SScOTgS.png" /></figure><p>BTW, Tauri won’t build with VS 2017, I just found this screenshot online :D</p><p>However, if you don’t need to build with MSVC, you can just use MingW and build the Rust binary with it, it will work 🤷‍♀</p><p>So I couldn’t successfully do this with Tauri, however, I had another project that I didn’t need Tauri in and I just compiled it with MingW and it worked perfectly. You just need to modify config.toml to use the MingW linker and set the target to gnu instead of msvc</p><p>.cargo/config.toml</p><pre>[target.x86_64-pc-windows-gnu]<br>linker = &quot;x86_64-w64-mingw32-gcc&quot;</pre><p>And then build:</p><pre>cargo run --target x86_64-pc-windows-gnu</pre><p>You can also override it to use GNU by default</p><pre>rustup override set x86_64-pc-windows-gnu</pre><h4>Linking to Rust on Linux</h4><p>We are not talking about Tauri here, I don’t want to support this for Tauri on Linux. I had another API to work with so no need to consider Tauri.</p><p>Oh boy, I expected this to be easy, but I couldn’t compile the Go library with GNU successfully for Linux on my Mac. I could compile it, but it just won’t link correctly, and to be honest, I have no idea why.</p><p>My initial attempt was to use MUSL. I installed MUSL and compiled the go library with it.</p><pre>CC=x86_64-linux-musl-gcc</pre><p>However, it just doesn’t work, when I build the Rust binary with MUSL and try to run it, it just causes a segmentation fault. <a href="https://github.com/rust-lang/rust/issues/95926">There’s a GitHub issue about this</a>.</p><p>So I just said f*** it and I used Docker to compile my Go library with GNU and used GNU to compile my API as well and it worked out perfectly.</p><p>However, don’t use Alpine Linux, it uses MUSL by default and you don’t want to mess with that :D Here’s an example docker file:</p><pre>FROM golang:1.20<br><br>WORKDIR /app<br><br>COPY go.mod go.sum ./<br><br>RUN go mod download<br><br>CMD [&quot;sh&quot;, &quot;-c&quot;, &quot;CGO_ENABLED=1 GOOS=linux GOARCH=arm64 go build -v -x -o target/lib/linux-arm64/libthirdparty.a -buildmode=c-archive lib.go&quot;]</pre><p>Then I had a build script to bind the /app path to my local directory so it has write access to it and I don’t even need to think about doing anything with Docker.</p><pre>docker run -it --name builder-linux-x86_64 --rm -v $(pwd):/app builder:linux-x86_64</pre><p>And here’s the docker image I used to deploy my API:</p><pre># Start from the official Rust image<br>FROM rust:latest<br><br>WORKDIR /usr/local<br><br># Install the necessary tools for cross-compilation<br>RUN apt-get update<br>RUN apt-get install -y gcc-x86-64-linux-gnu<br><br>RUN rustup target add x86_64-unknown-linux-gnu<br><br># Set the working directory inside the container<br>WORKDIR /usr/src/api<br><br># Copy the current directory contents into the container<br>COPY . .<br><br># Build the Rust project<br>RUN cargo build --release --verbose --target x86_64-unknown-linux-gnu<br><br>EXPOSE 4000<br><br># Set the entry point to run the compiled binary<br>CMD [&quot;./target/x86_64-unknown-linux-gnu/release/api&quot;]</pre><p>It just works!</p><h3>Handling asynchronous calls and Go routines</h3><p>This will involve some tricks to get it working successfully, but you’ll have to be very careful because we’re writing unsafe code and memory leaks can be a problem since we’re manually allocating and freeing memory.</p><p>The trick we’re going to use is to leverage Tokio’s oneshot channel. Basically what it does is that it creates a Sender and a Receiver where you can await the Receiver asynchronously until the Sender sends some data.</p><p>What we can do is create a Sender and a Receiver and pass a pointer to the Sender to Go. Then we can execute the Go routine and callback another function that we expose in Rust and it can resolve the pointer, trigger the sender to finish awaiting on the receiver, and then clear the allocated memory. We need to explicitly allocate some memory for the Sender to make sure Rust isn’t going to clear it when its ownership gets moved to the external Go function.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/797/1*gPu4shSGH_lYhsNpaNwLeg.png" /><figcaption>Flow for calling Go code from Rust asynchronously</figcaption></figure><p>Here’s the Rust code</p><pre>pub async fn get_info() -&gt; InfoResponse {<br>    // tx is the sender, rx is the receiver<br>    let (tx, rx) = oneshot::channel();<br>    // Allocate it on the heap<br>    let boxed_tx = Box::new(tx);<br>    // Box::into_raw ensures that Rust won&#39;t automatically<br>    // free the memory when it moves out of scope<br>    let handle = Box::into_raw(boxed_tx) as usize;<br><br>    unsafe {<br>        // Pass the pointer to Go<br>        wa_info(handle as libc::uintptr_t);<br>    }<br><br>    // Await the receiver asynchronously<br>    rx.await<br>        .expect(&quot;Failed to communicate with the library&quot;)<br>}</pre><p>Now we need to define the Callback and expose it externally so the Go code can call it:</p><p>We need to add the #[no_mangle] attribute to prevent Rust from modifying the symbol’s name in the final compiled binary and make sure it’s available in Go.</p><pre>#[no_mangle]<br>extern &quot;C&quot; fn get_info_callback(handle: usize, result: *mut CInfoResponse) {<br>    // Box::from_raw reads the pointer and parsers the data it&#39;s pointing to<br>    // It also moves the memory back into the ownership model<br>    // When the function goes out of scope, the memory will be freed<br>    let tx = unsafe { Box::from_raw(handle as *mut oneshot::Sender&lt;InfoResponse&gt;) };<br><br>    unsafe {<br>        if !result.is_null() {<br>            // Parse the like previously<br>            let status = CStr::from_ptr((*result).status).to_str().unwrap();<br>            let error_message = CStr::from_ptr((*result).error_message).to_str().unwrap();<br><br>            let info_response = InfoResponse {<br>                status: parse_status(status),<br>                error_message: error_message.to_string(),<br>            };<br><br>            // Use the Sender to notify the receiver<br>            let _ = tx<br>                .send(info_response)<br>                .expect(&quot;Failed to send back response from the library&quot;);<br>        } else {<br>            // Notify the receiver with an error code<br>            let _ = tx<br>                .send(InfoResponse {<br>                    status: Status::LibraryError,<br>                    error_message: &quot;Unhandled error while communicating with the library&quot;<br>                        .to_string(),<br>                })<br>                .expect(&quot;Failed to send back response from the library&quot;);<br>        }<br>    }<br>}</pre><p>Here’s the Go code</p><pre>//export get_info<br>func get_info(handle C.uintptr_t) {<br>   go func() {<br>    // Perform the login<br>    status, errorMessage := bot.IsSignedIn()<br>  <br>    // Convert to C strings like previously<br>    cStatus := C.CString(string(status))<br>    cErrorMessage := C.CString(string(errorMessage))<br>  <br>    response := C.InfoResponse{<br>     status:        cStatus,<br>     error_message: cErrorMessage,<br>    }<br>  <br>    // Allocate memory for the struct in C and copy the struct into it<br>    pResponse := (*C.InfoResponse)(C.malloc(C.size_t(unsafe.Sizeof(response))))<br>    *pResponse = response<br>  <br>    // Call the exposed Rust callback<br>    C.get_info_callback(handle, pResponse)<br>  <br>    // Free the C strings<br>    C.free(unsafe.Pointer(cStatus))<br>    C.free(unsafe.Pointer(cErrorMessage))<br>  <br>    // Free the struct<br>    C.free(unsafe.Pointer(pResponse))<br>   }()<br>}</pre><p>Notice how we can free the allocated memory in Go this time because we don’t have to free it Rust like previously.</p><p>Important to note that if we send other parameters like a string for example, we’ll have to parse it before running the Go routine because once the function goes out of scope, Rust will free the memory and it won’t be accessible inside the Go routine’s scope anymore causing a segmentation fault.</p><p>Thank you for reading, this was an interesting problem for me to tackle and I learned a lot while working on it :))</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5672932a966b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[10 Essential Steps to Dramatically Optimize The Performance of a Website]]></title>
            <link>https://medium.com/@ziadalzarka/dramatically-optimize-the-performance-of-a-website-def4b8f8aece?source=rss-c07fb8a8f629------2</link>
            <guid isPermaLink="false">https://medium.com/p/def4b8f8aece</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[wordpress]]></category>
            <category><![CDATA[seo]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Ziad Alzarka]]></dc:creator>
            <pubDate>Fri, 05 Jan 2024 01:42:03 GMT</pubDate>
            <atom:updated>2024-01-05T01:59:37.378Z</atom:updated>
            <content:encoded><![CDATA[<h4>Get a perfect PageSpeed insights score for a landing page whether it’s Wordpress or React</h4><h3>What we will be working on</h3><p>I’ll be using the example of the website of a company I used to work for <a href="http://coatconnect.com/">CoatConnect</a>.</p><p>Please note that I am no longer maintaining this website.</p><blockquote>I asked for permission to publish this article, so no worries :)</blockquote><h3>Analyzing problems</h3><p><a href="http://pagespeed.web.dev/">PageSpeed Insights</a> is a very powerful tool by Google. It allows us to analyze our website’s performance and figure out ways we can improve it.</p><p><strong>Score before optimization on Mobile</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*qkVT53mMSsfo_AuMctrB2A.png" /><figcaption>Score before performing optimizations on mobile</figcaption></figure><p><strong>Score before optimization on Desktop</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*f3z4d6Ky88L_CY5bShStbQ.png" /><figcaption>Score before performing optimizations on desktop</figcaption></figure><p>We notice there are some major problems that PageSpeed Insights has uncovered for us right out of the box.</p><h3>What can we do to make the website faster?</h3><p>We are using React for this project, but you can use any framework you like, the same concepts apply. This is a framework-agnostic article. It works with:</p><ul><li>Wordpress (you can use plugins for the techniques I’ll mention)</li><li>SPAs like React/Vue/Angular/Svelte …etc</li><li>MVCs like ASP.NET, Django, Express …etc</li></ul><p>In this article, I will be discussing React and Wordpress as they are the most common frameworks!</p><p>Here’s an overview of the final architecture we’ll be using:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/821/1*YIoY4t5pK5v_USlmmEvhhw.png" /><figcaption>Simple architecture</figcaption></figure><h4>1. Server-side rendering</h4><p>Your application has to be server-side rendered. In the case of Wordpress, this is already the default so no need to worry about that :)</p><p>The problem with SPAs is that they show content after loading JavaScript chunks first and executing them, so it takes a little while on the client before it can actually render content and that can destroy LCP and FCP.</p><p>You will have to convert your SPA into an SSR. In the case of React, you can use Next.js and for Vue you can use Nuxt.js or whatever technique works best for your case.</p><p>Note that it is not necessary to use frameworks like these, I did this manually because Next.js wasn’t mature enough yet to be able to migrate the whole project without pain. I used <a href="https://react.dev/reference/react-dom/server">Server React DOM APIs</a> before it got deprecated.</p><h4>2. Remove unused JavaScript</h4><p>In WordPress, you can cleanup unnecessary plugins and scripts your website isn’t using or you can try switching to different templates or whatever it takes to reduce the amount of JavaScript. It’s a matter of trial and error.</p><p>However, this can be a tough task for SPAs!</p><p><strong>Bundlephobia</strong></p><p><a href="https://bundlephobia.com/">Bundlephobia</a> is a great tool for analyzing bundle sizes of packages you install with NPM. For example, I switched from using <a href="http://momentjs.com/">moment.js</a> to <a href="https://day.js.org/">day.js</a> because it’s a much smaller library and does the same thing.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*Fyxi4CBlRQ0m8QUpSxrFOw.png" /><figcaption>moment.js on bundlephobia</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*hFpeCkaFonPBAbqLOXMUmw.png" /><figcaption>day.js on bundlephobia</figcaption></figure><h4>3. Lazy load components</h4><p>In the case of Wordpress or MVCs, you also don’t need to worry about this because the pages are static :)</p><p>Instead of downloading the entire SPA all at once, we can split it into smaller chunks that only include the needed code and we can import packages dynamically as we need them in the code instead of a top-level import.</p><p>This will dramatically decrease the initial chunk size and since we’re using React, we can utilize <strong><em>Code Splitting</em></strong> to split the app into chunks and lazy-load them accordingly.</p><ul><li><a href="https://webpack.js.org/guides/code-splitting/">Code Splitting in webpack</a></li><li><a href="https://rollupjs.org/tutorial/#code-splitting">Code Splitting in rollup</a></li><li><a href="https://nextjs.org/docs/pages/building-your-application/optimizing/lazy-loading">Lazy loading in Next.js</a></li></ul><p>You can analyze your bundle and modules using <a href="https://www.npmjs.com/package/source-map-explorer">source-map-explorer</a></p><pre>npx source-map-explorer dist/static/js/*.js</pre><p>This tool uses source maps to map bundles to their original files in your project and to npm packages as well, which can be helpful while fine tuning code splitting.</p><p>It might sometimes be better to take matters into your own hands and write your own strategy for code splitting instead of relying on the bundler’s default settings. The bundler you’re using should provide documentation on how to do this manually. I won’t post it here because everything changes overnight in the world of JavaScript, am I right? :)</p><h4>4. Reduce initial server response time (TTFB)</h4><p>High TTFB (Time-To-First-Byte) could be caused by a lot of different factors and the most common are:</p><ul><li>Low server resources</li><li>Static pages are not cached</li><li>Unoptimized server-side queries or latency in the database</li><li>Rendering depends on external API calls</li><li>Heavy computations</li></ul><p><strong>Caching on the server</strong></p><p>For Wordpress, you can use a plugin like <a href="https://wordpress.org/plugins/litespeed-cache/">LiteSpeed Cache</a> to support caching on the server.</p><p>For SPAs, you can do this in a million ways, you can implement your own caching layer inside the server itself or you can use a 3rd party or build a caching server, whatever works best. Here’s a very basic example of how you can implement this yourself in an express server.</p><p>Let’s assume our application’s response depends on 3 parameters:</p><ul><li>User’s language</li><li>Currency based on the user’s location</li><li>Device type (mobile, tablet, or desktop)</li></ul><p>Let’s create a middleware that generates a unique cache key for each different version of the website. It looks different on mobile than it does on desktop and it shows users different pieces of data based on their location.</p><pre>const cacheMiddleware = async (req, res, next) =&gt; {<br>  const key = `${req.url}${req.currency}${req.initialLanguage}${req.deviceType}`;<br>  const cacheKey = md5(key);<br>  req.cacheKey = cacheKey;<br>  ...<br>});</pre><p>We can later use this cache key to store the resulting HTML wherever you like. Let’s try storing them in memory. We can use node-cache.</p><pre>const cacheHolder = new NodeCache({ stdTTL: 3600, checkperiod: 600, useClones: false });<br>const cacheHTML = (key, html) =&gt; {<br>  cacheHolder.set(key, html);<br>};</pre><p>We can call this cacheHTML method, and pass it the cacheKey and the rendered HTML. We can also store different cache keys under the same request path to be able to invalidate the cache whenever the data changes.</p><p>This is a very naive implementation and not suited to be used to production, but it’s just to give you a rough idea of what can be done.</p><p>Some frameworks like Next.js can also do this for you for static pages and you can fine tune it to give you the best results.</p><p><strong>Using a CDN</strong></p><p>Using a CDN like CloudFlare, CloudFront or QUIC is also a great way to delegating the distribution of resource files instead of downloading directly from the server which consumes disk reads, CPU and bandwidth.</p><p><strong>Using a CDN as a caching layer</strong></p><p>A CDN can also be configured to cache the pages themselves for even faster serving of static pages, but be careful with this as the cache needs to be invalidated whenever a change to the pages is made. It can be done through the CDN’s API or in the case of Wordpress, plugins can handle this for you.</p><p>If your website’s cache policy depends on custom parameters, you can define that in your CDN’s configuration and make the cache dependent on some headers that the user sends like Accept-Language for example. It’s very easy to do that in a CDN like CloudFront. It depends on your architectural decisions :)</p><p><strong>Avoid heavy computations and external API calls</strong></p><p>You should never ever make rendering dependent on an external API call or a slow database query. Try avoiding it as much as possible, try caching or whatever works best for your case.</p><p>You should also avoid heavy computations on the server completely if you need it to reply quickly.</p><h4>5. Defer offscreen images</h4><p>For Wordpress, you can use a plugin like <a href="https://wordpress.org/plugins/litespeed-cache/">LiteSpeed Cache</a> as it supports lazy loading and image optimization.</p><p>When you open a website that has img tags in it, the browser goes ahead and fetches all these images and most of the time we have images that the user does not see until they scroll down the page. Those images must be lazy loaded to avoid making unnecessary network calls when we first load the website and leave more bandwidth for more important resources.</p><p>In React or any SPA, you can do this yourself or use a library <a href="https://www.npmjs.com/package/react-lazy-load-image-component">react-lazy-load-image-component</a>.</p><p>This is very easy to use, you just use it like you would use a normal img tag:</p><pre>import React from &#39;react&#39;;<br>import { LazyLoadImage } from &#39;react-lazy-load-image-component&#39;;<br><br>const MyImage = ({ image }) =&gt; (<br>  &lt;div&gt;<br>    &lt;LazyLoadImage<br>      alt={image.alt}<br>      height={image.height}<br>      src={image.src} // use normal &lt;img&gt; attributes as props<br>      width={image.width} /&gt;<br>    &lt;span&gt;{image.caption}&lt;/span&gt;<br>  &lt;/div&gt;<br>);<br><br>export default MyImage;</pre><h4>6. Minimize main thread work</h4><p>Figuring out what’s blocking the main thread can be a tough task, but here are common problems:</p><ul><li>Whole page is hydrated while loading</li><li>Third-party scripts are not deferred</li></ul><p>One of the ways to optimize blocking time is to lazily hydrate the page, and for that we can use <a href="https://www.npmjs.com/package/react-lazy-hydration">react-lazy-hydration</a> or <a href="https://www.npmjs.com/package/next-lazy-hydrate">next-lazy-hydration</a>.</p><p><strong>SSR Only</strong></p><p>This option should be used with static content that never changes on the page with JavaScript because, <em>ssrOnly</em> skips hydration all-together.</p><pre>import React from &quot;react&quot;;<br>import LazyHydrate from &quot;react-lazy-hydration&quot;;<br> <br>function App() {<br>  return (<br>    &lt;div&gt;<br>    &lt;LazyHydrate ssrOnly&gt;<br>      {…}<br>    &lt;/LazyHydrate&gt;<br>    &lt;/div&gt;<br>  );<br>}</pre><p><strong>When Idle</strong></p><p>This is a very important step because hydration blocks the main thread and using whenIdle delays the hydration until the static page has loaded first and the user is now seeing some content. Doing this ensures a low LCP time because if we hydrate instantly, then the main thread is busy hydrating the page and LCP is delayed.</p><pre>&lt;LazyHydrate whenIdle&gt;<br>  {…}<br>&lt;/LazyHydrate&gt;</pre><p><strong>When Visible</strong></p><p>You have to mark every part on the page that the user does not see instantly as whenVisible to avoid blocking the DOM while hydrating these parts.</p><p>An example problem would be if you <strong>Google Maps</strong> on your page. The Google Maps scripts will load and execute alongside the code while the page is being hydrated which is blocking, so it is very important to use whenVisible with the parts on the page that the user does not see instantly.</p><pre>&lt;LazyHydrate whenVisible&gt;<br>  {…}<br>&lt;/LazyHydrate&gt;</pre><p>Then, make sure every third-party script added and all JavaScript chunks are deferred to avoid downloading instantly.</p><pre>&lt;script src=&quot;[some-third-party-script].js&quot; defer&gt;&lt;/script&gt;<br>&lt;script src=&quot;[some-chunk].[hash].js&quot; defer&gt;&lt;/script&gt;</pre><h4>7. Avoid redirects at all costs</h4><p>Redirects cause a delay in page load and whatever that delay maybe every millisecond matters! If a delay in page redirect is 300ms, that’s 300ms you could save on page load time.</p><p>If you are using a URL shortener for assets especially images, that’s a 300ms delay on each image and sometimes that image could be contributing to your LCP.</p><h4>8. Load CSS asynchronously</h4><p>CSS is a pretty expensive asset that can block the main UI thread. To prevent CSS from blocking the main UI thread we have to do two things:</p><ul><li>Load CSS asynchronously</li><li>Generate our critical path CSS</li></ul><p>You can load CSS asynchronously using JavaScript like this:</p><pre>&lt;link <br>  href=&quot;CSS_ASSET&quot;<br>  rel=&quot;stylesheet&quot;<br>  media=&quot;print&quot;<br>  onload=&quot;this.media=&#39;all&#39;;this.onload=null;&quot; /&gt;</pre><p>Adding this onload property will cause CSS to load asynchronously preventing it from blocking the main thread, but doing that would make our website with no styles at all until the CSS loads and cause CLS and delay of LCP and we counter that with Critical Path CSS.</p><h4>9. Critical Path CSS</h4><p>For Wordpress, you can still use <a href="https://wordpress.org/plugins/litespeed-cache/">LiteSpeed Cache</a> for this. It outsources it and is a paid option. However, you can use any other plugin or create your own CCSS provider and host it somewhere.</p><p>To optimize for a high LCP score, we have to show styled content on the screen as fast as possible and not wait for external CSS or for JavaScript to modify the DOM.</p><p>Here’s the content we want to show to the user eventually:</p><p><strong>JavaScript Enabled</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*-2tIRfgfqAaSIgyixTw3ww.jpeg" /><figcaption>Website with CSS and JavaScript</figcaption></figure><p>Previously, we made CSS load asynchronously using JavaScript. Now, let’s try disabling your JavaScript.</p><ul><li>Open the Inspector (Ctrl+Shift+I)</li><li>Hit Ctrl+P</li><li>Type in “Disable JavaScript”</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/602/1*ZB7KQxbHldoY9r2BOwy_CA.png" /><figcaption>Disable JavaScript</figcaption></figure><p><strong>JavaScript Disabled (No CSS)</strong></p><p>Since we load CSS using JavaScript, CSS is not loaded, and as you can see, the page does not have any styles at all!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*vDc2C6sCdxkDU5_tSyrSaw.jpeg" /><figcaption>No CSS or JavaScript</figcaption></figure><p>To fix that, we need to generate the Critical Path CSS (CCSS). It is basically the CSS needed to only render what the user sees on the screen first.</p><p><strong>JavaScript disabled (CCSS)</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*-dY280VlAKM25sdo00Mh9Q.jpeg" /><figcaption>Page with Critical CSS</figcaption></figure><p>You can see here that the page has the <strong>Critical</strong> CSS on it without the need of downloading the full CSS stylesheet or JavaScript. As a matter of fact, there are images that are not shown here because they are lazy-loaded and JavaScript is not enabled.</p><p>To generate CCSS in SPAs, you can use the npm package <a href="https://www.npmjs.com/package/critical">critical</a>.</p><pre>// eslint-disable-next-line prefer-const<br>let { html, uncritical } = await critical.generate({<br>  base: &#39;build/public&#39;, // Local path to public assets<br>  html: renderedHTML, // Result of Server-Side rendered code<br>  width: viewPort.width, // User&#39;s device view port<br>  height: viewPort.height, // User&#39;s device view port<br>  inline: true, // Inlines css to improve performance<br>  minify: true, // Minifies css put into the &lt;style&gt; tag in the head<br>  rebase: asset =&gt; …, // Post process paths to assets in your css e.g. images, fonts, …etc<br>});</pre><p><strong>Getting the viewport of the user</strong></p><p>We can use the “User-Agent” header to detect which type of device the user is using and we can use the npm package <a href="https://www.npmjs.com/package/mobile-detect">mobile-detect</a> for that.</p><pre>import MobileDetect from &#39;mobile-detect&#39;;<br>export const getDeviceType = req =&gt; {<br>  const md = new MobileDetect(req.headers[&#39;user-agent&#39;]);<br>  if (md.tablet()) {<br>    return &#39;tablet&#39;;<br>  }<br>  if (md.mobile()) {<br>    return &#39;mobile&#39;;<br>  }<br>  return &#39;desktop&#39;;<br>};</pre><p>We can then use this express middleware to inject viewPort property in the request.</p><pre>const deviceTypeMiddleware = (req, res, next) =&gt; {<br>  req.deviceType = getDeviceType(req);<br>  req.viewPort = {<br>    mobile: { width: 414, height: 896 },<br>    tablet: { width: 768, height: 1024 },<br>    desktop: { width: 1366, height: 842 },<br>  }[req.deviceType];<br>  next();<br>};</pre><p>This critical path CSS generator does not require you to use express for server-side rendering your app. It can sit in the middle between your server and your clients and act as a middle layer.</p><p>You can architect this however you like, it can integrated into your caching layer and generated on demand. However, this is a long process it takes seconds and it is better to serve without Critical CSS than it is to make the user wait until it’s being generated!</p><h4>10. Optimize images and use next-gen image formats</h4><p>You can automate this process in a CMS easily by using plugins and in the case of an SPA, the bundlers can do this automatically for you if it’s resources or you can create your own image optimizer based on your needs if it’s user uploaded content. However, you can always outsource and use tools like <a href="https://cloudinary.com/">Cloudinary</a>.</p><p>For static images that will always be in your website like backgrounds or a hero section, you can use <a href="https://squoosh.app/">Squoosh</a> to fine tune the optimization of your images and see the difference in quality in real-time!</p><h4>Thank you!</h4><p>I hope you benefited from this article :) Thank you :))</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=def4b8f8aece" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The easiest way to crack a WiFi password using your computer]]></title>
            <link>https://medium.com/@ziadalzarka/the-easiest-way-to-crack-a-wifi-password-using-your-computer-7f0b308feb10?source=rss-c07fb8a8f629------2</link>
            <guid isPermaLink="false">https://medium.com/p/7f0b308feb10</guid>
            <category><![CDATA[wifi]]></category>
            <category><![CDATA[hashing]]></category>
            <category><![CDATA[passwords]]></category>
            <category><![CDATA[hacking]]></category>
            <category><![CDATA[hashcat]]></category>
            <dc:creator><![CDATA[Ziad Alzarka]]></dc:creator>
            <pubDate>Thu, 04 Jan 2024 18:10:42 GMT</pubDate>
            <atom:updated>2024-01-05T02:11:31.648Z</atom:updated>
            <content:encoded><![CDATA[<h3>The Easiest Way To Crack a WiFi Password Using Your Computer</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Oti35sgMx4KkYbo6CsfPRQ.png" /><figcaption>Cracking a WiFi password using hashcat</figcaption></figure><h3>How does WiFi cracking work?</h3><p>If you’re curious about understanding how this works you’ll need to understand how WiFi authentication works. in the first place. But it all boils down to a simple process:</p><ul><li>Start listening for packets for the target WiFi network</li><li>Perform deauthentication</li><li>Capture WiFi handshake</li><li>Crack the handshake</li></ul><p>When you connect to your home WiFi network, a handshake is done between your phone and the access point.</p><p>Wi-Fi handshakes are part of the process by which a device (like a laptop or smartphone) connects securely to a Wi-Fi network. The most common type is the WPA/WPA2 handshake, which is used to establish a connection using the Wi-Fi Protected Access (WPA or WPA2) security protocol.</p><p>The WPA/WPA2 handshake process then begins, which is a four-step process:</p><p><strong>Step 1: Authentication Request (AP → Client):</strong></p><p>The AP sends an authentication request to the client, including a random number known as an ANonce (AP nonce).</p><p><strong>Step 2: Authentication Response (Client → AP):</strong></p><ul><li>The client device generates its own random number called SNonce (Supplicant nonce), creates a pre-shared key (PSK) if using WPA2-PSK (based on the Wi-Fi password), and calculates a MIC (Message Integrity Code) using the ANonce, SNonce, PSK, and MAC addresses.</li><li>The client sends back its SNonce, along with the calculated MIC, to the AP.</li></ul><p><strong>Step 3: The AP verifies the MIC:</strong></p><ul><li>The AP uses the received SNonce, its ANonce, the PSK, and the MAC addresses to calculate its own MIC.</li><li>If its MIC matches the one received from the client, the AP knows that both it and the client have the correct PSK.</li><li>The AP then sends a message to the client confirming the successful authentication and includes the GTK (Group Temporal Key), encrypted with the PSK.</li></ul><p><strong>Step 4: Acknowledgment and Encryption Ready (Client → AP):</strong></p><ul><li>The client sends an acknowledgment back to the AP.</li><li>Both the AP and the client now have the necessary keys to encrypt and decrypt the data they send to each other.</li></ul><p>After the handshake, all data transmitted between the client and the AP is encrypted using the established keys, providing a secure Wi-Fi connection.</p><h4>How can we crack the password?</h4><p>We can do that by intercepting the handshake, extracting the hash from it and trying to crack it locally by trying different combinations of characters until we try the correct combination which is the password!</p><p>How do we intercept the handshake? Well… it might not seem obvious, but WiFi isn’t directional, it doesn’t send data to a specific device, it broadcasts it in the air and all the clients can receive this data! Which is exactly why we need to encrypt the traffic because everyone receives everything!</p><p>Modern software just filters the received packets to extract out the ones meant to it only!</p><h3>Hash cracking with GPUs</h3><p>You will need a powerful GPU for this. Hash cracking is much faster using GPUs for the following reasons:</p><ul><li>GPUs are designed for highly parallel operations. They contain hundreds or thousands of smaller cores designed for handling multiple tasks simultaneously. This is in contrast to CPUs, which typically have a much smaller number of cores optimized for sequential serial processing and are more general purpose.</li><li>Hash cracking involves trying millions or billions of combinations, which is a highly parallelizable task. Each attempt to crack a hash can be processed independently. GPUs can handle many such attempts in parallel, significantly speeding up the process.</li><li>GPUs have instruction sets that are often more optimized for the types of computations required for hash cracking, such as bitwise operations and large number arithmetic as it’s used in computer graphics.</li></ul><h3>Steps to cracking a WiFi password</h3><p>We will be using 3 tools for this:</p><ul><li><a href="https://github.com/phenotypic/WiFiCrackPy">WiFiCrackPy</a> which is a python script that automates most of this attack for you</li><li><a href="https://github.com/cyrus-and/zizzania">zizzania</a> used by the script to perform the deauthentication attack</li><li><a href="https://hashcat.net/hashcat/">hashcat</a> used to crack the hash itself</li></ul><p>Start by installing the <a href="https://github.com/phenotypic/WiFiCrackPy">WiFiCrackPy</a> prerequisites:</p><pre>brew install hashcat libpcap wget hcxtools</pre><p>Clone <a href="https://github.com/cyrus-and/zizzania">zizzania</a> and compile it:</p><pre>make -f config.Makefile &amp;&amp; make -j &quot;$(sysctl -n hw.logicalcpu)&quot;</pre><p><em>Please keep in mind that the prerequisites might change in the future, it is accurate at the time I’m posting this article :)</em></p><p>Then clone <a href="https://github.com/phenotypic/WiFiCrackPy">WiFiCrackPy</a> and install it’s depenedencies</p><pre>git clone https://github.com/phenotypic/WiFiCrackPy.git<br>cd WiFiCrackPy<br>pip3 install -r requirements.txt</pre><p>Now let’s run the script:</p><pre>python3 WiFiCrackPy.py</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*34sWVtokUtD2OmM-T4bxfA.png" /><figcaption>Running WiFiCrackPy.py</figcaption></figure><p>Now select the WiFi network, I selected 4.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*obrrKMmbaQAoiWYoBFQLNw.png" /><figcaption>Waiting for the handshake</figcaption></figure><p>Now it’s waiting to capture the handshake and this happens when a client disconnects and connects again, which is what the deauthentication attack does.</p><p>You can make the tool run the deauthentication attack automatically by running it with the arguments -d.</p><pre>python3 WiFiCrackPy.py -d</pre><p>However, this doesn’t always work and because this article is for education purposes only, I won’t get into details on how to perform this, I just simply disconnect and connect again on my phone.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rviPAXZ_7gn2OEjG5WVqqg.png" /></figure><p>I’ll select <a href="https://hashcat.net/wiki/doku.php?id=mask_attack">brute-force</a> and since I already know the password is 11 digits, I’ll supply it with a <a href="https://hashcat.net/wiki/doku.php?id=mask_attack">pattern</a> of only digits and 11 characters and I’ll also provide it with the first 4 digits to speed up the process and not burn my computer out as this would usually take days :D Speeding it up this way will make it only take a minute.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hEkYmPnbomOUVSkNahdH4A.png" /><figcaption>Brute-force pattern</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*w9NBW3dd-enmdm9o4946Gg.png" /><figcaption>Status</figcaption></figure><p>As you can see, it’s iterating through every possible combination of digits and trying to crack the hash. You can use dictionaries if you think the password might be common or your own <a href="https://hashcat.net/wiki/doku.php?id=mask_attack">brute-force pattern</a>.</p><p>Aaaaand finally, it’s cracked!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Y22r5BVEbOSvp4ShLHQeug.png" /><figcaption>Password cracked!</figcaption></figure><p>If you would like to stop and try again, it’s okay because this tool saves the handshake in capture.hc22000 file and you can run hashcat on it pretty easily.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cdHe82iwzWW0I1HRqVZLaw.png" /></figure><p>You can run hashcat by running:</p><pre>sudo hashcat -m 22000 capture.hc22000 -a 3 &quot;2510?d?d?d?d?d?d?d&quot; -O</pre><p>If for some reason your WiFi gets stuck in monitoring mode you can just run this command to switch it back:</p><pre>sudo tcpdump -I -i en0 -p</pre><p>Note that en0 is the interface name, it might be named something else your machine, you can use ifconfig to find out.</p><h3>Benchmarks</h3><p>You can find benchmarks for different GPUs online easily by googling them. We are typically looking for the 22000 module benchmark as it’s the one used for cracking a WiFi password.</p><p>You can also benchmark your own computer by running the command:</p><pre>hashcat -b</pre><p>However, this command will benchmark all hashcat modules and to benchmark the WPA module only, you can run:</p><pre>hashcat -m 22000 -b</pre><p>Here are the benchmarks from my own computer:</p><pre>ziadalzarka@MacBook-Pro WiFiCrackPy % hashcat -m 22000 -b<br>hashcat (v6.2.6) starting in benchmark mode<br><br>Benchmarking uses hand-optimized kernel code by default.<br>You can use it in your cracking session by setting the -O option.<br>Note: Using optimized kernel code limits the maximum supported password length.<br>To disable the optimized kernel code in benchmark mode, use the -w option.<br><br>* Device #2: Apple&#39;s OpenCL drivers (GPU) are known to be unreliable.<br>             You have been warned.<br><br>METAL API (Metal 341.35)<br>========================<br>* Device #1: Apple M1 Max, 10880/21845 MB, 32MCU<br><br>OpenCL API (OpenCL 1.2 (Nov 11 2023 23:48:17)) - Platform #1 [Apple]<br>====================================================================<br>* Device #2: Apple M1 Max, skipped<br><br>Benchmark relevant options:<br>===========================<br>* --optimized-kernel-enable<br><br>-------------------------------------------------------------<br>* Hash-Mode 22000 (WPA-PBKDF2-PMKID+EAPOL) [Iterations: 4095]<br>-------------------------------------------------------------<br><br>Speed.#1.........:   245.0 kH/s (66.27ms) @ Accel:64 Loops:512 Thr:64 Vec:1<br><br>Started: Thu Jan  4 19:21:22 2024<br>Stopped: Thu Jan  4 19:21:25 2024</pre><p>I hope you fed your curiosity by reading this article, please don’t use it for unethical purposes it’s for education only :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7f0b308feb10" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>