Topic

Cryptography

A collection of 10 issues
Latest — Jul 19, 2023

Symmetric algorithms, forming the backbone of modern cryptography, offer a secure method of encrypting and decrypting data utilizing a single shared key. They have been widely adopted for their unmatched speed and efficiency. Like any other technology, symmetric algorithms come with their own set of benefits and drawbacks. This article seeks to offer a comprehensive review of the pros and cons of symmetric algorithms, providing a deeper understanding of their integral role in data security and the potential challenges they entail.

Pros of symmetric algorithms

Unrivaled efficiency

Symmetric algorithms are best known for their superior efficiency in handling large volumes of data for encryption and decryption. The use of a single key significantly reduces the demand for computational resources, setting symmetric algorithms apart from their asymmetric counterparts. This makes them an excellent fit for applications that demand high-speed data processing, including secure communication channels and real-time data transfers.

Impressive speed

Symmetric algorithms, by virtue of their simplicity, can process data at a much faster rate than asymmetric algorithms. Without the need for complex mathematical operations, such as prime factorization or modular arithmetic, symmetric algorithms can encrypt and decrypt data rapidly, reducing latency. This speed advantage is particularly beneficial for applications requiring swift data encryption, including secure cloud storage and virtual private networks (VPNs).

Key distribution

Symmetric algorithms simplify the key distribution process. Given that both the sender and receiver utilize the same key, they only need to execute a secure key exchange once. This offers increased convenience in scenarios where multiple parties need to communicate securely, such as within large organizations, military operations, or corporate communications.

Computational simplicity

Symmetric algorithms are relatively straightforward to implement due to their computational simplicity. This allows for efficient coding, making them ideally suited for resource-constrained devices that possess limited computational capabilities, such as embedded systems or Internet of Things (IoT) devices. This simplicity also contributes to easier maintenance and debugging, reducing the potential for implementation errors that could compromise security.

Cons of symmetric algorithms

Complex key management

The management and distribution of shared keys are significant challenges inherent to symmetric algorithms. The security of these algorithms is closely tied to the confidentiality of the key. Any unauthorized access or compromise of the key can lead to a total breach of data security. Consequently, robust key management protocols are essential, including secure storage, key rotation, and secure key exchange mechanisms, to mitigate this risk.

Lack of authentication

Symmetric algorithms do not inherently provide authentication mechanisms. The absence of additional measures, such as digital signatures or message authentication codes, can make it challenging to verify the integrity and authenticity of the encrypted data. This opens the door for potential data tampering or unauthorized modifications, posing a considerable security risk.

Scalability

Symmetric algorithms face challenges when it comes to scalability. Since each pair of communicating entities requires a unique shared key, the number of required keys increases exponentially with the number of participants. This can be impractical for large-scale networks or systems that involve numerous users, as managing a vast number of keys becomes complex and resource-intensive.

Lack of perfect forward secrecy

Symmetric algorithms lack perfect forward secrecy, meaning that if the shared key is compromised, all previous and future communications encrypted with that key become vulnerable. This limitation makes symmetric algorithms less suitable for scenarios where long-term confidentiality of data is crucial, such as secure messaging applications.

An in-depth analysis of symmetric algorithms

Symmetric algorithms, including the widely adopted AES, DES, and Blowfish, are favored for their speed and efficiency. However, their robustness is largely dependent on the size of the key and the security of the key during transmission and storage. While larger keys can enhance security, they also increase the computational load. Thus, selecting the appropriate key size is a critical decision that requires a careful balance between security and performance requirements.

One of the standout strengths of symmetric encryption is its application in bulk data encryption. Because of their speed, symmetric algorithms are ideally suited for scenarios where large amounts of data need to be encrypted quickly. However, they may not always be the best solution. In many cases, asymmetric encryption algorithms, despite their higher computational demands, are preferred because of their additional security benefits.

It's also crucial to note that cryptographic needs often go beyond just encryption and decryption. Other security aspects, such as data integrity, authentication, and non-repudiation, are not inherently provided by symmetric algorithms. Therefore, a comprehensive security scheme often uses symmetric algorithms in conjunction with other cryptographic mechanisms, such as hash functions and digital signatures, to provide a full suite of security services.

Final thoughts

Symmetric algorithms occupy a pivotal place in the realm of cryptography. Their efficiency and speed make them an invaluable asset for many applications, especially those involving large-scale data encryption. However, the limitations inherent in symmetric algorithms, including key management complexities, lack of authentication, and absence of perfect forward secrecy, necessitate meticulous implementation and the incorporation of additional security measures. Therefore, the decision to utilize symmetric algorithms should be made based on a thorough understanding of these pros and cons, as well as the specific requirements of the system in question.

Pros and cons of symmetric algorithms: ensuring security and efficiency

Jun 30, 2023 — 4 min read

The intricate dance between spies and encryption has been played out over thousands of years, and its rhythm continues to quicken. As we delve deeper into this dance, we see a confluence of technology, secrecy, and intelligence that has shaped the course of history and continues to impact our world today.

A brief history of encryption

Encryption, in its essence, is about transforming information into a code that is unreadable to anyone except the intended recipient. The Ancient Greeks and Romans were among the first to understand this concept. They used simple substitution ciphers, where each letter in a message would be replaced by another letter. The Caesar Cipher, used by Julius Caesar for secure military communications, is a classic example. This cipher was a simple shift of the alphabet, and while it was easy to break, it underscored the vital principle of encryption: the ability to shield information from prying eyes.

Fast forward to the World Wars, and we see the stakes rising. Encryption technology became more advanced and intertwined with the art of espionage. The Enigma machine, utilized by the Germans during World War II, is a well-known example of this progression. The Enigma was an electromechanical device that used a set of rotating disks to scramble plaintext messages into complex ciphertext. The machine's complexity made it a powerful tool for clandestine communication, and cracking its code was a task that required immense intellectual prowess.

The British cryptanalysts at Bletchley Park, led by Alan Turing, took on this monumental challenge. Their efforts to break the Enigma code were not just a victory for cryptography but also a critical factor that contributed to the Allied victory. It was espionage and counter-espionage at its finest, with encryption at the heart of the battle.

The Cold War saw the battleground shift, but the importance of encryption remained the same.

Cryptic case studies

In the last few years, we've seen several noteworthy instances where spies have used encryption and other covert tactics to achieve their goals. Let's explore five recent cases:

  1. Walter Glenn Primrose and Gwynn Darle Morrison were apprehended for a most unusual crime: the theft of deceased infants' identities. The case took a peculiar twist when a photograph was discovered featuring the duo dressed in what was purportedly KGB uniforms. The objective behind this odd photograph remains shrouded in ambiguity. However, this case casts a spotlight on the extraordinary lengths to which spies will resort to obfuscate their true selves, potentially utilizing encryption as a tool to further conceal their covert activities.
  2. In another instance, the veneer of Russian intelligence's machinations to sway U.S. elections was peeled back with the indictment of Alexandr Viktorovich Ionov. This indictment served as a window into the operational mechanics of the Russian FSB, divulging their deployment of an array of stratagems, including the use of encryption and disinformation campaigns, to sow seeds of chaos within the United States and undermine the foundations of global democracy.
  3. A narrative involving U.S. nuclear engineer Jonathan Toebbe and his spouse, Diana, unfolded as the pair tried to profit from selling purloined U.S. Navy nuclear documents and designs in exchange for cryptocurrency. Their surreptitious operation was derailed by an FBI sting operation, underscoring the pivotal role of counterintelligence mechanisms and encryption in the intricate world of modern espionage.
  4. In 2022, European nations initiated a large-scale crackdown on Russian intelligence operations that resulted in the expulsion of 556 Russian intelligence officers and diplomats. This widespread ejection served to hinder Russia's influence operations on European soil and stifle their capacity to manage and support their spy networks. This incident underscores the concerted global efforts being taken to neutralize encrypted espionage activities.
  5. China remains a prominent figure on the stage of global espionage, relentlessly targeting Western technological knowledge and silencing dissent within the Chinese diaspora. One particularly significant case involved Yanjun Xu, an intelligence officer who set his sights on the U.S. aerospace sector. Xu's subsequent 20-year prison sentence serves as a sobering testament to China's long-haul espionage strategy, the role of encryption in facilitating covert operations, and the international cooperative efforts required to counteract such threats.

Reflecting upon both historical and contemporary instances, one can see the intricate duality that encryption presents in espionage. As a tool, it simultaneously serves as a means for covert agents to veil their communications, maintaining the secrecy that their roles require. Simultaneously, it is the shield that protects sensitive data from falling into the wrong hands, acting as a safeguard against the very spies who would employ it for their own purposes.

As technology surges forward, the tactics and techniques of spies and cryptographers mirror this progression. This perpetual cycle of action and counteraction — the relentless pursuit to devise impenetrable codes on one hand, and the counter-effort to decode them on the other — encapsulates the ongoing relationship between espionage and encryption. This dance, marked by strategic maneuvering, continuous adaptation, and intellectual rigor, escalates in intensity with each passing moment, as each side ceaselessly strives to outsmart the other.

Summing up

In conclusion, the interplay between espionage and encryption is a nuanced ballet of complexity and evolution. Encryption serves dual roles in this dance: as a tool that facilitates the clandestine operations of spies, and as a defense mechanism against such covert activities. As we continue to ride the wave of technological advancement, the ties between espionage and encryption will undoubtedly become more intricate, more convoluted, and more pivotal. Whether the scenario involves state-sponsored cyber-espionage aiming to disrupt nations or individuals attempting to monetize state secrets, encryption remains a critical element in these engagements, forming the core of this ongoing battle.

Spies and encryption: a dance of secrecy and technology

Jan 9, 2023 — 5 min read

Since the time of the Roman Empire, people have been able to use encryption to keep their communications private. When the Roman emperor Gaius Julius Caesar was penning an important message, he would sometimes replace a letter in the source text with another letter that was positioned three characters to the left or right of the original letter in the alphabet. This practice dates back to well before our period. If the communication was intercepted by his adversaries, they would not be able to decipher it since they would think it was written in some other language. This method of concealment was known as the Caesar cipher, and it was categorized alongside the other substitution ciphers. The substitution ciphers' overarching strategy is to change the meaning of a character by using a different character.

However, in encrypted messages, common terms were replaced by a single letter, eliminating the possibility of substitution. In this manner, Mary Stuart, imprisoned in Sheffield Castle, communicated with Anthony Babington about the conspiracy and Elizabeth's death. This is a part of that letter.

Indeed, Elizabeth's counterintelligence department, commanded by Francis Walsingham, intercepted the letter, which was quickly decrypted by Elizabeth's greatest cryptanalyst, Thomas Fellipes. How did he manage it? Through an analysis of frequencies.

All letters appear in the language with varying frequency. As a result, you just need to define the percentage of characters in the text that will be replaced by a certain character, and it will take some time to substitute and test hypotheses. This is called frequency analysis. It only works on somewhat long texts, and the longer the text, the better.

Anthony Babington was hung, drawn and quartered, Mary Stuart was beheaded, and the process of letter replacement was no longer deemed secure. However, an antidote to frequency analysis was discovered immediately. It is sufficient to utilize several encryption methods: encrypt one string with one, and the other with another, and frequency analysis will be rendered ineffective.

Since then, there has been an ongoing race between encryption and cipher cracking.

The cracking of the Enigma cipher machine used by Nazi Germany to safeguard military and political communications is the most notable feat in breaking encryption algorithms. By the standards of the time, it was a superb encryption device, on which the brightest brains in Germany collaborated. But deciphering the encryption required no less of a force: a team of British cryptographers collaborated with the young scientist Alan Turing.

Despite the cloak of secrecy, his name is linked to the selection of the key that could unlock the Enigma. Indeed, the key was a seemingly mundane Hitler greeting, which had to be included at the conclusion of every piece of correspondence. Alan Turing accomplished the impossible by providing his country with a crucial advantage during World War II.

Modern algorithms like AES, Twofish, and Blowfish differ significantly from substitution or the displacement of letters, as well as Enigma ciphers. Furthermore, they have nothing to do with them and are immune to brute-force and frequency analysis attacks. One thing stays constant, however: there are still individuals who wish to hack them and decipher encrypted messages. Nowadays, the availability of such a dependable data protection instrument cannot help but bother those who wish to acquire access to any information of special services.

Methods of attacks on ciphers by intelligence agencies

Today, intelligence agencies use three primary methods to attack ciphers.

Direct key selection to ciphers

Data centers that use brute force to break encrypted data are being created for this purpose. You can crack practically any contemporary encryption by brute force; simply guess the key (which is generally logical: if there is any key, in theory, sooner or later it can be guessed). The only question is how much power you have and how much time you have. For example, whereas a single contemporary computer can check 10,000 keys per second on average, a data center of thousands of machines may match tens of millions of keys per second.

Fortunately, cracking a powerful cipher can take more than a dozen years in a contemporary data center, and it is impossible to envision what has to be done so that a whole data center is engaged in cracking your encrypted data. After all, a single day in a data center costs tens of thousands of dollars. Because of the expense of resources, a basic password selection using a dictionary is generally done.

This was the situation with Daniel Dantas, a Brazilian banker who was detained in Rio de Janeiro in July 2008 on accusations of financial fraud. Five hard discs with encrypted data were discovered during a search of his flat. Local specialists were unable to break them and went to the FBI for assistance. The FBI returned the CDs after a year of futile attempts. The method of picking a password using a dictionary was utilized for hacking. Daniel Dantas devised a strong password that would be immune to dictionary assaults. It is unclear whether this aided him in court, but access to his encrypted data was never acquired. He utilized TrueCrypt, an encryption application, by the way.

Aside from data centers, there is an ongoing development of a quantum computer that has the potential to drastically revolutionize modern cryptography. If cryptographers' forecasts come true, it will be easy to crack any current crypto container very fast following the advent of such a supercomputer. Some scientists believe that such a supercomputer has already been developed and is located someplace in the hidden cellars of the US National Security Agency.

The second attack method is a scientific study of modern encryption algorithms with the aim of breaking them

A lot of money is being invested in this business, and such decisions are truly invaluable for special services and intelligence. Here, researchers compete with intelligence agencies. If researchers break the protocol or discover a weakness early on, the rest of the world is likely to learn about it and switch to more secure methods. If they are discovered by intelligence agencies, they are discreetly utilized to obtain access to encrypted data.

A 768-bit RSA key was regarded as an entirely reliable solution ten years ago, and it was utilized by private users, huge corporations, and governments. However, a consortium of engineers from Japan, Switzerland, the Netherlands, and the United States successfully computed data encrypted using a 768-bit RSA cryptographic key at the end of 2009. The usage of 1024-bit RSA keys was suggested. However, 1024-bit RSA keys are no longer deemed strong enough either.

The third attack method is a collaboration with device, program, and encryption algorithm creators to weaken encryption and add backdoors

It is sufficiently difficult for special services to decrypt a correctly encrypted crypto container, so instead, they try to bargain with firms producing encryption tools so that the latter leaves decryption flaws or degrades the algorithms utilized. The US’ NSA is ahead of the rest of the world in this regard. According to Edward Snowden's allegations, the American creator of cryptographic technology RSA Security was paid $ 10 million by the NSA to build a backdoor into its software. RSA Security provided its clients with the notoriously flawed Dual EC DRBG pseudo-random number generation technique for this money. Because of this flaw, US spy services were able to readily decode communications and information.

We don't know what additional backdoors exist in encryption algorithms today, but we do know that decrypting information is one of intelligence services' top goals. High-level professionals are continually working on it, and governments are pouring money into it. It is well known that the majority of efforts are focused on cracking SSL protocols, 4G security technologies, and VPNs.

The history of encryption. Confrontation of encryption and intelligence agencies.

Nov 10, 2022 — 4 min read

It's possible that you've become familiar with the term "time-based one-time passwords" (TOTP) in relation to "two-factor authentication" (FA) or "multi-factor authentication" (MFA).

However, do you really understand TOTP and how they work?

The Meaning of TOTP

"Time-Based One-Time Passwords” refer to passwords that are only valid for 30-90 seconds after they have been formed with a shared secret value and the current time on the system.

Passwords are almost always composed of six-digit sequences that are changed every thirty seconds. On the other hand, some implementations of TOTP make use of four-digit codes that become invalid after a period of 90 seconds.

An open standard is used in the TOTP algorithm, and this standard is detailed in RFC 6238.

What is a shared secret?

TOTP authentication uses a shared secret in the form of a secret key that is shared between the client and the server.

To the naked eye, the Shared Secret seems to be a string with a representation in Base32 that is similar to the following:

KRUGS4ZANFZSAYJAONUGC4TFMQQHGZLDOJSXIIDFPBQW24DMMU======

Computers are able to comprehend and make sense of information even if it is not legible by humans in the manner in which it is presented.

The client and the server both have a copy of the shared secret safely stored on their respective systems after a single transmission of the secret.

If an adversary is able to discover the value of the shared secret, then they will be able to construct their own unique one-time passcodes that are legitimate. Because of this, every implementation of TOTP needs to pay particular attention to securely storing the shared secret in a safe manner.

What is system time?

There is a clock that is integrated into every computer and mobile phone that measures what is referred to as Unix time.

Unix time is measured in terms of the number of seconds that have passed since January 1, 1970, at 00:00:00 UTC.

Unix time appears to be nothing more than a string of numbers:

1643788666

This small number, however, is excellent for the generation of an OTP since the majority of electrical devices using Unix time clocks are sufficiently synced with one another.

Implementations of the TOTP Authentication Protocol

The use of passwords is not recommended. However, you may increase security by combining a traditional password with a time-sensitive one-time password (TOTP). This combination is known as two-factor authentication or 2FA, and it may be used to authenticate your accounts, virtual private networks (VPNs), and apps securely.

TOTP can be implemented in hardware and software tokens:

•  The TOTP hardware token is a physical keychain that displays the current code on a small screen

•  The TOTP soft token is a mobile application that displays a code on a phone’s screen

It makes no difference whether you use software tokens or hardware tokens. The purpose of using two different forms of authentication is to increase the level of protection afforded to your online accounts. You have access to a one-time password generator that you may use during two-factor authentication to obtain access to your account. This generator is available to you regardless of whether you have a key fob or a smartphone with an authentication app.

How does a time-based one-time password work?

The value of the shared secret is included in the generation of each time-based one-time password (TOTP), which is dependent on the current time.

To produce a one-time password, the TOTP method takes into account both the current Unix time and the shared secret value.

The counter in the HMAC-based one-time password (HOTP) method is swapped out for the value of the current time in the time-based one-time password algorithm, which is a version of the HOTP algorithm.

The one-time password (TOTP) technique is based on a hash function that, given an input of indeterminate length, generates a short character string of fixed length. This explanation avoids getting too bogged down in technical language. If you simply have the result of a hash function, you will not be able to recreate the original parameters that were used to generate it. This is one of the hash function's strengths.

It is essential to keep in mind that TOTP offers a higher level of security than HOTP. Every 30 seconds, a brand new password is produced while using TOTP. When using HOTP, a new password is not created until after the previous one has been entered and used. The fact that the one-time password for HOTP continues to work even after it has been used for authentication leaves hackers with a significant window of opportunity to mount a successful assault.

Authentication using Multiple Factors (MFA)

A user must first register their TOTP token in any multi-factor authentication (MFA) system that supports a time-based one-time password before they can use the device to connect to their account.

Some TOTP soft tokens need the registration of a different OTP generator for each account. This effectively implies that if you add two accounts to your authenticator app, the program will produce two temporary passwords, one for each account, every 30 seconds. A single TOTP soft token (authenticator program) may support an infinite number of one-time password generators. Individual one-time password generators safeguard the security of all other accounts in the case where the security of an account is compromised.

To use 2FA, a secret must be created and shared between the TOTP token and the security system. The security system's secret must then be passed to the token.

How is the shared secret sent to the token?

Typically, the security system creates a QR code and requests that the user scan it using an authenticator app.

A QR code of this type is a visual depiction of a lengthy string of letters. The shared secret is, roughly speaking, part of this lengthy sequence.

The software will string the image and extract the secret when the user scans the QR code using the authenticator app. The authenticator program may now utilize the shared secret to generate one-time passwords.

When registering a TOTP token, the secret is only sent once. Many of the concerns about stealing the private key are alleviated. An adversary can still steal the secret, but they must first physically steal the token.

It works even when you're not connected to the internet!

To use the TOTP technique, you do not need an active internet connection on your smartphone or a physical key.

The TOTP token only needs to obtain the shared secret value once. The security system and the OTP generator may thus produce successive password values without needing to communicate. As a consequence, time-based one-time passwords (TOTP) operate even when the computer is turned off.

All about Time-Based One-Time Passwords (TOTP)

Mar 25, 2022 — 5 min read

If you've heard of ‘SHA’ in various forms but aren't sure what it stands for or why it's essential — you’re in luck! We'll attempt to shed some light on the family of cryptographic hash algorithms today.

But, before we get into SHA, let's go over what a hash function is and how it works. Before you can comprehend what SHA-1 and SHA-2 are, you must first grasp these principles.

Let's get started.

What Is a Hash Function?

A hash function relates to a set of characters (known as a key) of a certain length. The hash value is a representation of the original string of characters, however, it is usually smaller.

Because the shorter hash value is simpler to search for than the lengthier text, hashing is used for indexing and finding things in databases. Encryption employs hashing as well.

SHA-1, SHA-2, SHA-256… What’s this all about?

There are three types of secure hash algorithms: SHA-1, SHA-2, and SHA-256. The initial iteration of the algorithm was SHA-1, which was followed by SHA-2, an updated and better version of the first. The SHA-2 method produces a plethora of bit-length variables, which are referred to as SHA-256. Simply put, if you see “SHA-2,” “SHA-256” or “SHA-256 bit,” those names are referring to the same thing.

The NIST's Formal Acceptance

FIPS 180-4, published by the National Institute of Standards and Technology, officially defines the SHA-256 standard. Moreover, a set of test vectors is included with standardization and formalization to confirm that developers have correctly implemented the method.

Let’s break down the algorithm and how it works:

1. Append padding bits

The first step in our hashing process is to add bits to our original message to make it the same length as the standard length needed for the hash function. To accomplish so, we begin by adding a few details to the message we already have. The amount of bits we add is determined so that the message's length is precisely 64 bits less than a multiple of 512 after these bits are added. This can be expressed mathematically in the following way:

n x 512 = M + P + 64

M is the original message's length.
P stands for padded bits.

2. Append length bits

Now that we've added our padding bits to the original message, we can go ahead and add our length bits, which are equal to 64 bits, to make the whole message an exact multiple of 512.

We know we need to add 64 extra bits, so we'll compute them by multiplying the modulo of the original message (the one without the padding) by 232. We add those lengths to the padded bits in the message and get the complete message block, which must be a multiple of 512.

3. Initialize the buffers

We now have our message block, on which we will begin our calculations in order to determine the final hash. Before we get started, I want to point out that we'll need certain default settings to get started with the steps we'll be taking.

a = 0x6a09e667
b = 0xbb67ae85
c = 0x3c6ef372
d = 0xa54ff53a
e = 0x510e527f
f = 0x9b05688c
g = 0x1f83d9ab
h = 0x5be0cd19

Keep these principles in the back of your mind for now; all will fit together in the following phase. There are a further 64 variables to remember, which will operate as keys and are symbolized by the letter 'k.'

Let's go on to the portion where we calculate the hash using these data.

4. Compression Function

As a result, here is where the majority of the hashing algorithm is found. The whole message block, which is 'n x 512' bits long, is broken into 'n' chunks of 512 bits, each of which is then put through 64 rounds of operations, with the result being provided as input for the next round of operations.

The 64 rounds of operation conducted on a 512-bit message are plainly visible in the figure above. We can see that we send in two inputs: W(i) and K(i). During the first 16 rounds, we further break down the 512-bit message into 16 pieces, each consisting of 32 bits. Indeed, we must compute the value for W(i) at each step.

W(i) = Wⁱ⁻¹⁶ + σ⁰ + Wⁱ⁻⁷ + σ¹
where,
σ⁰ = (Wⁱ⁻¹⁵ ROTR⁷(x)) XOR (Wⁱ⁻¹⁵ ROTR¹⁸(x)) XOR (Wⁱ⁻¹⁵ SHR³(x))
σ¹ = (Wⁱ⁻² ROTR¹⁷(x)) XOR (Wⁱ⁻² ROTR¹⁹(x)) XOR (Wⁱ⁻² SHR¹⁰(x))
ROTRⁿ(x) = Circular right rotation of 'x' by 'n' bits
SHRⁿ(x)  = Circular right shift of 'x' by 'n' bits

5. Output

Every round's output is used as an input for the next round, and so on until just the final bits of the message are left, at which point the result of the last round for the nth portion of the message block will give us the result, i.e. the hash for the whole message. The output has a length of 256 bits.

Conclusion

In a nutshell, the whole principle behind SHA would sound something like this:

We determine the length of the message to be hashed, then add a few bits to it, beginning with '1' and continuing with '0' and then ‘1’ again until the message length is precisely 64 bits less than a multiple of 512. By multiplying the modulo of the original message by 232, we may add the remaining 64 bits. The complete message block may be represented as 'n x 512' bits after the remaining bits are added. Now, we split each of these 512 bits into 16 pieces, each of 32 bits, using the compression function, which consists of 64 rounds of operations. For the first 16 rounds, these 16 sections, each of 32 bits, operate as input, and for the next 48 rounds, we have a technique to compute the W(i). We also include preset buffer settings and 'k' values for each of the 64 rounds. We can now begin computing hashes since we have all of the necessary numbers and formulae. The hashing procedure is then repeated 64 times, with the result of the i round serving as the input for the i+1 round. As a result, the output of the 64th operation of the nth round will be the output, which is the hash of the whole message.

The SHA-256 hashing algorithm is now one of the most extensively used hashing algorithms since it has yet to be cracked and the hashes are generated rapidly when compared to other safe hashes such as the SHA-512. It is well-established, but the industry is working to gradually transition to SHA-512, which is more secure, since experts believe SHA-256 may become susceptible to hacking in the near future.

How SHA-256 works

Feb 10, 2022 — 4 min read

If the concept of ‘quantum cryptography' sounds complicated to you, you're right. That’s why this ‘encryption tutorial for dummies’ shall demystify the concept and provide an explanation in layman’s terms.

Quantum cryptography, which has been around for a few decades, is becoming more and more important to our daily lives because of its ability to protect essential data in a manner that conventional encryption techniques cannot.

What is it?

Cryptography, as we all know, is a technique that aims to encrypt data by scrambling plain text so that only those with the appropriate ‘key’ can read it. By extension, quantum cryptography encrypts data and transmits it in an unhackable manner using the principles of quantum mechanics.

While such a concept seems straightforward, the intricacy resides in the quantum mechanics that underpin quantum cryptography. For example:

  • The particles that make up the cosmos are fundamentally unpredictable, and they may exist in several places or states of existence at the same time;
  • A quantum attribute cannot be measured without causing it to change or be disturbed;
  • Some quantum attributes of a particle can be cloned, but not the whole particle.

How does it work?

Theoretically, quantum cryptography operates by following a model that was first published in 1984.

Assume there are two people called Alice and Bob who want to communicate a message in a safe manner, according to the model of quantum cryptography. Alice sends Bob a key, which serves as the signal for the communication to begin. One of the most important components is a stream of photons that go in just one direction. Each photon corresponds to a single bit of data — either a 0 or a 1 — in the computer's memory. However, in addition to traveling in a straight path, these photons are oscillating, or vibrating, in a certain fashion as they move.

The photons pass via a polarizer before reaching Alice, the sender, who then commences the transmission. When some photons pass through a polarizer with the same vibrations as before, and when others pass through with different vibrations, the filter is said to be ‘polarized’. There are many polarization states to choose from, including vertical (1 bit), horizontal (0 bit), 45 degrees right (1 bit) and 45 degrees left (0 bit). In whatever system she employs, the broadcast has one of two polarizations, each encoding a single bit, which is either 0 or 1.

From the polarizer to the receiver, the photons are now traveling via optical fiber to Bob. Each photon is analyzed using a beam splitter, which determines the polarization of each photon. After receiving the photon key, Bob does not recognize the right polarization of the photons, so he chooses one polarization at random from a pool of available options. Alice now compares the polarizers Bob used to polarize the key and informs Bob of the polarizer she used to deliver each photon to the receiver. Bob checks to see whether he used the right polarizer at this point. The photons that were read with the incorrect splitter are then eliminated, and the sequence that is left is deemed the key sequence.

Let's pretend there is an eavesdropper present, who goes by the name of Eve. Eve seeks to listen in and has the same tools as Bob in order to do so successfully. However, Bob has the benefit of being able to converse with Alice in order to check which polarizer type was used for each photon, but Eve does not. Eve is ultimately responsible for rendering the final key.

Alice and Bob would also be aware if Eve was listening in on their conversation. After Eve observes the flow of photons, the photon locations that Alice and Bob anticipate to see will be altered as a result of her observations.

Well, that’s all pretty mind-blowing, but for us, the general public, the biggest question is…

Is it really used?

Although the model described above has not yet been fully developed, there have been successful implementations of it, including the following:

  • The University of Cambridge and the Toshiba Corporation collaborated to develop a high-bit-rate quantum key distribution system based on the BB84 quantum cryptography protocol;
  • DARPA's Quantum Network, which operated from 2002 to 2007, was a 10-node QKD (Quantum Key Distribution) network constructed by Boston University, Harvard University, and IBM Research. It was operated by the Defense Advanced Research Projects Agency;
  • Quantum Xchange created the first quantum network in the United States, which is comprised of over 1,000 kilometers of optical fiber;
  • The development of commercial QKD systems was also carried out by commercial businesses such as ID Quantique, Toshiba, Quintessence Labs, and MagiQ Technologies Inc.

As you can see, these rare implementations are pretty far from what you’d expect to use every day. But hopefully, that will change in the near future.

The pros and cons of quantum cryptography

As with any developing technology, the state of it now (2022), may be very different to its state in the future. Thus, the following table may change dramatically. We do believe, however, that we’ll see fewer points in the ‘Limitations’ column as the years go on.

The need for unbreakable encryption is right there staring us down. The development of quantum computers is on the horizon, and the security of encrypted data is now in jeopardy due to the threat of quantum computing. We are fortunate in that quantum cryptography, in the form of QKD, provides us with the answer we need to protect our information long into the future — all while adhering to the difficult laws of quantum physics.

What is quantum cryptography?

Jan 12, 2022 — 4 min read

End-to-end encryption has been introduced by many communication providers in recent years, notably WhatsApp and Zoom. Although those companies have tried to explain the concept to their user base several times, we believe they failed. Whilst it's clear that these platforms have increased security, most don’t know how or why. Well, encryption is a rather simple concept to understand: It converts data into an unreadable format. But what exactly does "end-to-end" imply? What are the advantages and disadvantages of this added layer of security? We'll explain this as simply as possible without diving too much into the underlying math and technical terminology.

What is end-to-end encryption?

End-to-end encryption (E2EE) is a state-of-the-art protocol for communication security. Only the sender and the intended recipient(s) have access to the data in an end-to-end encrypted system. The encrypted data on the server is inaccessible to both hackers and undesirable third parties.

End-to-end encryption is best understood when compared to the encryption-in-transit approach, so let’s perform a quick recap. If a service employs encryption-in-transit, it is usually encrypted on your device before being delivered to the server. It’s then decrypted for processing on the server before it’s re-encrypted and routed to its final destination. When the data is in transit, it’s encrypted, but when it’s ‘at rest’, it’s decrypted. This safeguards the data during the most dangerous stage of the journey, transit — when it’s most exposed to hackers, interception, and theft.

End-to-end encryption, on the other hand, is the process of encrypting data on your device and not decrypting it until it reaches its destination. When your message travels through the server, not even the service that is delivering the data can view the content of your message.

In practice, this means that messengers using 'real' end-to-end encryption, like Signal, know only your phone number and the date of your last login – nothing more.

This is important for users that want to be sure their communication is kept secure from prying eyes. There are also some real-life examples that utilize end-to-end encryption for financial transactions and commercial communication.

How does it work?

The generation of a public-private key pair ensures the security of end-to-end encryption. This method, also known as asymmetric cryptography, encrypts and decrypts the message using distinct cryptographic keys. Public keys are widely distributed and are used to encrypt or ‘lock’ messages. Only the owner has access to the private keys, which are needed to unlock or decrypt the communication.

Whenever the user takes part in any end-to-end encrypted communication, the system automatically generates dedicated public and private keys.

If this sounds too complicated, here is a very simple metaphor:

You just bought a new Rolex for your buddy, who lives in Australia. Now, it’s already in a fancy green leather box, so you decide to put the stamp directly on it and send it. There is nothing wrong with that approach as long as you trust that the postal workers won’t steal it.

However, if you decide to put the Rolex box inside another box, hiding the nature of the gift from all interacting parties along the way, then you’ve effectively ensured (for all intents and purposes) that the Rolex is only visible to the intended recipient; when your mate from down under gets a hold of the box, he takes his pair of scissors and ‘decrypts’ the present. Indeed, you’ve ensured ‘end-to-end’ encryption.

You’re already using end-to-end encryption, daily

As we mentioned before, during an E2EE interaction, the server that delivers encrypted data between one "end" and the other "end" is unable to decode and read the data it sends. Even the servers' owners are unable to access the information since it is not saved on the servers themselves, only the "endpoints" (or the devices) of the discussion can decode the data.

If you’re daily using messengers like WhatsApp, iMessage, and Signal (where E2EE is enabled by default) or Telegram, Allo, and Facebook's ‘Secret Conversation’ function (where E2EE can be manually activated) – you’re already using end-to-end encryption.

What's more fascinating is that E2EE communication providers don't require you to trust them. And that’s great!

The fact that their systems can be hacked makes no difference to you because the transported data is encrypted and can only be read by the sender and receiver, which has enraged several organizations. There are known cases when such agencies asked for special ‘backdoors’ that would allow them to decrypt messages.

Why isn’t everything end-to-end encrypted?

End-to-end encryption is theoretically sound, but it lacks flexibility, thus it can't be utilized when the "two ends" that communicate data don't exist, such as with cloud storage.

This is why Zero-Knowledge Encryption was created, a solution that overcomes the problem by hiding the encryption key, even from the storage provider, resulting in an authentication request without the requirement for password exchange.

Moreover, end-to-end encryption does not hide information about the message, such as the date and time it was sent or the people who participated in the conversation. This metadata might provide indications on where the 'end-point' might be – not great if you are the target of a hacker.

The biggest problem, however, is that in reality, we never know whether the communication is end-to-end encrypted. Providers may claim to provide end-to-end encryption when what they truly deliver is encryption-in-transit. The information might be kept on a third-party server that can be accessed by anybody who has access to the server.

Conclusion

While it’s obvious that you shouldn’t be shipping Dave’s Rolex in its fancy green box, the reality is, if you’ve nothing to hide and you’re not transporting something incredibly valuable, encryption-in-transit is up to the job.

End-to-end encryption is a wonderful technology that enables a high level of security when properly implemented. But it doesn't really tackle the main issue – the end-user, still, to this day, needs to trust the system that they’re using to communicate. We hope that the next generation of encryption technologies such as ZKP will be able to change that.

What is End-to-end encryption?

Jan 10, 2022 — 4 min read

In this year of our lord, 2022, the term ‘Zero-Knowledge Encryption’ equates to best-in-class data insurance. We’ve already written an article named “What is Zero-Knowledge Proof?”, so we’re not going to look at definitions here, but rather, we’re going to explore the pros and cons of Zero-Knowledge proof encryption when compared to other technologies.

But for those who don’t want to dive deep into technical details, here’s an explanation of what Zero-Knowledge Encryption means:

It simply implies that no one else (not even the service provider) has access to your password-protected data.

This is important because even if your files are completely encrypted, if the server has access to the keys, a centralized hacker attack can result in a data breach.

In order to gain a better understanding of the factors that led to the development of Zero-Knowledge Encryption, we've decided to present a succinct, yet comprehensive, assessment of the advantages and disadvantages of three existing options:

Encryption-in-transit

Data in-transit, also known as data in motion, is data that is actively flowing from one point to another, such as that over the internet or over a private network. Data protection in transit refers to the security of data while it is being transferred from one network to another or from a local storage device to a cloud storage device. Effective data protection measures for in-transit data are critical because data is often considered less secure while in transit. Think of it like hiring security guards to accompany your cash-in-transit vehicle’s trip to the bank.

This means that, while using this approach, stored docs are 100% decryptable, so vulnerable.

As for our everyday life, the following technologies use the ‘encryption-in-transit’ approach:

Encryption-at-rest

Any data encryption is the process of converting one type of data into another that cannot be decrypted by unauthorized users. For example, you may have saved a copy of your passport. You obviously don't want this data to be easily accessed. If you store encrypted data on your server, it’s effectively "resting" there (which is why it’s called encryption-at-rest). This is usually accomplished by the use of an algorithm that is incomprehensible to a user who does not have access to the encryption key needed to decode it. Only an authorized person will be able to access the file, ensuring that your data is kept safe.

The Advanced Encryption Standard (AES) is often used to encrypt data at rest.

But, in order to access the data, you need a key — and that’s where the potential vulnerability lies.


Encryption-at-rest is like storing your data in a secret vault, encryption-in-transit is like putting it in an armored vehicle with security guards for transport.

End-to-end Encryption

End-to-end encryption is the act of applying encryption to messages on one device so that only the device to which it is sent can decrypt it. The message travels all the way from the sender to the recipient in encrypted form.

In practice, it means that only the communicating users (who have the key) can read the messages.

End-to-end encryption has created an impregnable fortress for communication services (for example, messengers), going beyond the security "façade" of encryption-in-transit and encryption-at-rest solutions.

This is the most common approach when protecting oneself against data breaches nowadays, but it only works from "one end to the other," as the term implies. Even though this all sounds great, end-to-end encryption can only be used for a "communication system" like Whatsapp or Telegram.

While theoretically sound, end-to-end encryption lacks flexibility, so it can’t be used when the "two ends" that share data don't exist, such as for cloud storage.

This is the motivation behind the development of Zero-Knowledge Encryption, a method that solves the problem by hiding the encryption key, even from the storage provider, resulting in an authentication request without the need for password exchange.

Zero-Knowledge Encryption

To log in to an account, you usually have to type in the exact password. In today's hyperconnected world, it's normal practice to tell the server your secret key ahead of time and test whether it matches.

Instead, there is another, more secure way, to manage this delicate process and that’s called Zero-Knowledge Encryption.

Without diving deep, The Zero-Knowledge relies on three main requirements:

  1. Completeness — an honest prover will be able to convince the verifier that he has the password by completing some process in the required way;
  2. Soundness — the verifier will almost certainly discover when the prover is lying;
  3. Zero-knowledge — if the prover has a password, the verifier receives no more information other than the fact that the statement is true.

Essentially, the system will check to see if you can demonstrate your knowledge several times by responding to various conditions. It’s like a brute force attack carried out backwards — you perform the same action many times in order to make sure that the prover isn’t lying.

Instead of concluding, let’s round up the pros and cons of Zero-Knowledge proof encryption when compared to the alternatives:


The con here is a clear example of the exceptional security provided by the Zero-Knowledge Encryption solution, which prevents even system administrators from recovering your password. This is why we, at Passwork, rely on this technology in our products. Ultimately, that’s why you can rely on us too.

Why Zero-Knowledge Encryption is the best

Dec 20, 2021 — 4 min read

It is rare for technologies to be born from ambitious philosophical concepts or mind games. But, when it comes to security and cryptography – everything is a riddle.

One of such riddles is ‘How can you prove that you know a secret without giving it away?’. Or in other words, ‘how can you tell someone you love them without saying that you love them?’.

The Zero-Knowledge Proof technique, as suggested by the name, uses cryptographic algorithms to allow several parties to verify the authenticity of a piece of information without having to share the material that makes it up. But how is it possible to prove something without supporting evidence? In this article, we’ll try our best to break it down for you as easily as possible.

Why?

We’re asking ourselves day after day – why on Earth would people decide to use such a complicated concept. Well, millions of people use the internet every day, accepting cookies and sharing personal information in exchange for access to services and digital products. Users are gradually becoming more vulnerable to security breaches and unauthorized access to their data. Furthermore, individuals frequently have to give up their privacy in return for digital platform services such as suggestions, consultations, tailored support, and so on, all of which wouldn’t be available when browsing privately. Due to all the above mentioned, there is a certain asymmetry regarding access to information – you give your information in exchange for a service.

In 1985, three great minds noticed ‘a great disturbance in the Force’ ahead of their time and released a paper called "The Knowledge Complexity of Interactive Proof-Systems" which introduced the concept of Zero-Knowledge Proof (ZKP) for the first time.

So what is it?

ZKP is a set of tools that allows an item of data to be evaluated without having to reveal the data that supports it. This is made feasible by a set of cryptographic methods that allow a "tester" to mathematically prove to a "verifier" that a computational statement is valid without disclosing any data.

It is possible to establish that particular facts are correct without having to share them with a third party in this way. For example, a user could demonstrate that he is of legal age to access a product or service without having to reveal his exact age. Or, it’s a bit like showing your friend your driving license instead of proving to him that you can drive by road-tripping to Mexico.

This technique is often used in the digital world to authenticate systems without the risk of information being stolen. Indeed, it’s no longer necessary to provide any personal data in order to establish a person's identity.

Sounds great, but how does it work?

The prover and the verifier are the two most important roles in zero-knowledge proofs. The prover must demonstrate that they are aware of the secret whereas the verifier must be able to determine whether or not the prover is lying.

It works because the verifier asks the prover to do actions that can only be done if the prover is certain that he or she is aware of the secret. If the prover is guessing, the verifier's tests will catch him or her out. If the secret is known, the prover will pass the verifier's exam with flying colours every time. It's similar to when a bank or other institution requests letters from a known secret word in order to authenticate your identity. You're not telling the bank how much money you have in your account; you're simply demonstrating that you know.

Wonderful, but how does it REALLY work?

To answer this, let’s take a look at a piece of research by Kamil Kulesza.

Assume that two characters, Alice and Bob, find themselves at the mouth of a cave with two independent entrances leading to two different paths (A and B). A door inside the cave connects both paths, but it can only be unlocked with a secret code. This code belongs to Bob (the 'tester,') and Alice (the 'verifier,') wants to buy it, but first, she wants to make sure Bob isn't lying.

How can Bob demonstrate to Alice that he has the code without divulging its contents? They perform the following to achieve this: Bob enters the cave via one of the entrances at random while Alice waits outside (A or B). Once inside, Alice approaches the front door, summons Bob, and instructs him to use one of the two exits. Bob will always be able to return by the path that Alice used since he knows the secret code.

Bob will always be able to return via the path that Alice directs him to, even if it does not coincide with the one he chose in the first place, because he can unlock the door and depart through the other side with the secret code.

But wait a minute, there is still a 50% chance that both Alice and Bob chose the same path, right? It is correct indeed, however, if this exercise is repeated several times, the likelihood that Bob will escape along the same path chosen by Alice without possessing the code decreases until it is almost impossible. Conclusion? If Bob leaves this path a sufficient number of times, he has unmistakably shown to Alice that his claim of holding the secret code is true. Moreover, there was no need to reveal the actual code in this case.

You can find out more about the Bob and Alice metaphor here.

Got it, so how is it used?

As for right now, ZKP is developing hand in hand with blockchain technology.

Zcash is a crypto platform that uses a unique iteration of zero-knowledge proofs (called zk-SNARKs). It allows native transactions to stay entirely encrypted while still being confirmed under the network's consensus rules. It’s a great example of this technology being used in practice.

Even though zero-knowledge proofs have a lot of potential to change the way today's data systems verify information, the technology is still considered to be in its infancy — primarily because researchers are still figuring out how to best use this concept while identifying any potential flaws. This, however, doesn’t stop us from using this protocol in our products! ;)

For a deeper understanding of the technical aspects and history behind this protocol, we recommend watching this video on YouTube.

What is Zero-knowledge Proof?

Nov 5, 2021 — 5 min read

Cryptography is both beautiful and terrifying. Perhaps a bit like your ex-wife. Despite this, it represents a vital component of day-to-day internet security; without it, our secrets kept in the digital world would be exposed to everyone, even your employer. I doubt you’d want information regarding your sexual preferences to be displayed to the regional sales manager while at an interview with Goldman Sachs, right?

Computers are designed to do exactly what we ask them to do. But sometimes there are certain things that we don’t want them to do, like expose your data through some kind of backdoor. This is where cryptography comes into play. It transforms useful data into something that can’t be understood without the proper credentials.

Let’s take a look at an example. Most internet services need to store their users’ password data on their own servers. But they can’t store the exact values that people input on their devices because, in the event of a data breach, malevolent intruders would effectively gain access to a simple spreadsheet of all usernames and passwords.

This is where ‘Hash’ and ‘Salt’ help us a lot. Throughout this article, we’re going to explain these two important encryption concepts through simple functions in Node.JS.

What is a ‘hash’?

A ‘hash’ literally means something that has been chopped and mixed, and originally was used to describe a kind of food. Now, chopping and mixing are exactly what the hash function does! You start with some data, you pass it through a hash function where it gets whisked and chopped, and then you watch it get transformed into a fixed-length value (which at first sight seems pretty meaningless). The important nuance here is that, contrary to cooking, an input always produces a corresponding output. For the purposes of cryptography, such a hash function should be easily computable and all values should be unique. It should work in a similar way to mashing potatoes – mashing is a one-way process; the raw potato may not be restored once it has been mashed. Indeed, the result of a hash function should be impenetrable to computer-led reverse engineering efforts.

These properties come in handy when you’re looking to store user passwords on a database – you don’t want anyone to know their real values.

Let’s implement a hash in Node.JS!

First, let’s import the createHash function from the built-in ‘crypto’ module:

const { createHash } = require ('crypto');

Next, we ought to define the module that we’re naming as the ‘hash’ (which takes a string as the input, and returns a hash as the output):

function hash(input) {
    return createHash();
}

We also need to specify the hashing algorithm that we want to use. In our case, it will be SHA256. SHA stands for Secure Hash Algorithm and it returns a 256-bit digest (output). It is important to architect your code so it is easy to switch between algorithms because at some point in time they won’t be secure anymore. Remember, cryptography is always evolving.

function hash(input) {
    return createHash('sha256');
}

Once we call our hashing function, we may call ‘update’ with the input value and return the output by calling ‘digest’. We should also specify the format of the output (e.g. hex). In our case, we’ll go with Base64.

function hash(input) {
    return createHash('sha256').update(input).digest('base64');
}

Now that we have our hash function, we can provide some input, and console log the result.

let youShallNotPassPass = 'admin1234';
const hashRes1 = hash(youShallNotPassPass);
console.log(hashRes1)

Here’s our baby hash:
rJaJ4ickJwheNbnT4+I+2IyzQ0gotDuG/AWWytTG4nA=

So, how can we use this long, convoluted string of numbers, letters, and symbols? Well, now it’s easy to compare two values while operating with only hashes.

let youShallNotPassPass = 'admin1234';
const hashRes1 = hash(youShallNotPassPass);
const hashRes2 = hash(youShallNotPassPass);
const isThereMatch = hashRes1 === hashRes2;
console.log(isThereMatch ? 'hashes match' : 'hashes do not match’)

As long as hash values are unique object representations, they can be useful for object identification. For example, they might be used to iterate through objects in an array or find a specific one in the database.

But we have a problem. Hash functions are very predictable. On top of that, people don’t use strong passwords that often, so the hacker may just compare the hashes on a database with a precomputed spreadsheet of the most common passwords. If the values match –  the password is compromised.

Because of this, it’s insufficient to just use a hash function to store unique ids on a password database.

And that’s where our second topic makes an entrance – Salt.

‘Salt’ is a bit like the mineral salt that you would add to a batch of mashed potatoes – the taste will definitely depend on the amount and type of salt used. This is exactly what salt in cryptography is – random data that is used as an additional input to a hash function. Its use makes it much harder to guess what exact data stands behind a certain hash.

So, let’s salt our hash function!

First, we ought to import ‘Scrypt' and ‘RandomBytes’ from the ‘crypto’ module:

const { scryptSync, randomBytes } = require('crypto');

Next, let’s implement signup and login functions that take ‘nickname’ and ‘password’ as their inputs:

function signup(nickname, password) { }
function login(nickname, password) { }

When the user signs up, we will generate a salt, which is a random Base64 string:

const salt = randomBytes(16).toString('base64');

And now, we hash the password with a 'pinch' of salt and a key length, which is usually 64:

const hashedPassword = scryptSync(password, salt, 64).toString('base64');

We use ‘Scrypt’ because it’s designed to be expensive computationally and memory-wise in order to make brute-force attacks unrewarding. It’s also used as proof of work in cryptocurrency mining.

Now that we have hashed the password, we need to store the accompanying salt in our database. We can do this by appending it to the hashed password with a semicolon as a separator:

const user = { nickname, password: salt + ':' + hashedPassword}

Here’s our final signup function:

function signup(nickname, password) {
    const salt = randomBytes(16).toString('base64');
    const hashedPassword = scryptSync(password, salt, 64).toString('base64');
    const user = { nickname, password: salt + ':' + hashedPassword};
    users.push(user);
    return user;
}

Now let’s create our login function. When the user wants to log in, we can grab the salt from our database to recreate the original hash:

const user = users.find(v => v.nickname === nickname);
const [salt, key] = user.password.split(':');
const hash = scryptSync(password, salt, 64);

After that, we simply check whether the result matches the hash in our database. If it does, the login is successful:

const match = hash === key;
return match;

Here is the complete login function:

function login(nickname, password) {
    const user = users.find(v => v.nickname === nickname);
    const [salt, key] = user.password.split(':');
    const hash = scryptSync(password, salt, 64).toString('base64');
    const match = hash === key;
    return match;
}

Let’s do some testing:

//We register the user:
const user = signup('Amy', '1234');

//We try to login with the wrong pass:
let isSuccess = login('Amy', '12345');
console.log(isSuccess ? 'Login success' : 'Wrong password!')

//Wrong password!
//We try to login with the correct pass:
isSuccess = login('Amy', '1234')
console.log(isSuccess ? 'Login success' : 'Wrong password!')

//Login success

Our example, hopefully, has provided you with a very simplified explanation of the signup and login process. It’s important to note that our code is not protected against timing attacks and it doesn’t use PKI infrastructure to check hashes, so there are plenty of vulnerabilities for hackers to exploit.

Cryptography itself can be described as the constant war between hackers and cryptographic engineers. Or, that familiar legal battle with your ex-wife over her maintenance payments. After all, what works today may not work tomorrow. A proof of MD5 hash algorithm vulnerability is a very good example.

So if your task is to ensure your users’ data privacy, be ready to constantly update your functions to counteract the recent ‘breakthroughs’.

What is password hashing and salting?