Saturday, October 23, 2021

Hash Function in Action: Message Authentication Codes

In Introduction to Cryptographic Hash Functions for the Working Developer, I presented a straight to the point, overview of some essential things a developer should know about cryptographic hash functions. 

This post continues in the theme around hash functions, by taking a look at another cryptographic construction hash functions make possible, that is: Message Authentication Codes (MACs).

It is worth quoting Bruce schneier again:

Much more than encryption algorithms, one-way hash functions are the workhouses of modern cryptography

Because Message Authentication Code based on hash functions is a perfect demonstration of how crucial hash functions are.

This post contains the following sections:

  • Why Hash Functions alone are not enough
  • What is Message Authentication Code
  • What is a Hash Based Authentication Code (HMAC)
  • What is a Keccak Based Authentication Code (KMAC)
  • Some real world applications of Message Authentication Code

Wednesday, October 20, 2021

Introduction to Cryptographic Hash Functions for the Working Developer

Much more than encryption algorithms, one-way hash functions are the workhouses of modern cryptography - Bruce schneier

This post would be a quick, straight to the point, overview of some essential things a developer should know about cryptographic hash functions. It is targeted at the working developer who needs to be familiar enough with cryptographic hash functions in order to use them, but who does not need to know the gory details of how they are implemented, all their possible use cases or how they work internally.


This post contains the following sections:
  1. Cryptographic hash function: A definition
  2. Properties of cryptographic hash functions.
  3. Types of hash functions
    1. Fixed length hash Functions
    2. Extendable Output Functions (XOF)
    3. Password hashing functions 
  4. Some Hashing Hygiene

Tuesday, September 28, 2021

NFTs are not to blame

T206 Honus Wagner baseball card sold for $6.606 million just this August 2021, Pikachu Illustrator, a pokeman card sold for $195,000 in 2019. You can get different Micheal Jordan's basketball card on e-bay ranging from couple of thousands to couple of millions. Sentimental and collectible items have always been part of the human experience. NFTs are not to blame.

Why should pieces of cards with pictures of athletes (or game characters) be worth that much? Why should JPEGs/PNGs be worth that much? Maybe because humans also value things for sentimental reasons just as they do for utilitarian/sustenance reasons.

NFTs only made the act of ownership that was so easy to establish in the physical realm, also possible in the digital realm. It's only natural it will be used for digital arts/collectible culture.

The mistake to avoid, is thinking NFTs are only about digital arts and collectibles. No! they are more than this. The ability to create unique, non fungible digital items that can be provable owned, can be, and is being deployed for other use cases.


Monday, September 13, 2021

Why I am offering NFTs as a crowdfunding perk

Non-equity funding campaigns are always based on promises: "Back us now, and we promise you early access to the product when we launch, or we promise you a discount, digital shout-out or swags". I am currently running an Indiegogo campaign where the promise will also include an NFT: Non Fungible Token, which is a digital artifact that can be used to prove things like ownership. This, as far as I know, is the first time NFTs would be used in this capacity.

In this post, I will shed some light on what NFTs are and share my thoughts on why they are a  perfect perk for a non-equity crowdfunding campaign. In doing so, I will touch on my thoughts on the continual march towards the digitalization of the human experience. How digitalization and technologies like virtual/augmented reality, blockchain technology, etc are making it possible to further digitize aspects of society and human interaction that were previously rife with problems or just plain impossible to digitize.

By the way, my campaign is to kickstart the development of DishAfrik: a recipe app to discover, enjoy and share African recipes. Think of it as Yummly or Tasty.co but focused on African cuisine. One of the perks of the campaign is going to be 54 uniquely generated collages made up of 54 recipes from 54 countries. 54 because currently Africa is home to 54 fully recognised sovereign states.

You should check out the IndieGoGo campaign and back the project :) Find it here 

TL;dr 
  • Ever since the third industrial revolution, there has been a march towards digitalization of the physical world. 
  • Blockchain-related technologies, like NFTs, provided the possibility to digitize aspects of the physical world that relied on scarcity, uniqueness, and proof of ownership, aspects that were previously hard to digitize. 
  • DishAfrik's Indiegogo campaign will be making use of NFTs as a perk, using it as a way to capture participation, while also creating digital art in the form of a recipe collage that can also be owned.


Friday, June 11, 2021

Understanding the Magic behind Utility Types in TypeScript

This post will be the conlcuding post in the Introduction to Advanced Types in TypeScript series. It looks at some of the utility Types in TypeScript, explain how it works while pointing out the features within the TypeScript type system that makes it possible.

Why TypeScript?

TypeScript comes with a powerful and expressive type system. Its expressiveness makes it a joy to work with while its powerful features makes it possible to build, and scale large codebases by providing type safety.

One of the ways TypeScript brings about type safety is by providing developers the tool to manipulate types in ways that encode constraints within the type system. This then ensures that code that could lead to runtime exception do not compile, making it possible to catch errors during development time and not in production. One of such tools TypeScript provides for this are Utility Types.

Utility Types are a set of Generic Types that come natively within TypeScript that makes it possible to transform one type into another. This sort of type transformation is useful because it makes it possible to take exiting types, and apply modifications to it which would ensure the enforcement of certain constraints.

In this post, we would look at 2 of such Utility type and how they could be used to provide more type safety. After that, we would take a step back to understand some of the other TypeScript features that come together to make Utility Types possible. Armed with this knowledge, we will then demystify Utility types by taking a peek under the hood of the 2 Utility types in focus to see how they are implemented.


Monday, June 07, 2021

First impressions with Deno from building PlanetTypeScript.com

PlanetTypeScript.com is a content aggregator for all things TypeScript. It regularly polls RSS feeds for TypeScript related content, which it then list on the site, send out as a tweet via @planetypescript, and also as a weekly digest to subscribers.

Back when I used to write a lot of Java-related content on this blog, I found out that my blog ended up on www.topjavablogs.com/, which is a site that aggregates Java contents. So when I decided to play around with Deno, I thought a nice little idea would be to build something similar to topjavablogs.com, but for TypeScript. And that is how PlanetTypescript.com was born.

In this post, I will share some of my first impressions with Deno. The things I enjoyed and the bits I found inconvenient. Let's start with the cool stuff.


Friday, May 28, 2021

3 Ways to Name Types in Typescript

TypeScript type's system is structural and hence, it allows for the easy creation of types based on the shape of data. These types can be created and used without having a name. For example:

let john: {name: string, age: number} = { 
  name: "John Doe", 
  age: 30
}

Where {name: string, age: number} is the type defined.

But there is a problem with using the type definition this way. If we want to create another person and annotate another variable with the type, we would need to repeat ourselves:

let john: {name: string, age: number} = {
  name: "John Doe", 
  age: 30
}

let jane: {name: string, age: number} = {
   name: "Jane Doe", 
   age: 45
}

This is not dry.


Saturday, May 22, 2021

How to implement sleep function in JavaScript

Most popular mainstream languages have a sleep functionality that allows for the pausing of code execution for a specified amount of time. Not surprising this functionality is often implemented via a function usually named sleep. For example:

// ruby
sleep(time_secs)
// python
import time
time.sleep(time_secs)
// Java
Thread.sleep(time_milli_secs)
// Perl
sleep(time_secs)

JavaScript does not have a similar sleep function, although it has the setTimeout function which can be used to achieve a similar purpose. The only problem is, using setTimeout is not as convenient as one would like. This is due to the fact that setTimeout is an asynchronous function, hence one would have to continue the execution of the code, in the callback passed to it, after the elapsed time.

console.log("Executing code..."); 
setTimeout(() => { 
console.log("continue after pause"); 
}, 3000)

This is not convenient.

A more convenient option would be to have something similar to:

console.log("Executing code..."); 
// sleep for some time
// sleep()
console.log("continue after pause");

Unfortunately, this does not exist natively in JavaScript. But this is not to say we can't implement one!


Thursday, May 20, 2021

Callback, Promise and Async/Await by Example in JavaScript

This post is going to show,  by way of code examples, how to take a callback based API, modify it to use Promises and then use the Async/Await syntax. This post won't go into a detailed explanation of callbacks, promises or the Async/Await syntax. For such a detailed explanation of these concepts please check Asynchronous JavaScript, which is a section of MDN Web Docs, that explains asynchronicity and how callbacks, promises, and the Async/Await syntax helps with working with asynchronous JavaScript.

This post is meant for the developer who has somewhat of an understanding of asynchronicity in JavaScript, but requires a straight to the point code example to serve as a quick syntax reference for how to take a callback based API, update it to use promises and finally use the Async/Await with it.

For demonstration purposes, we are going to use the fs.readFile, which is a callback based API from reading files. We will have a file test.txt that would contain some text, we will then have a file script.js that would open the file, read the contents, and print it to the terminal.

The code will first be implemented using callbacks, it would then be updated to use Promises, and finally, instead of using Promise directly, it will be updated to use Async/Await.

Let's get started.


Sunday, May 09, 2021

ip-num v1.3.2 has been released

ip-num is A TypeScript/JavaScript library for working with ASN, IPv4, and IPv6 numbers. It provides representations of these internet protocol numbers with the ability to perform various IP related operations like parsing, validating etc, on them.

A new version of ip-num, version 1.3.2 is now available.

This release contains one new feature and a bug fix.

Add method to split range into smaller ranges of certain size

In previous versions of ip-num, it was possible to take IP ranges with prefix less than /32 and split them into two. For example:

import {IPv4CidrRange} from "ip-num/IPRange";
import {IPv4Prefix} from "ip-num/Prefix";

let ipv4CidrRange = IPv4CidrRange.fromCidr("192.168.208.0/24");
let splitRanges: Array<IPv4CidrRange> = ipv4CidrRange.split();

// console logs:
// 192.168.208.0/25
// 192.168.208.128/25

splitRanges.forEach(range => console.log(range.toCidrString()))

But what if one needs to take an IP range and instead of just splitting into two, there is the requirement to split into a number of ranges with a specified prefix? Well, that is now possible with the addition of splitInto method:

import {IPv4CidrRange} from "ip-num/IPRange";
import {IPv4Prefix} from "ip-num/Prefix";

let ipv4CidrRange = IPv4CidrRange.fromCidr("192.168.208.0/24");
let splitRanges: Array<IPv4CidrRange> = 
ipv4CidrRange.splitInto(IPv4Prefix.fromNumber(26));

// console logs:
// 192.168.208.0/26
// 192.168.208.64/26
// 192.168.208.128/26
// 192.168.208.192/26

splitRanges.forEach(range => console.log(range.toCidrString()))

RangedSet.isCidrAble() incorrect results

Previous versions of ip-num failed to properly report that a string representing a single IP can be represented in the CIDR notation. This has now been fixed:

import {RangedSet} from "ip-num/IPRange";

let rangedSet= RangedSet.fromRangeString("1.2.3.4-1.2.3.4");

// now returns true
console.log(rangedSet.isCidrAble())

As always, ip-num is just an npm install or npm upgrade away.

Feel free to open an issue to discuss a feature or to report a bug.


Sunday, April 25, 2021

Mapped Types in Typescript

This post will explore Mapped Types, another advanced feature of the Typescript type system. It is part of the Introduction to Advanced Types in TypeScript series.

A useful mental model to have when approaching some of the advanced type system features of Typescript is to view them as a mechanism for constructing other types from existing types. This view is spot on when it comes to mapped types as they are a mechanism that Typescript provides by constructing new types by mapping existing types into new ones.

This post would show how this looks like. It would be as beginner-friendly as possible, but having some knowledge of GenericsUnion Types and Literal types in Typescript would be a plus.

To kickstart we take a quick again, at the keyof Operator, as it is essential to the workings of Mapped Types.


Tuesday, April 06, 2021

Conditional Types in Typescript

This post is about conditional types in typescript, which happens to be an interesting and powerful feature of the typescript's type system. It is part of the Introduction to Advance Types in TypeScript series.

Conditional types can be seen as a mechanism that allows us to perform ternary operations on types. 

Normally, ternary operations work with values, for example:

resulting value == true ? value A : value B
let value = 10
const isEven = value % 2 == 0 ? true : false
Conditional types gives us the ability to perform similar operation on types. Where we get a type out of two possibility, depending on the outcome of a check. 


Saturday, April 03, 2021

any, unknown and never types in Typescript

This post will be a quick overview of three interesting types in Typescript: any, unknown, and never with the aim of quickly explaining what they are, and when to use them. It is part of the Introduction to Advance Types in TypeScript series.  

To start with, it is a good mental model to view Types from the perspective of set theory. This idea is fully explored in Union and Intersection Types in TypeScript, but for a quick summary, the idea is simple. When types are created, see it as similar to defining a Set. And what do sets contain? they contain objects. The next thing is to see values as objects that belongs to a set. A value defined to be part of a set, would not be allowed in a different set which it does not belong in or overlap with. 


Friday, April 02, 2021

Tuple Types in TypeScript

In this post, we would be looking at tuple types in TypeScript. It will also touch on generic rest parameters and variadic tuple types which are two of the advanced parts of tuple types. 


Sunday, March 14, 2021

I'm on a roll! 😅

Just this Tuesday, 9th of March, at work, I was partly responsible for a partial downtime of a critical piece of the internet's infrastructure. 

This morning, I got two packages delivered to my place. One for myself, the other, to keep for my neighbor who wasn't at home. A combination of miscommunication with the delivery guy and excitement to unwrap my package, I ended up tearing up my neighbors package, mistaking it for mine! 😅. It was super awkward explaining my little mistake to her, when she came to pick her stuff up 😬. 

And fast forward to just a couple of hours ago, I mistakenly pushed a property file containing sensitive credentials to Github! Impact not super devastating but still, some damage control had to be done! 

It feels like I am on a roll here...what will I be tripping over next? What will the next gaffe be? Me dropping the database in production? 😅😬

Update: Two months after, no database was harmed :)

Saturday, March 06, 2021

Spread and Rest in JavaScript

What does the rest parameter syntax look like? 

Simple, It looks like this: ...stuff

That’s cool. What about the spread syntax? What does that look like?

Well, it also looks like this: ...stuff

And this is why the spread and the rest parameter syntax could be confusing and easily misplaced for each other. They have precisely the same syntax! What then separates them? Answer is the context they are used.

This post will look into these JavaScript syntaxes with the aim of disambiguating them. The hope is that it helps in removing the confusion.


Saturday, February 27, 2021

Introduction to Index Types in TypeScript

This post will look at Index Types in TypeScript. It will go over what they are and also touch on two type-operators related to them. These type operators are the index type query operator and indexed access operators. 

This post is part of the Introduction to Advanced Types in TypeScript series. To better understand, it requires having some familiarity with Union Types, Generics, and Literal types. These are topics that have already been covered in the series.


Tuesday, February 16, 2021

Overview of Indexable Types In TypeScript

This blog post will look at Indexable Types. It is part of the Introduction to Advanced Types in TypeScript series.

In JavaScript, there are values, from which additional values can be retrieved via an index. A natural example of such a value is an Array: For example, given the following array:

const primaryColors =  ["red", "green", "blue"]

The value primaryColors is an array value, and its individual content can be accessed by providing an index of type number:

console.log(primaryColors[0])
console.log(primaryColors[1])
console.log(primaryColors[2])


Sunday, February 07, 2021

Using Literal and Template Literal Types in TypeScript

This blog post will look at some of the use cases of literal and template literal types in TypeScript. It is a continuation of Literal and Template Literal Types, which introduces the language feature and it is a part of the Introduction to Advanced Types in TypeScript series.

This post will look at the following use cases:

  1. Compile time spell checker
  2. Alternative to enum
  3. Discriminated Union Pattern
  4. Stricter Type Constraints and Type Level Computation

Monday, February 01, 2021

Literal and Template Literal Types

This blog post will look at Literal and Template Literal Types. It is part of the Introduction to Advanced Types in TypeScript series.

In the post, Union and Intersection Types in TypeScript, the idea of viewing types with the perspective of Set theory was introduced. The key idea is to see types more or less as sets, and values of a type as elements that belong to a set. If this idea of viewing types from the perspective of Set theory is new to you, then I’ll advise to take a pause and read Union and Intersection Types in TypeScript before continuing with the rest of the post, because it is a useful perspective to understand literal types.


Monday, January 18, 2021

Union and Intersection Types in TypeScript

This blog post will look at Union and Intersection types in TypeScript. It is part of the Introduction to Advance Types in TypeScript series.

Union and Intersection types are useful features of TypeScript. But they can come across as a bit strange, especially to developers coming from more traditional languages like Java, C#, etc. Hence in this post, I will first start with a background section. This will help in developing the fundamental perspective needed to understand and appreciate union and intersection types in TypeScript.  


Wednesday, January 13, 2021

Generic Constraints, Generic Methods, and Generic Factories in TypeScript

In Introduction to Generics in TypeScript the idea of Generics was introduced. It was shown how Generics provide a mechanism for having a balance between writing code that is flexible enough to apply to a broad range of types but not too flexible that type safety is lost. 

This post will be a short one that builds on that and shows a couple of extra things that can be achieved when using Generics in TypeScript. Three things will be shown in this post: Generic Constraints, Generic Methods, and Generic Factories


Monday, January 11, 2021

Introduction to Generics in TypeScript

Generics provides a mechanism for writing code that is flexible enough to apply to a broad range of types but not too flexible that type safety is lost. 

What exactly does the above statement mean?

To demonstrate what it means, we will define a class and a function that makes use of Generics. The generic class will be an implementation of a List, which only allows adding and retrieving an item and the generic function will be the identity function

Both the List data structure and the Identity function are good examples because they are straightforward enough to allow for easy demonstration of the Generics concepts.

Let’s start with List.


Introduction to Advanced Types in TypeScript

This is the start of a series of posts where I take a look at aspects of TypeScript's type system that can be referred to as "Advanced".  See this as an exploration of TypeScript’s type system past Classes and Interfaces.

A good mental model to have when exploring the advanced part of TypeScript type system is to see it as a more sophisticated mechanism for creating types. 

The normal, non-advanced ways of creating types in TypeScript involve using features of the language like type aliasclass and interface

For example these: 

interface IPerson {
  name: string
  age: number
}

type TPerson = {
  name: string
  age: number
}

class CPerson {
  constructor(private name:string, private age: number) {}
  
  getName() {
    return this.name;
  }

  getAge() {
    return this.name;
  }
}

With the advanced type features, types can be constructed directly or indirectly based on other existing types. How exactly this is done, will be the subject of this series of posts.

The posts in the series include:


Sunday, January 10, 2021

How to apply type annotations to functions in TypeScript

This post explores the various ways of ascribing functions with type annotations in TypeScript. To fully appreciate the various ways of ascribing type annotations to functions, we would first take a quick look at the various ways functions can be defined in JavaScript. Once that is done, we then look at how to bring TypeScript's static type annotation into the picture. 

There are mainly two ways of defining functions in JavaScript. Namely: 
  • Function expressions 
  • Function declarations. 
Let’s quickly go over how these two work.