Cryptology Fundamentals
Cryptology Fundamentals
Cryptology Fundamentals
Cryptology Fundamentals
Cryptology Fundamentals
Part 1
Cryptology Fundamentals:#1 Introduction
Hello, in this first article of the cryptology basics series, I will talk about what cryptology is, traditional encryption techniques and how to create a strong password.
Cryptology Overview
In this type of science, called encryption science, things that are intended to be kept secret are encrypted using different techniques and methods within a system. At the same time, the science of cryptology also works to prevent encrypted messages from being deciphered by unwanted people.

Cryptology is the science of passwords. Cryptography deals with information security, Cryptoanalysis is the exact opposite of cryptography, in other words, breaking secure information. Cryptoanalysts generally work based on decryption. Cryptology is a mathematics science and is generally based on number theory.
Cryptography is the science of secret writing for the purpose of concealing the meaning of a message.
Cryptanalysis is the science of breaking and deciphering crypto systems.
Historical Development
The first cryptologist was an Egyptian scribe who lived 4000 years ago. He created hieroglyphs in an encrypted way while telling the story of his master's life, and some of the hieroglyphs had never been used before.
Although cryptography began this way, it developed almost nothing for the first 3000 years of its life. It was used in the most basic way in different parts of the world, but with the collapse of civilizations, the next steps could not be taken.
In China, the leading civilization of the period, cryptography could not be developed at all because it was very difficult to even write without encryption.
Later (5th â€" 6th century BC), cryptography entered the military field due to the need for secrecy in military intelligence. The first cryptographers in the military field were the Spartans.
In the 9th century, Kindî was the first person to discover frequency analysis by developing the single-alphabet substitution encryption method applied in the science of cryptology. Kindi was the first person to discover frequency analysis by developing the single-alphabet substitution encryption method discovered and applied by Julius Caesar (50 BC) in the field of cryptology.
Traditional Encryption Techniques
Historically, many basic encryption algorithms have been developed and used. Nowadays, with the developing computer technology, it has become very easy to crack these passwords. Now let's talk in detail about these encryption techniques and their weaknesses.
Substitution Password
One of the simplest methods for encrypting a text, the substitution cipher has been used many times throughout history and is a good example of basic cryptography.
The idea is very simple, we replace each letter of the alphabet with another. For example;
A â†' k
B â†' d
C â†' w
In this example, ABBA will be encrypted as kddk.
Let's assume that we choose completely randomly the substitution table in which we determine which letter corresponds to which letter. The substitution table becomes the key to this encryption system. As always in symmetric cryptography, the key must be kept secret, that is, distributed securely between A and B. To get detailed information about Symmetric-Asymmetric cryptography, you can look at our previous article.
 As you can imagine, this password is quite easy to crack. At this point, we can benefit from classical cryptanalysis techniques.
First Attack: Brute Force or Comprehensive Key Search
Brute force attacks are based on a simple concept: The attacker has the ciphertext and a short piece of plaintext (e.g. the header of the ciphertext). In this case, it decrypts the ciphertext by trying all possible keys. If the resulting plaintext matches the short piece of plaintext, it has found the correct key. In practice, a brute force attack can be more complex because wrong keys can yield false, positive results.
It is important to note that a brute force attack against symmetric passwords is always possible in principle. Whether it is applicable in practice depends on the number of possible keys that exist for a given cipher. If it takes too much time to test all the keys, i.e. several decades, the password is safe from a brute force attack.
Find the key space of the substitution cipher.Let's break it down: When choosing the letter that will replace the first letter A, we choose a random letter from the 26 letters of the alphabet (we chose k in the example above). The equivalent of the next alphabet letter B is chosen randomly from the remaining 25 letters, etc. Therefore, the key space of the substitution cipher = 26 · 25 · ….. · 3 · 2 · 1 = 26! It is possible.
Even with hundreds of thousands of high-power computers, such a search would take several decades. Therefore, we can consider the substitution password to be secure. However, this is wrong because there is another, stronger attack.
Second Attack: Letter Frequency Analysis
Frequency Analysis was proposed by Al-Kindi in the 9th century. It is based on repetitions in the language.
For any language, the frequency of use of letters in that language is calculated. The table containing the frequency of use of letters in the English language is given below.

As can be seen from the table, the most frequently used letter in the English language is the letter 'E', and the second most frequently used letter is the letter 'T'. If the ciphertext is long, the most visible letter most likely corresponds to E in the plaintext, the second most visible letter most likely corresponds to T, and so on.
The substitution cipher can be easily cracked by such an analytical attack. The biggest weakness of the password is that every character of the plaintext is replaced with the same character every time.
Caesar Code
The Caesar cipher, also known as the shift cipher, is actually a special case of the substitution cipher. The shift cipher itself is extremely simple: We shift each letter of the plaintext by a fixed number of positions in the alphabet. For example, if we shift 3 positions, d instead of A, e instead of B, etc. would come. The only problem arises towards the end of the alphabet: what should we do with X, Y, Z? In this case, we go back to the beginning. In this case, X->a is replaced by Y->b and Z->c.
 Historically, Julius Caesar used this cipher with a three-position shift. This is where the name Caesar cipher comes from.
 For the mathematical expression of the cipher, the letters of the alphabet are numerically encoded as shown in the table below.

Let the key be k = 17 and the plaintext is:
Let ATTACK = x1,x2,…,x6 = 0,19,19,0,2,10.s
Ciphertext is calculated as follows:
y1,y2,…,y6 = 17,10,10,17,19,1 = rkkrtb
Like the substitution password, the shift password is not secure at all. Likewise, we have two ways to crack this password:
 1. Since the key space consists of 26 keys, we can crack the password of a given ciphertext by brute force by trying to decrypt it with all 26 possible keys. If the resulting plaintext is readable, we have found the key.
 2. Frequency analysis can be used as in the substitution cipher.
Vigenere Cipher
Vigenere encryption, a simple form of multi-alphabet encryption, is an improvement of the Caesar encryption algorithm based on single-alphabet shift and substitution encryption methods. While Caesar cipher uses only one alphabet for shift and substitution operations, Vigenere cipher uses more than one alphabet. Thus, different letters emerge as a result of encrypting the same letters in the message to be encrypted.
In the encryption method, first the key to be used during the encryption process is selected. The first letter of the message to be encrypted is shifted in proportion to the order of the first letter of the key value in the alphabet and the encrypted letter is obtained. According to the order of each letter in the key value, each letter in the message to be encrypted is encrypted with a different alphabet and the encryption process is completed.
Playfair Password
Proposed by Charles Wheatstone in 1854, Lord Playfair encouraged its use. It is aimed to create a stronger encryption by using more than one letter change.
A 5×5 table containing the key and the rest of the alphabet is used in encryption. Knowing the key and 4 simple rules is enough to use the system.
Rules:
1- If two letters are the same or there is only one letter left, an "X" letter is added after the first letter.
2- If two letters are on the same line, each letter is replaced with the letter to its right. (if a letter is at the end of a line, it is replaced with the letter at the beginning of the line)
3-If two letters are in the same column, each letter is replaced with the letter below it (if a letter is at the end of the column, it is replaced with the letter at the beginning of the column).
4-If they are not in the same column or row as the letter, the letters are considered as two corners of a rectangle and the letters are placed in the letter in the opposite corner.is replaced with . Let's explain with an example.
our message: cryptology
our password: keyword
In this case, the table will be as shown in the figure. The key is written first. The same letters are used once. The rest of the 5×5 grid is filled with the remaining letters. To reduce the number to 25 letters, the letter I and J are placed in the same box.

plaintext: for kr ip to lo ji
ciphertext: becomes rf hq kz sc jx
Binary letter exchange systems such as Plafair are not robust to two-letter frequency analysis. It is possible to crack short length letter changes with computers.
To crack the code, the frequency of occurrence of binary letter groups in the language is calculated and the message is then tried to be deciphered. This process may seem intimidating at first, but it is not difficult at all for a computer. A powerful computer system is capable of performing frequency analysis up to 8-letter
Affine Password
Affine encryption is a variant of mono-alphabetic substitution encryption methods. In the method, first a numerical value is assigned to each letter of the alphabet to be used, and these values ​​are kept in a table. This table must be present on both sides who want to communicate mutually.
For each character of the clear message to be encrypted, the number value corresponding to the character is sent as input to a simple mathematical function. This number value produced as output from the function, whatever character it represents in the table, forms the structure of the encrypted message.
Vernam Cipher
Although this method, which we can also call unbreakable encryption, is very reliable, it is quite difficult to implement in practice. In this method, a long string of random characters/bits is generated to be used one time. The plain text is XORed with a one-time pad to obtain the cipher text. XORing the ciphertext with the one-time pad returns the plaintext.

As its name suggests, also known as one-time pad, it should be disposable and completely randomly produced. .Reusing the same key causes weakness in encryption and allows it to be broken.
This encryption technique provides perfect confidentiality because the ciphertext does not contain any information about the plaintext. Frequency analysis cannot be used in this technique. It is also possible to use a version that works on letters or characters instead of bits.
In addition, the fact that the key is very long (the same length as the message) and difficult to distribute makes it difficult to use this cipher in practice.
Strong Password
The characteristics of a strong password are that it is both long and diverse. A simple password combination like "1234" can be easily guessed. Even if it is unpredictable, an internet hacker who attacks with the help of a program can easily obtain your password after a few hours of scanning (sometimes shorter). The diversity in our password, the length of our password and the inclusion of different characters in our password make it difficult and sometimes impossible to crack our password with methods such as brute force.
You can create a strong password yourself or get help from a tool: https://passwordsgenerator.net/
For a strong password:
- Aim for maximum length
- Do not create your password with only numbers or letters
- Include extra characters in your password
Strong password examples
- Tu\9a;gMD
*hb!(Bz8XE
*5}JBqseLL - `zhx!8BBF
*u$7sSsX3#
Of course, it can be difficult to remember such passwords. You can use password manager software for this.
In this article, I explained the subject of cryptology. In my next article, I will talk about cryptography and cryptanalysis. You can find the list of the series on my profile.
Part 2
Cryptology Fundamentals:#3 Cryptanalysis
Hello, in this article of the cryptology basics series, I will talk about what cryptanalysis is, password cracking techniques and social engineering methods.
Cryptanalysis Overview
Cryptanalysis is the science of breaking and deciphering crypto systems. It is the branch of cryptology that investigates the decryption of encrypted texts. Cryptanalysis is used to find unknown keys.

Cryptanalysis; We can divide Application Attacks into three areas: classical cryptanalysis and social engineering. Now let's look at these areas and the methods used.
Application Attacks
Cryptanalysis methods that attempt to obtain the secret key through reverse engineering or password attacks are types of attacks.
Brute-Force Attacks
This type of password attack uses trial and error methods to guess the target user's password information. The attacker tries as many permutations as possible to correctly guess the user's password. Although it is a relatively old method that requires a lot of patience and time, a brute force attack is still one of the most used methods because it is automatic and straightforward.

There are several types of brute force attacks:
1. Simple brute force attacks: Uses data about a user to guess the most likely password. This technique is used for simple passwords, such as those containing a combination of pet name-year and birth.
2. Credential stuffing: Involves the use of previously compromised login combinations maliciously obtained from vulnerable websites. These types of attacks take advantage of target users' tendency to reuse username-password combinations across multiple services.
3. Reverse brute force attacks: It starts with a known password and then looks for usernames that match that password. Since threat actors often have access to multiple databases of leaked credentials, it is easy to identify common passwords within a given group of users.
Dictionary Attacks
This attack method uses a predefined list of words that are likely to be used as passwords by a particular target network.
The predefined list is created from a website user's behavioral patterns and passwords obtained from previous data breaches. Lists common password combinations by case;
- By changing
- By adding numeric suffixes and prefixes
- Using common expressions
is created. These lists are passed to tools that attempt to authenticate against a list of known usernames.
Here are the tools that can be used to create a password list.
Password Spraying Attacks
In this attack, the hacker attempts to authenticate using the same password across several accounts before switching to another password. Since most website users set simple passwords, password spraying is the most effective technique.
Attackers often use the password spraying attack on websites where administrators set a standard default password for new users and unregistered accounts.
Keylogging
When conducting a Keylogging attack, the attacker installs keyboard monitoring software on the user's computer to record the keys the user secretly types. A keylogger records all the information users type into login forms and then sends them to the malicious attacker.
Computer Forensics
From the memory, disk or processor of a system to which we have physical access; It involves obtaining the secret key using various forensic methods such as string analysis and signal measurement. In cases where I do not have physical access, such as a remote server, we do not need to worry about this attack.
Application Attacks Tools
- CrackStation
- John the Ripper
- Hashcat
- Medusa
- Hydra
- Brutus
- RainbowCrack
- L0phtCrack
- OphCrack
Classical Cryptanalysis
Classical cryptanalysis is the science of recovering the plaintext from its ciphertext or, alternatively, finding the key from its ciphertext. It uses mathematical analysis that takes advantage of the internal structure of the encryption method.
Encryption Decryption
An encryption process consists of 3 elements. These are: clear text, encrypted text and key. If we have any two of these elements, we can easily find the third. However, the main function of cryptanalysis is the ability to find others when only the ciphertext is available. It uses various mathematical methods for this.
These methods are:
- Known Plaintext Analysis (KPA): In this type of attack, some plaintext-ciphertext pairs are already known. The attacker maps them to find the encryption key. This attack is easier to use because a lot of information is already available.
- Chosen Plaintext Analysis (CPA): In this type of attack, the attacker selects random plaintexts and retrieves the corresponding ciphertexts and tries to find the encryption key. Like KPA, it is very simple to implement, but its success rate is quite low.
- Ciphertext Analysis Only (COA): In this type of attack, only some ciphertexts are known and the attacker tries to find the corresponding encryption key and plaintext. It is the most difficult to implement, but the most likely attack since only ciphertext is required.
- Adaptive Selected Plaintext Analysis (ACPA): This attack is similar to CPA. Here the attacker, after having the ciphertexts for some texts, requests the ciphertexts of additional plaintexts.
- Birthday attack: This attack exploits the possibility of two or more people in a group of people sharing the same birthday. In cryptography, this attack is used to find collisions in a hash function.
- Differential cryptanalysis: This type of attack involves comparing pairs of plaintexts and their corresponding ciphertexts to find patterns in the encryption algorithm. It can be effective against block ciphers with certain properties.
- Integral cryptanalysis: It is a method used on block cipher methods based on Replacement-Scrambling functions.
Social Engineering
No matter how strong the crypto system we have established, risks arising from human factors should not be ignored. Bribery, blackmail, deception or classic espionage can be used to obtain a secret key. For example, holding a gun to a person's head and forcing them to tell the password can be quite successful. Another less violent attack is social engineering techniques such as calling the people we want to attack and saying, "We're calling from your company's IT department. We need your password for important software updates." It is surprising that there are no small number of people who are naive enough to actually give their passwords in such cases.
The attacker is always looking for the weakest link in your crypto system. For this, we need to choose strong algorithms and ensure that social engineering and application attacks are impractical. Both application attacks and social engineering attacks can be quite powerful in practice.
Phishing Attacks
It involves a social engineering technique in which the attacker disguises himself as a trusted site by sending a malicious link to the victim. Once the victim assumes they are authenticating with a legitimate web server, they click on that link, providing the attacker with their account information. In this way, the attacker obtains the account information of the target user, and the victim is phished.
Aside from identity theft, phishing attacks enable an attacker to obtain a user's permissions, allowing them to compromise deeper components of the system before the attack is detected. In phishing attacks, attackers often use multiple methods to trick the user into clicking the malicious link:
- DNS cache poisoning: Attackers exploit the application's DNS server to redirect user requests to a malicious site with a similar-sounding domain name.It exploits the security vulnerabilities in its mind.
- URL hijacking/typo: The attacker creates a real-looking URL with subtle differences from the website they want to impersonate. The attack relies on users making typos, so they land on the malicious page.
- Tabbing: The attacker rewrites unattended browser tabs with malicious sites disguised as legitimate web pages.
- UI fix/iFrame overlay: Using transparent layers, the attacker places a link to the malicious page over a legitimate, clickable button.
- Clone phishing : In this attack, the attacker sends a copy of a legitimate email to malicious sites where the links in the original email are replaced with URLs.
In this article, I talked about cryptanalysis. In my next article, I will talk about cryptography. You can find the list of the series on my profile.
Part 3
Cryptology Fundamentals:#2 Cryptography
Hello, in this article of the cryptology basics series, I will talk about what cryptography is, encryption techniques and cryptographic protocols.
Cryptography Overview
Cryptography is the science of secret writing for the purpose of hiding the meaning of a message. Cryptography is a set of mathematical methods and is intended to provide conditions such as confidentiality, authenticity, authentication, and prevention of false rejection necessary for the security of important information. These methods aim to protect the information â€" and therefore the interests of the sender, receiver, carrier of the information, its subjects, and any other parties â€" from active attacks or passive perceptions that may be encountered during the transmission and storage of information.

Cryptography; We can divide it into 3 areas: symmetric encryption, asymmetric encryption and cryptographic protocols. Now let's look at these areas and the methods used.

Basic Classification Diagram for Cryptographic Algorithms
Symmetric Encryption
Symmetric Encryption** is an encryption technique where both parties use the same encryption and decryption method. There is only one common secret key to be used in this encryption method.
All cryptography from ancient times until 1976 was based solely on symmetric methods, and symmetric ciphers are still widely used. It is especially useful for encryption and integrity control of messages.

Symmetric Encryption
In the computer system; All data such as text, images, music are expressed as 1â€"0s, and each 1â€"0 is called a bit.
Symmetric encryption is divided into block ciphers and stream ciphers. Although stream cipher and block cipher are symmetric encryption techniques, there are some important differences. While block ciphers encrypt fixed-length blocks of bits, stream ciphers combine plaintext bits into a text encryption stream using the XOR operation.

Stream Encryption
In stream encryption, bits are encrypted individually. Each bit is encrypted by XORing the bit coming from the bit stream generator. If the encrypted text is XORed with the cipher stream, the plain text is found and decrypted. For this reason, in the stream encryption technique, there is no need for different algorithms for encryption and decryption operations, these operations are performed with the same algorithm.

XOR operation
The most important point in stream encryption algorithms is the bit stream generator. The bitstream generator creates a bitstream based on the key given to it. The complexity and randomness of this bitstream are of great importance to the reliability of the encryption. At this point, different stream encryption algorithms with different bit stream generators have been developed.
ChaCha20
ChaCha20 algorithm is a stream encryption algorithm. Supports 128 and 256 bits. It has similar features to its predecessor Salsa20. It has a primitive function consisting of 12 or 20 different rounds. It was standardized by the IETF in RFC 7539 and is among the most used algorithms today because it is much more efficient and faster than AES in software applications.
Google has a big part in making ChaCha20 so popular. Until a few years ago, Google used AES-GCM as the symmetric encryption algorithm for Chrome and Android. However, due to the use of ARM-based processors in mobile devices and the lack of AES configurations in these processors as in Intel-based processors, encryption was relatively slow. For this reason, Google was working on a more up-to-date, secure and faster encryption algorithm.

ChaCha20-Poly1305
The jumping off point for ChaCha20 was when the android version of Chrome started using ChaCha20 for encryption and Poly1305 for authentication. The main reason for this was that ChaCha20 achieved three times the performance of slightly older protocols such as AES.
ChaCha20, HTTPS connectionsIt is widely used for SSH connections and managing servers. Even the popular WireGuard VPN protocol uses only ChaCha20 for symmetric data encryption. It is very likely that we will soon see ChaCha20 in IPsec connections as well.
Block Cipher
In block ciphering, an entire block of plaintext bits is encrypted at a time. This requires a key bit block that is the same length as the text bit block. In practice, keys with a block length of 128 bits (16 bytes) or 64 bits (8 bytes) are used. The longer the key length, the more reliable the encryption process.
In block ciphering, encryption and decryption algorithms are different algorithms. The decryption algorithm does the exact opposite of what is done in the encryption algorithm.

Block Cipher
There are two key features that make block cipher algorithms reliable. These are the concepts of confusion and diffusion
**Confusion is an encryption process in which the relationship between the key and the ciphertext is hidden.
**Diffusion is an encryption process in which the effect of one plaintext symbol is spread across many ciphertext symbols in order to hide statistical properties of the plaintext.
Algorithms that perform only propagation or only confusion are not secure. However, strong passwords can be created by using a combination of such processes. Today's block cipher algorithms consist of loops that repeatedly apply these operations to the data.
There are two standardized algorithms widely used in the block cipher technique. These; advanced encryption standard (AES) and data encryption standard (DES) algorithms.
DES
Data Encryption Standard (DES) has been by far the most popular block cipher method for most of the last 30 years. Although DES is not considered secure today because its key length is very short, it is still used in old applications.
DES is an algorithm that encrypts 64-bit blocks with a 56-bit key. This algorithm completes the encryption process in 16 rounds, all performing the same operation. A different subkey is used in each round, and all subkeys are derived from the main key k.

If we look in more detail at the transactions made in each round, we encounter the Feistel structure of the DES algorithm (also known as the Feistel network). If this feistel structure is carefully designed, very strong passwords can be created. In addition to their cryptographic power, an advantage of Feistel networks is that encryption and decryption are almost the same process.

The two fundamental properties of passwords mentioned above, namely hashing and diffusion, are implemented within the f-function. Round is taken as the number of rounds and K1, K2,..KN are taken as subkeys for rounds 1,2,..,n respectively. Then, the Ciphertext blocks are divided into 2 equal parts, L and R, and processed within the function. Then, input R is output as L, input L is output as R, and this process is repeated n times.
The diagram shows both encryption and decryption. It is worth noting that the subkey order is reversed for decryption; This is the only difference between encryption and decryption.
Once the f-function is securely designed, the security of the Feistel cipher increases with the number of keys and block length. The more the number of keys, the more the number of rounds and the more confusion and diffusion we get. Likewise, the longer the block length, the longer the password spreads and the harder it is to crack.
####AES
Advanced Encryption Standard (AES) is the most widely used symmetric cipher today. Software that incorporates AES includes Internet security standard IPsec, TLS, Wi-Fi encryption standard IEEE 802.11i, secure shell network protocol SSH (Secure Shell), Internet telephony Skype, and numerous security products worldwide.
Unlike DES, the AES algorithm does not have a Feistel structure. Feistel networks do not encrypt an entire block per iteration, for example in DES 64/2 = 32 bits are encrypted in one round. AES, on the other hand, encrypts all 128 bits in one round. Therefore, the AES algorithm has a relatively small number of rounds.

AES algorithm
In the image above, the plaintext is x and the ciphertext is y.rak and number of rounds are shown as nr.
AES consists of layers. Each layer processes all 128 bits of the block. There are three different types of layers. These;
Key Addition(AddRoundKey) layer: In the key generator, the 128-bit subkey derived from the main key is XORed with state(x).
SubBytes layer:* Each byte in the state matrix is ​​updated according to a table and with a non-linear transformation.
Diffusion layer: Provides diffusion over text bits. It consists of two sublayers, both of which perform linear operations:
- **Row Shift (ShiftRows) layer, each row is shifted circularly a certain number of times.
- The Column Mixing (MixColumn) layer mixes the four-byte blocks in each column. Last round, the MixColumn transform is not used.
In the AES encryption algorithm, the reverse process is done to decrypt.
Asymmetric Encryption
Asymmetric Encryption is an encryption technique in which a user has a private key and also a public key. Asymmetric algorithms can be used for digital signatures, key generation, and classical data encryption.
It was introduced in 1976 as a completely different type of cipher by Whitfield Diffie, Martin Hellman and Ralph Merkle. Also known as public key encryption.

Asymmetric Encryption
Asymmetric cryptography, also known as public key cryptography, is a fairly new encryption technique. It was introduced in 1976 by Whitfield Diffie, Martin Hellman and Ralph Merkle. In asymmetric encryption, each user has a private key and a public key. The way these keys are used is as follows:
- Message + public key = Encrypted message
- Encrypted message + secret key = Decrypted message
- Message + secret key = Signed message
- Signed message + public key = Authentication
In asymmetric encryption, a message encrypted with a user's public key can only be decrypted with that user's private key. This method is used to send a message to that user. If a user has encrypted the message with his private key, we can decrypt this message with that user's public key. This method is also used in authentication, if the message can be decrypted with that user's public key, his identity is confirmed.
Before moving on to the actual public key encryption algorithms, let's take a look at the mathematical basis of these algorithms.
Public Key Algorithm Families
Integer-Factorization Schemes: Many public-key schemes rely on the fact that it is difficult to factor large integers. The most well-known representative of this family of algorithms is RSA.
Discrete Logarithm Schemes: Based on mathematics known as the discrete logarithm problem in finite fields. Examples of this are Diffie-Hellman key exchange, Elgamal encryption or Digital Signature Algorithm (DSA).
Elliptic Curve (EC) Schemes: A generalization of discrete logarithms are elliptic curve public key schemes. The most popular examples include Elliptic Curve Diffie-Hellman key exchange (ECDH) and Elliptic Curve Digital Signature Algorithm (ECDSA).
The first two families appeared in the mid-1970s. Elliptic curves were introduced in the mid-1980s. There are no known attacks against either scheme if parameters and key lengths are chosen carefully.
RSA
RSA is an encryption technique developed considering the algorithmic difficulty of factoring very large integers. There are many applications where RSA is used, but in practice it is most commonly used for digital signatures, digital certificates, and encryption of small pieces of data. Additionally, RSA is the most widely used asymmetric encryption scheme today.
It should be noted that RSA encryption is not intended to replace symmetric ciphers, as it is several times slower than symmetric ciphers such as AES. This is due to the many calculations involved in performing RSA (or any other public key algorithm). Therefore, the main use of the encryption feature is to securely exchange a key with a symmetric cipher (key transfer). In practice, RSA is often used in conjunction with a symmetric cipher such as AES, where the symmetric cipher does the actual bulk data encryption.
The underlying one-way function of RSA is the integer factorization problem:
 Multiplying two large prime numbers is computationally easy (you can actually do it with paper and pencil).niz), but it is very difficult to factor the resulting product. Euler's theorem and Euler's phi function play important roles in RSA. Now, let's look at how encryption, decryption, and key generation work with RSA.

RSA encryption algorithm
e: encryption exponent, d: decryption exponent, n: length
Modular computations play an important role in RSA encryption and decryption. In practice x, y, n and d are very long numbers (usually 1024 bits).
A distinctive feature of all asymmetric schemes is that there is a setup phase in which the public and private key are calculated. Depending on the public key scheme, key generation can be quite complex. Let's take a look at the steps involved in calculating the public and private key for an RSA encryption system:
- N = p.q
 Two different and large prime numbers are determined, which will form the very large integer that we will denote by N. These numbers are called p and q. - φ(N) = (p-1)(q-1)
 The totient value of number N is calculated. Totient is a function in number theory that indicates the number of numbers that are smaller than an integer and prime to that number. - 1 < e < φ(N) and GCF(e, φ(N)) = 1
 As can be understood from the mathematical expression above, an integer between 1 and the Totient value, which is prime between the Totient value and the Totient value, is selected and named e. Choosing a small number of e to be chosen here provides performance gains when performing operations such as mod and exponentiation, but in some cases it reduces security. - d.e ≡ 1 (mod φ(N)
 The number d that provides equivalence and will be used to create the secret key is found. The process to be done here is to find the inverse of the number e in mod φ(N).
We have obtained all the values necessary to create the public and private key. Provided that the numbers (p,q, φ(N)) used in calculating the number d constituting the private key remain secret, the pair (N,e) is the public key; The (N,d) pair constitutes the secret key.
As you can see, doing these operations can be very long and tiring. For this purpose, some practical methods are used in advanced systems. When designing the RSA scheme, if the e and d values are too large, it may cause slow encryption. On the other hand, if these values are too small, this brings security problems.
Protocols
Cryptographic Protocols are encryption methods created by applying and standardizing cryptographic algorithms. Symmetric and asymmetric algorithms are the building blocks of secure Internet communications. A protocol defines how to use these algorithms.
Digital signature
Digital signature is a legal authentication method used for authentication purposes in the electronic environment. It can be roughly defined as a signature made electronically. As with traditional handwritten signatures, only the person creating the digital message must be able to produce a valid signature. To achieve this with cryptographic primi-262 10 Digital Signatures we need to implement public key cryptography. The basic idea is that the person signing the message uses a private key and the receiving party uses the matching public key. The principle of the digital signature scheme is shown in the figure.

Digital Signature
The key feature of digital signatures is this: Since a valid signature can only be calculated with the signer's private key, a signed message can be unambiguously traced back to its origin. Only the signer has the authority to create a signature in his or her own name. Therefore, we can prove that the signing party actually created the message.
 Each of three popular families of public key algorithms, namely integer factorization, discrete logarithms, and elliptic curves, allow us to create digital signatures.
Summary Functions
Hash functions, also known as hash functions, are an important cryptographic protocol. It is extremely useful and appears in almost all information security applications. For a given message, the message digest or hash value can be viewed as a message fingerprint, that is, a unique representation of a message. Unlike other crypto algorithms, hash functions do not have a key.

Summary Function
Hash functions are mathematical functions that convert a numerical input value into another compressed numerical value.Zion. The input of the hash function is of arbitrary length, but the output is always fixed length. The values ​​returned by a hash function are called message digests or simply hash values. Regardless of the input, all output strings produced by a given hash function are the same length. The length is defined by the type of hashing technology used. The output strings are created from a sequence of characters defined in the hash function.
The uses of hash functions in cryptography are very diverse. Hash functions are an important part of digital signature schemes and message authentication codes. It is also widely used for other cryptographic applications, for example, storing password hashes or key derivation.
Features of hash functions
- One-way: Once a hash value is created, it should be impossible to convert it back to the original data.
- Conflict-free: For a hash function to be conflict-free, the hash value of two different data values ​​must not be the same. In other words, each input sequence must produce a unique output sequence.
- Fast: If a hash function takes too long to calculate hash values, it is of little use. Hash functions must therefore be very fast.
Popular Hash Functions
Message Digest (MD)
The MD family consists of hash functions MD2, MD4, MD5 and MD6. Adopted as Internet Standard RFC 1321. It is a 128-bit hash function. The most popular member of the family is MD5.
MD5 was the most popular and widely used hash function for many years. MD5 digests are widely used in the software world to provide assurance about the integrity of the transferred file. For example, file servers often provide a pre-computed MD5 hash for files, so a user can compare the hash of the downloaded file with the provided value. In 2004, conflicts were found in MD5. An analytics attack using the computer cluster was reported to be successful in just an hour. This collision attack resulted in MD5 being an unreliable algorithm and therefore its use is no longer recommended.
Secure Hash Function (SHA)
The SHA family consists of four SHA algorithms; SHA-0, SHA-1, SHA-2 and SHA-3. Although they are from the same family, they have structurally different algorithms.
The original version is SHA-0, a 160-bit hash function, and was published by the National Institute of Standards and Technology (NIST) in 1993. It had a few weaknesses and did not become very popular. Later in 1995, SHA-1 was designed to fix the alleged weaknesses of SHA-0.
SHA-1 is the most widely used of the existing SHA hash functions. It is used in many commonly used applications and protocols, including Secure Sockets Layer (SSL) security. In 2005, a method was found for SHA-1 to expose conflicts within the practical time frame, making the long-term usability of SHA-1 questionable.
The SHA-2 family has four SHA variants, SHA-224, SHA-256, SHA-384, and SHA-512, depending on the number of bits in the hash values. No successful attack on the SHA-2 hash function has yet been reported. Although SHA-2 is a powerful hash function and is significantly different, its basic design is still similar to that of SHA-1. Therefore, NIST has called for new hash function designs.
In October 2012, NIST selected the Keccak algorithm as the new SHA-3 standard. Keccak offers many advantages to its users, such as efficient performance and strong resistance to attacks.
RIPEMD
RIPEMD is the abbreviation for RACE Integrity Primitives Assessment Message Digest. This set of hash functions was designed by the open research community and is commonly known as a family of European hash functions. The family has 3 members. These; RIPEMD, RIPEMD-128 and RIPEMD-160. 256 and 320 bit versions of this algorithm are also available.
The original RIPEMD (128 bit) was based on the design principles used in MD4 and security issues were found. RIPEMD 128-bit version came as a quick fix to overcome vulnerabilities in the original RIPEMD.
RIPEMD-160 is an improved version and is the most used version in the family. The 256- and 320-bit versions reduce the likelihood of conflicts, but do not have higher security levels compared to RIPEMD-128 and RIPEMD-160, respectively.
####Whirlpool
Whirlpool, 512 bIt is a hash function. It is derived from a modified version of the Advanced Encryption Standard (AES). One of the designers was Vincent Rijmen, co-creator of AES. Three versions of Whirlpool have been released. These; They are WHIRLPOOL-0, WHIRLPOOL-T and WHIRLPOOL.
Key Distribution Protocol
Key da protocol is an encryption protocol in which some secret values are shared among several members of a group. The secret value can also be used, for example, as a secret session key for a secure communication channel between members of the group. Roughly speaking, key distribution protocol deals with creating a shared key between two or more parties. For this, key transport or key agreement methods can be used. A key transport protocol is a technique by which one party securely transfers a secret value to others. In a key agreement protocol, two (or more) parties derive the public key, with all parties contributing the key. Ideally, neither party can control what the final public key will be.

Key Agreement
In cryptography, a key agreement protocol is a protocol in which two or more parties can agree on a key in a way that both affects the outcome. If done properly, this prevents unintended third parties from imposing a choice on contracting parties. In practice, advanced protocols do not reveal to any eavesdropping party what key has been agreed upon.
Key Transport
In many key transport protocols, one party simply generates the key and sends that key to the other party; the other side has no influence on the key.
Using a key agreement protocol avoids some of the key distribution problems associated with such systems. Protocols where both parties influence the final derived key are the only way to implement perfect forward secrecy.

In this article, I talked about cryptography. In my next article, I will talk about cryptanalysis. You can find the list of the series on my profile.
Part 4
Hello, in this article of the cryptology basics series, I will talk about what blockchain is, how it works and where it is used.
What is Blockchain?
Blockchain(blockchain) is an ever-growing list of records blocks, linked and secured using cryptography.
Blockchain technology was invented by Satoshi Nakamoto in 2008. Since it has gained great importance in the last few years, many countries have started working to develop the technology and use it in various fields. Blockchain is highly appreciated by FinTech organizations. Practical applications of Blockchain Technology such as Digital Identities, Bitcoin and Ethereum have made it clear that this technology is here to stay. It is a combination of various technologies, including distributed data storage, encryption algorithms and consensus mechanism. Technology has the ability to revolutionize the working models of departments such as finance, banking and cybersecurity departments.
Some of the advantages of blockchain technology:
- No third party intervention.
- Data cannot be modified or deleted.
- Secure data notebook.
- All blocks in the blockchain are timestamped.
- Transparent transactions.
- Distributed to each node in the blockchain.
- There is no risk of duplication or fraud.
How Does Blockchain Work?
Briefly, the blockchain works like this: Each block typically contains transaction data, the hash of the previous block, and a timestamp. By design, a blockchain is resistant to subsequent modification of records. The ledger used is "an open, distributed ledger that can record transactions between two parties in an efficient, verifiable and persistent manner." For use as a distributed ledger, a blockchain is typically managed by a peer-to-peer network for inter-node communication and validating new blocks, collectively tied to a protocol. If the data in any block is wanted to be changed later, the block containing the data and all subsequent blocks will need to be changed. This requires being elected in the node selection for each block write and approval by the majority of the nodes in the network each time before the next node is written. In addition, since it is clear who modified each block, it is possible to detect possible abuse.
Blockchain works on three leading technologies:
1- Cryptography keys
Cryptography keys are of two types â€" Private key and Public key. Both parties in a network have these two keys, thus helping to create a secure digital identity. These keys help in the successful execution of transactions between these two people. This secure identity is the most important aspect of Blockchain technology, called a 'digital signature' when it comes to cryptocurrency.
2- A peer-to-peer network with a shared ledger
The digital signature is then combined with a peer-to-peer network; A large number of individuals acting as authorities and using the digital signature to reach the consensus of others on transactions, among all other matters.
3- A computing tool for sharing the records and transactions of the network
Once they all consent to an agreement, it is confirmed by a mathematical verification that results in a secure transaction between two parties on a shared network.
Thus, in Blockchain technology, users use cryptography keys to perform different digital transactions over a peer-to-peer network.
Where is Blockchain Used?
Blockchain technology can be integrated into multiple domains. The primary use of blockchains today is cryptocurrencies, most notably bitcoin.
Blockchain technology has great potential to transform business operating models in the long term. Blockchain distributed ledger technology is typically a "low cost" technology based on its potential to create new foundations for global economic and social systems.It is a more fundamental technology than a disruptive technology that attacks a traditional business model with a costly solution and quickly consumes incumbents. The use of blockchains promises to bring significant efficiency to global supply chains, financial transactions, ledgers of assets, and decentralized social networks.
Smart contracts
Blockchain-based smart contracts are contracts that can be executed or enforced in whole or in part without human interaction. One of the main purposes of a smart contract is automatic escrow. The IMF believes that blockchains can reduce moral damages and optimize the use of contracts in general. Its legal status is unclear due to lack of widespread use.
Decentralized networks
- The Backfeed project develops a distributed governance system for blockchain-based applications that enables collaborative creation and distribution of value across networks of simultaneously occurring peers.
- The Alexandria project is a blockchain-based Distributed Library.
- Tezos is a blockchain project that governs itself through the vote of token holders. Bitcoin implements the blockchain as a cryptocurrency and payment system. The Ethereum blockchain added a smart contract system on top of a blockchain. The Tezos blockchain will add an autonomy system â€" a decentralized code Development function on top of both the bitcoin and Ethereum blockchains.
Governments and national currencies
Jose Arrieta, Operations Manager for IT Contract Planning at the U.S. General Services Administration, explained at the ACT-IAC (American Technology Council and Industry Advisory Council) Forum in September 2017 that the organization is using blockchain distributed ledger technology through automation to streamline the FASt Lane process of IT Schedule 70 contracts.
The Commercial Clearance Advisory Committee, a subcommittee of U.S. Customs and Border Protection, is working to find practical ways blockchain can be applied to its missions.
Banks
Large parts of the financial industry are implementing distributed ledgers for use in banking, and according to a September 2016 IBM study, this is happening faster than expected. Banks are interested in this technology because it has the potential to speed up back-office settlement systems.
Other financial companies
Credit and debit payment company MasterCard has added three blockchain-based APIs for programmers to enhance both person-to-person (P2P) and business-to-business (B2B) payment systems.
CLS Group is using blockchain technology to increase the number of foreign exchange deals it can extend.
VISA payment systems, Mastercard, Unionpay and SWIFT have announced their plans and developments to use blockchain technology.
Blockchain Types
Currently, there are three types of blockchain networks:
public blockchains, private blockchains and consortium blockchains.
Public blockchains
A public blockchain has absolutely no access restrictions. Anyone with an Internet connection can make transactions and gain validity (that is, participate in the execution of a consensus protocol). Often, such networks offer economic incentives for people who secure them and use a Proof of Stake or Proof of Work algorithm.
Some of the largest, best-known public blockchains are Bitcoin and Ethereum.
Private blockchains
These types of blockchains can be considered a middle ground for companies interested in blockchain technology in general but not comfortable with a level of control offered by public networks. Typically, they try not to incorporate blockchain into accounting and record-keeping procedures without compromising their autonomy and exposing sensitive data to public internet risk.
Consortium blockchains
A consortium blockchain is often said to be semi-decentralized. He is also on leave; But instead of a single organization controlling it, each company can operate a node in such a network. Administrators of a consortium chain restrict users' read rights as they see fit, allowing only a limited number of trusted nodes to execute a consortium protocol.
In this article, I talked about blockchain. You can find the list of the series on my profile.
Part 5
Cryptology Fundamentals:#5 Applications
Hello, in this last article of the cryptology basics series, I will talk about how cryptographic protocols are implemented. I will use the Java programming language during the implementation phase.
MD5 Application
MD5 is a widely used hash function that can produce a fixed-size output (128 bits) for any input data. In Java, you can calculate the MD5 digest of a string or file using the MessageDigest class, which is part of the Java Security API.
Here is an example of how to calculate the MD5 hash of a string in Java:
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public class MD5Example {
public static void main(String[] args) {
String input = "Hello, world!";
String md5Hash = calculateMD5(input);
System.out.println("MD5 hash of '" + input + "' is: " + md5Hash);
}
public static String calculateMD5(String input) {
try {
MessageDigest md = MessageDigest.getInstance("MD5");
byte[] hash = md.digest(input.getBytes());
StringBuilder sb = new StringBuilder();
for (byte b : hash) {
sb.append(String.format("%02x", b));
}
return sb.toString();
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException("MD5 algorithm not available", e);
}
}
}
In this example, we first import the MessageDigest class and define a calculateMD5 method that takes a string input and returns the MD5 value as a string.
Inside the calculateMD5 method, we first create a new instance of the MessageDigest class by using the getInstance method and giving the "MD5" algorithm as a parameter. Next, we call the hash method on the MessageDigest object and pass the input string as a byte array to calculate the MD5 digest.
Finally, we convert the byte array to a string using a StringBuilder object and the String.format method to format each byte as a two-digit hexadecimal number. We then return the resulting string as an MD5 digest.
SHA-1 Implementation
SHA-1 (Secure HashAlgorithm 1) is a widely used hash function that can create a fixed-size output (160 bits) for any input data. In Java, you can calculate the SHA-1 digest of a string or file using the MessageDigest class, which is part of the Java Security API.
Here is an example of how to calculate the SHA-1 hash of a string in Java:
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public class SHA1Example {
public static void main(String[] args) {
String input = "Hello, world!";
String sha1Hash = calculateSHA1(input);
System.out.println("SHA-1 hash of '" + input + "' is: " + sha1Hash);
}
public static String calculateSHA1(String input) {
try {
MessageDigest md = MessageDigest.getInstance("SHA-1");
byte[] hash = md.digest(input.getBytes());
StringBuilder sb = new StringBuilder();
for (byte b : hash) {
sb.append(String.format("%02x", b));
}
return sb.toString();
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException("SHA-1 algorithm not available", e);
}
}
}
In this example, we first import the MessageDigest class and define a calculateSHA1 method that takes a string input and returns the SHA-1 digest as a string.
Inside the calculateSHA1 method, we first create a new instance of the MessageDigest class by using the getInstance method and giving the "SHA-1" algorithm as a parameter. Next, we call the hash method on the MessageDigest object and pass the input string as a byte array to calculate the SHA-1 hash value.
Finally, we convert the byte array to a string by using a StringBuilder object and the String.format method to format each byte as a two-digit hexadecimal number. We then return the resulting string as a SHA-1 digest.
DES Application
DES (Data Encryption Standard) is a symmetric key encryption system that can be used to encrypt and decrypt data.me algorithm. In Java, you can use the Cipher class from the Java Cryptography Architecture (JCA) to implement DES encryption and decryption.
Here is an example of how to encrypt and decrypt a string using DES in Java:
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
public class DESExample {
public static void main(String[] args) throws Exception {
String originalString = "Hello, world!";
String secretKey = "mysecretkey";
// Encrypt the original string
String encryptedString = encrypt(originalString, secretKey);
System.out.println("Encrypted string: " + encryptedString);
// Decrypt the encrypted string
String decryptedString = decrypt(encryptedString, secretKey);
System.out.println("Decrypted string: " + decryptedString);
}
public static String encrypt(String plainText, String secretKey) throws Exception {
Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
SecretKeySpec secretKeySpec = new SecretKeySpec(secretKey.getBytes(StandardCharsets.UTF_8), "DES");
cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);
byte[] encryptedBytes = cipher.doFinal(plainText.getBytes(StandardCharsets.UTF_8));
return Base64.getEncoder().encodeToString(encryptedBytes);
}
public static String decrypt(String encryptedText, String secretKey) throws Exception {
Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
SecretKeySpec secretKeySpec = new SecretKeySpec(secretKey.getBytes(StandardCharsets.UTF_8), "DES");
cipher.init(Cipher.DECRYPT_MODE, secretKeySpec);
byte[] decodedBytes = Base64.getDecoder().decode(encryptedText);
byte[] decryptedBytes = cipher.doFinal(decodedBytes);
return new String(decryptedBytes, StandardCharsets.UTF_8);
}
}
In this example, we first import the required classes and define the encrypt and decrypt methods, which take a plaintext string and a secret key string as input and return the corresponding encrypted or decrypted string.
Inside each method, we first create a Cipher object using the "DES/ECB/PKCS5Padding" conversion string, which specifies the DES encryption algorithm with Electronic Code Book (ECB) mode and PKCS5 padding.
We then create a SecretKeySpec object using the secret key string and the "DES" algorithm and initialize the cipher object with the secret key using the init method with the appropriate mode (Cipher.ENCRYPT_MODE or Cipher.DECRYPT_MODE).
For encryption, we convert the plaintext string into a byte array and call the doFinal method on the cipher object to encrypt the data. Then, we convert the resulting byte array to a base64-encoded string using the Base64 class and return the encrypted string.
For decryption, we decode the base64-encoded string back into a byte array using the Base64 class, call the doFinal method on the cipher object to decrypt the data, and convert the resulting byte array into a string using the appropriate character set (in this case, StandardCharsets.UTF_8). We then return the decrypted string.
AES Implementation
AES (Advanced Encryption Standard) is a symmetric key encryption algorithm that can be used to encrypt and decrypt data. In Java, you can use the Cipher class from the Java Cryptography Architecture (JCA) to implement AES encryption and decryption.
Here is an example of how to encrypt and decrypt a string using AES in Java:
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
public class AESExample {
public static void main(String[] args) throws Exception {
String originalString = "Hello, world!";
String secretKey = "mysecretkey";
// Encrypt the original string
String encryptedString = encrypt(originalString, secretKey);
System.out.println("Encrypted string: " + encryptedString);
// Decrypt the encrypted string
String decryptedString = decrypt(encryptedString, secretKey);
System.out.println("Decrypted string: " + decryptedString);
}
public static String encrypt(String plainText, String secretKey) throws Exception {
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
SecretKeySpec secretKeySpec = new SecretKeySpec(secretKey.getBytes(StandardCharsets.UTF_8), "AES");
cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);
byte[] encryptedBytes = cipher.doFinal(plainText.getBytes(StandardCharsets.UTF_8));
return Base64.getEncoder().encodeToString(encryptedBytes);
}
public static String decrypt(String encryptedText, String secretKey) throws Exception {
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
SecretKeySpec secretKeySpec = new SecretKeySpec(secretKey.getBytes(StandardCharsets.UTF_8), "AES");
cipher.init(Cipher.DECRYPT_MODE, secretKeySpec);
byte[] decodedBytes = Base64.getDecoder().decode(encryptedText);
byte[] decryptedBytes = cipher.doFinal(decodedBytes);
return new String(decryptedBytes, StandardCharsets.UTF_8);
}
}
In this example, we first import the required classes and define the encrypt and decrypt methods, which take a plaintext string and a secret key string as input and return the corresponding encrypted or decrypted string.
Inside each method, we first create a Cipher object using the "AES/ECB/PKCS5Padding" transform string, which specifies the AES encryption algorithm with Electronic Code Book (ECB) mode and PKCS5 padding.
We then create a SecretKeySpec object using the secret key string and the "AES" algorithm and initialize the cipher object with the secret key using the init method with the appropriate mode (Cipher.ENCRYPT_MODE or Cipher.DECRYPT_MODE).
For encryption, we convert the plaintext string into a byte string and call the doFinal method on the cipher object to encrypt the data. Then, we convert the resulting byte array to a base64-encoded string using the Base64 class and return the encrypted string.
For decryption, we decode the base64-encoded string back into a byte array using the Base64 class, call the doFinal method on the cipher object to decrypt the data, and convert the resulting byte array into a string using the appropriate character set (in this case, StandardCharsets.UTF_8). We then return the decrypted string.
RSA Implementation
RSA (Rivestâ€"Shamirâ€"Adleman) is a public key encryption algorithm that can be used to securely encrypt and decrypt data. In Java, you can use the KeyPairGenerator and Cipher classes from the Java Cryptography Architecture (JCA) to implement RSA encryption and decryption.
Here is an example of how to create an RSA key pair in Java, encrypt a string using the public key, and decrypt the encrypted string:
import javax.crypto.Cipher;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.util.Base64;
public class RSAExample {
public static void main(String[] args) throws Exception {
String originalString = "Hello, world!";
// Generate an RSA key pair
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
keyPairGenerator.initialize(2048);
KeyPair keyPair = keyPairGenerator.generateKeyPair();
// Get the public and private keys from the key pair
byte[] publicKeyBytes = keyPair.getPublic().getEncoded();
byte[] privateKeyBytes = keyPair.getPrivate().getEncoded();
// Encrypt the original string using the public key
byte[] encryptedBytes = encrypt(originalString.getBytes(), publicKeyBytes);
String encryptedString = Base64.getEncoder().encodeToString(encryptedBytes);
System.out.println("Encrypted string: " + encryptedString);
// Decrypt the encrypted string using the private key
byte[] decryptedBytes = decrypt(Base64.getDecoder().decode(encryptedString), privateKeyBytes);
String decryptedString = new String(decryptedBytes);
System.out.println("Decrypted string: " + decryptedString);
}
public static byte[] encrypt(byte[] plainBytes, byte[] publicKeyBytes) throws Exception {
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.ENCRYPT_MODE, KeyFactory.getInstance("RSA").generatePublic(new X509EncodedKeySpec(publicKeyBytes)));
return cipher.doFinal(plainBytes);
}
public static byte[] decrypt(byte[] encryptedBytes, byte[] privateKeyBytes) throws Exception {
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.DECRYPT_MODE, KeyFactory.getInstance("RSA").generatePrivate(new PKCS8EncodedKeySpec(privateKeyBytes)));
return cipher.doFinal(encryptedBytes);
}
}
In this example, we first import the required classes and define the encrypt and decrypt methods, which take a byte array of plaintext or encrypted data and a byte array of public or private key as input and return the corresponding encrypted or decrypted byte array. .
In the main method, we first create an RSA key pair using the KeyPairGenerator class with the "RSA" algorithm and a key size of 2048 bits. We then extract the public and private keys from the key pair as byte arrays using the getEncoded method.
For encryption, we call the encrypt method with the original string converted to a byte array and the public key byte array as input. We create a Cipher object using the "RSA" algorithm in the Encrypt method and initialize it with the public key using the appropriate mode (Cipher.ENCRYPT_MODE) using the init method. Next, we call the doFinal method on the cipher object to encrypt the data and return the resulting byte array.
For decryption, we call the decrypt method with the base64-decrypted encrypted string converted to a byte array and the private key byte array as input. Inside the Decrypt method, we create another Cipher object using the "RSA" algorithm and initialize it with the private key using the appropriate mode and init method.
ECDH Application
ECDH (Elliptic Curve Diffie-Hellman) is a key agreement protocol that allows two parties to establish a shared secret over an unsecured communication channel. In Java, you can use the KeyAgreement and KeyPairGenerator classes from the Java Cryptography Architecture (JCA) to implement ECDH key exchange using elliptic curve cryptography.
Here's an example of creating an ECDH key pair, performing a key exchange with another party, and deriving a shared key using Java:
import javax.crypto.KeyAgreement;
import javax.crypto.SecretKey;
import javax.crypto.spec.ECGenParameterSpec;
import java.security.*;
import java.security.spec.ECParameterSpec;
import java.security.spec.ECPublicKeySpec;
import java.security.spec.InvalidKeySpecException;
public class ECDHExample {
public static void main(String[] args) throws Exception {
// Generate an ECDH key pair
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("EC");
ECGenParameterSpec ecGenParameterSpec = new ECGenParameterSpec("secp256r1");
keyPairGenerator.initialize(ecGenParameterSpec);
KeyPair keyPair = keyPairGenerator.generateKeyPair();
PrivateKey privateKey = keyPair.getPrivate();
PublicKey publicKey = keyPair.getPublic();
// Simulate the other party by generating its own ECDH key pair
KeyPair otherKeyPair = keyPairGenerator.generateKeyPair();
PrivateKey otherPrivateKey = otherKeyPair.getPrivate();
PublicKey otherPublicKey = otherKeyPair.getPublic();
// Perform key exchange with the other party
KeyAgreement keyAgreement = KeyAgreement.getInstance("ECDH");
keyAgreement.init(privateKey);
keyAgreement.doPhase(otherPublicKey, true);
// Derive the shared secret
byte[] sharedSecret = keyAgreement.generateSecret();
// Simulate the other party deriving the shared secret using its private key
KeyFactory keyFactory = KeyFactory.getInstance("EC");
ECParameterSpec ecParameterSpec = ((ECPublicKeySpec) otherPublicKey.getKeySpec(ECPublicKeySpec.class)).getParams();
PublicKey simulatedOtherPublicKey = keyFactory.generatePublic(new ECPublicKeySpec(((java.security.spec.ECPoint) otherPublicKey).getW(), ecParameterSpec));
KeyAgreement simulatedKeyAgreement = KeyAgreement.getInstance("ECDH");
simulatedKeyAgreement.init(otherPrivateKey);simulatedKeyAgreement.doPhase(publicKey, true);
byte[] simulatedSharedSecret = simulatedKeyAgreement.generateSecret();
// Compare the two shared secrets (should be equal)
System.out.println("Shared secret: " + bytesToHex(sharedSecret));
System.out.println("Simulated shared secret: " + bytesToHex(simulatedSharedSecret));
System.out.println("Shared secrets match: " + bytesToHex(sharedSecret).equals(bytesToHex(simulatedSharedSecret)));
}
public static String bytesToHex(byte[] bytes) {
StringBuilder sb = new StringBuilder();
for (byte b : bytes) {
sb.append(String.format("%02X", b));
}
return sb.toString();
}
}
In this example, we first import the required classes and define a bytesToHex method to convert a byte array to a hexadecimal string.
Inside the main method, we first create an ECDH key pair using the KeyPairGenerator class with the "EC" algorithm and the "secp256r1" elliptic curve parameter property. We then extract the private and public keys from the key pair.
We simulate the counterparty by creating its own ECDH key pair using the same curve parameters.
ECDSA Application
ECDSA (Elliptic Curve Digital Signature Algorithm) is a digital signature algorithm based on elliptic curve cryptography. In Java, you can use the Signature and KeyPairGenerator classes from the Java Cryptography Architecture (JCA) to implement ECDSA.
Here's an example of how to create an ECDSA key pair using Java, sign a message with the private key, and verify the signature with the public key:
import java.security.*;
import java.security.spec.ECGenParameterSpec;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
public class ECDSAExample {
public static void main(String[] args) throws Exception {
// Generate an ECDSA key pair
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("EC");
ECGenParameterSpec ecGenParameterSpec = new ECGenParameterSpec("secp256r1");
keyPairGenerator.initialize(ecGenParameterSpec);
KeyPair keyPair = keyPairGenerator.generateKeyPair();
PrivateKey privateKey = keyPair.getPrivate();
PublicKey publicKey = keyPair.getPublic();
// Sign a message with the private key
byte[] message = "Hello, world!".getBytes();
Signature signature = Signature.getInstance("SHA256withECDSA");
signature.initSign(privateKey);
signature.update(message);
byte[] signatureBytes = signature.sign();
// Verify the signature with the public key
Signature verifier = Signature.getInstance("SHA256withECDSA");
verifier.initVerify(publicKey);
verifier.update(message);
boolean signatureValid = verifier.verify(signatureBytes);
System.out.println("Signature valid: " + signatureValid);
}
}
In this example, we first import the necessary classes.
Inside the main method, we generate an ECDSA key pair using the KeyPairGenerator class with the "EC" algorithm and the elliptic curve parameter property "secp256r1". We extract the private and public keys from the key pair.
We then create a message to sign and use the Signature class to sign the message with the private key. To use SHA-256 as the hash function, we specify the "SHA256withECDSA" algorithm.
Next, we create a validator object using the Signature class and initialize it with the public key. We update the validator with the same message and verify the signature using the verification method. We compare the result to true to determine whether the signature is valid.
Note that in a real-world scenario, you will typically transmit the signed message and the public key separately to the verifier to ensure that the signature has not been tampered with during transmission.
In this article, I made cryptology applications with Java. You can access the article series from my profile. Don't forget to like and follow.
Part 2
Cryptology Fundamentals:#3 Cryptanalysis
Hello, in this article of the cryptology basics series, I will talk about what cryptanalysis is, password cracking techniques and social engineering methods.
Cryptanalysis Overview
Cryptanalysis is the science of breaking and deciphering crypto systems. It is the branch of cryptology that investigates the decryption of encrypted texts. Cryptanalysis is used to find unknown keys.

Cryptanalysis; We can divide Application Attacks into three areas: classical cryptanalysis and social engineering. Now let's look at these areas and the methods used.
Application Attacks
Cryptanalysis methods that attempt to obtain the secret key through reverse engineering or password attacks are types of attacks.
Brute-Force Attacks
This type of password attack uses trial and error methods to guess the target user's password information. The attacker tries as many permutations as possible to correctly guess the user's password. Although it is a relatively old method that requires a lot of patience and time, a brute force attack is still one of the most used methods because it is automatic and straightforward.

There are several types of brute force attacks:
1. Simple brute force attacks: Uses data about a user to guess the most likely password. This technique is used for simple passwords, such as those containing a combination of pet name-year and birth.
2. Credential stuffing: Involves the use of previously compromised login combinations maliciously obtained from vulnerable websites. These types of attacks take advantage of target users' tendency to reuse username-password combinations across multiple services.
3. Reverse brute force attacks: It starts with a known password and then looks for usernames that match that password. Since threat actors often have access to multiple databases of leaked credentials, it is easy to identify common passwords within a given group of users.
Dictionary Attacks
This attack method uses a predefined list of words that are likely to be used as passwords by a particular target network.
The predefined list is created from a website user's behavioral patterns and passwords obtained from previous data breaches. Lists common password combinations by case;
- By changing
- By adding numeric suffixes and prefixes
- Using common expressions
is created. These lists are passed to tools that attempt to authenticate against a list of known usernames.
Here are the tools that can be used to create a password list.
Password Spraying Attacks
In this attack, the hacker attempts to authenticate using the same password across several accounts before switching to another password. Since most website users set simple passwords, password spraying is the most effective technique.
Attackers often use the password spraying attack on websites where administrators set a standard default password for new users and unregistered accounts.
Keylogging
When conducting a Keylogging attack, the attacker installs keyboard monitoring software on the user's computer to record the keys the user secretly types. A keylogger records all the information users type into login forms and then sends them to the malicious attacker.
Computer Forensics
From the memory, disk or processor of a system to which we have physical access; It involves obtaining the secret key using various forensic methods such as string analysis and signal measurement. In cases where I do not have physical access, such as a remote server, we do not need to worry about this attack.
Application Attacks Tools
- CrackStation
- John the Ripper
- Hashcat
- Medusa
- Hydra
- Brutus
- RainbowCrack
- L0phtCrack
- OphCrack
Classical Cryptanalysis
Classical cryptanalysis is the science of recovering the plaintext from its ciphertext or, alternatively, finding the key from its ciphertext. It uses mathematical analysis that takes advantage of the internal structure of the encryption method.
Encryption Decryption
An encryption process consists of 3 elements. These are: clear text, encrypted text and key. If we have any two of these elements, we can easily find the third. However, the main function of cryptanalysis is the ability to find others when only the ciphertext is available. It uses various mathematical methods for this.
These methods are:
- Known Plaintext Analysis (KPA): In this type of attack, some plaintext-ciphertext pairs are already known. The attacker maps them to find the encryption key. This attack is easier to use because a lot of information is already available.
- Chosen Plaintext Analysis (CPA): In this type of attack, the attacker selects random plaintexts and retrieves the corresponding ciphertexts and tries to find the encryption key. Like KPA, it is very simple to implement, but its success rate is quite low.
- Ciphertext Analysis Only (COA): In this type of attack, only some ciphertexts are known and the attacker tries to find the corresponding encryption key and plaintext. It is the most difficult to implement, but the most likely attack since only ciphertext is required.
- Adaptive Selected Plaintext Analysis (ACPA): This attack is similar to CPA. Here the attacker, after having the ciphertexts for some texts, requests the ciphertexts of additional plaintexts.
- Birthday attack: This attack exploits the possibility of two or more people in a group of people sharing the same birthday. In cryptography, this attack is used to find collisions in a hash function.
- Differential cryptanalysis: This type of attack involves comparing pairs of plaintexts and their corresponding ciphertexts to find patterns in the encryption algorithm. It can be effective against block ciphers with certain properties.
- Integral cryptanalysis: It is a method used on block cipher methods based on Replacement-Scrambling functions.
Social Engineering
No matter how strong the crypto system we have established, risks arising from human factors should not be ignored. Bribery, blackmail, deception or classic espionage can be used to obtain a secret key. For example, holding a gun to a person's head and forcing them to tell the password can be quite successful. Another less violent attack is social engineering techniques such as calling the people we want to attack and saying, "We're calling from your company's IT department. We need your password for important software updates." It is surprising that there are no small number of people who are naive enough to actually give their passwords in such cases.
The attacker is always looking for the weakest link in your crypto system. For this, we need to choose strong algorithms and ensure that social engineering and application attacks are impractical. Both application attacks and social engineering attacks can be quite powerful in practice.
Phishing Attacks
It involves a social engineering technique in which the attacker disguises himself as a trusted site by sending a malicious link to the victim. Once the victim assumes they are authenticating with a legitimate web server, they click on that link, providing the attacker with their account information. In this way, the attacker obtains the account information of the target user, and the victim is phished.
Aside from identity theft, phishing attacks enable an attacker to obtain a user's permissions, allowing them to compromise deeper components of the system before the attack is detected. In phishing attacks, attackers often use multiple methods to trick the user into clicking the malicious link:
- DNS cache poisoning: Attackers exploit the application's DNS server to redirect user requests to a malicious site with a similar-sounding domain name.It exploits the security vulnerabilities in its mind.
- URL hijacking/typo: The attacker creates a real-looking URL with subtle differences from the website they want to impersonate. The attack relies on users making typos, so they land on the malicious page.
- Tabbing: The attacker rewrites unattended browser tabs with malicious sites disguised as legitimate web pages.
- UI fix/iFrame overlay: Using transparent layers, the attacker places a link to the malicious page over a legitimate, clickable button.
- Clone phishing : In this attack, the attacker sends a copy of a legitimate email to malicious sites where the links in the original email are replaced with URLs.
In this article, I talked about cryptanalysis. In my next article, I will talk about cryptography. You can find the list of the series on my profile.
Part 3
Cryptology Fundamentals:#2 Cryptography
Hello, in this article of the cryptology basics series, I will talk about what cryptography is, encryption techniques and cryptographic protocols.
Cryptography Overview
Cryptography is the science of secret writing for the purpose of hiding the meaning of a message. Cryptography is a set of mathematical methods and is intended to provide conditions such as confidentiality, authenticity, authentication, and prevention of false rejection necessary for the security of important information. These methods aim to protect the information â€" and therefore the interests of the sender, receiver, carrier of the information, its subjects, and any other parties â€" from active attacks or passive perceptions that may be encountered during the transmission and storage of information.

Cryptography; We can divide it into 3 areas: symmetric encryption, asymmetric encryption and cryptographic protocols. Now let's look at these areas and the methods used.

Basic Classification Diagram for Cryptographic Algorithms
Symmetric Encryption
Symmetric Encryption** is an encryption technique where both parties use the same encryption and decryption method. There is only one common secret key to be used in this encryption method.
All cryptography from ancient times until 1976 was based solely on symmetric methods, and symmetric ciphers are still widely used. It is especially useful for encryption and integrity control of messages.

Symmetric Encryption
In the computer system; All data such as text, images, music are expressed as 1â€"0s, and each 1â€"0 is called a bit.
Symmetric encryption is divided into block ciphers and stream ciphers. Although stream cipher and block cipher are symmetric encryption techniques, there are some important differences. While block ciphers encrypt fixed-length blocks of bits, stream ciphers combine plaintext bits into a text encryption stream using the XOR operation.

Stream Encryption
In stream encryption, bits are encrypted individually. Each bit is encrypted by XORing the bit coming from the bit stream generator. If the encrypted text is XORed with the cipher stream, the plain text is found and decrypted. For this reason, in the stream encryption technique, there is no need for different algorithms for encryption and decryption operations, these operations are performed with the same algorithm.

XOR operation
The most important point in stream encryption algorithms is the bit stream generator. The bitstream generator creates a bitstream based on the key given to it. The complexity and randomness of this bitstream are of great importance to the reliability of the encryption. At this point, different stream encryption algorithms with different bit stream generators have been developed.
ChaCha20
ChaCha20 algorithm is a stream encryption algorithm. Supports 128 and 256 bits. It has similar features to its predecessor Salsa20. It has a primitive function consisting of 12 or 20 different rounds. It was standardized by the IETF in RFC 7539 and is among the most used algorithms today because it is much more efficient and faster than AES in software applications.
Google has a big part in making ChaCha20 so popular. Until a few years ago, Google used AES-GCM as the symmetric encryption algorithm for Chrome and Android. However, due to the use of ARM-based processors in mobile devices and the lack of AES configurations in these processors as in Intel-based processors, encryption was relatively slow. For this reason, Google was working on a more up-to-date, secure and faster encryption algorithm.

ChaCha20-Poly1305
The jumping off point for ChaCha20 was when the android version of Chrome started using ChaCha20 for encryption and Poly1305 for authentication. The main reason for this was that ChaCha20 achieved three times the performance of slightly older protocols such as AES.
ChaCha20, HTTPS connectionsIt is widely used for SSH connections and managing servers. Even the popular WireGuard VPN protocol uses only ChaCha20 for symmetric data encryption. It is very likely that we will soon see ChaCha20 in IPsec connections as well.
Block Cipher
In block ciphering, an entire block of plaintext bits is encrypted at a time. This requires a key bit block that is the same length as the text bit block. In practice, keys with a block length of 128 bits (16 bytes) or 64 bits (8 bytes) are used. The longer the key length, the more reliable the encryption process.
In block ciphering, encryption and decryption algorithms are different algorithms. The decryption algorithm does the exact opposite of what is done in the encryption algorithm.

Block Cipher
There are two key features that make block cipher algorithms reliable. These are the concepts of confusion and diffusion
**Confusion is an encryption process in which the relationship between the key and the ciphertext is hidden.
**Diffusion is an encryption process in which the effect of one plaintext symbol is spread across many ciphertext symbols in order to hide statistical properties of the plaintext.
Algorithms that perform only propagation or only confusion are not secure. However, strong passwords can be created by using a combination of such processes. Today's block cipher algorithms consist of loops that repeatedly apply these operations to the data.
There are two standardized algorithms widely used in the block cipher technique. These; advanced encryption standard (AES) and data encryption standard (DES) algorithms.
DES
Data Encryption Standard (DES) has been by far the most popular block cipher method for most of the last 30 years. Although DES is not considered secure today because its key length is very short, it is still used in old applications.
DES is an algorithm that encrypts 64-bit blocks with a 56-bit key. This algorithm completes the encryption process in 16 rounds, all performing the same operation. A different subkey is used in each round, and all subkeys are derived from the main key k.

If we look in more detail at the transactions made in each round, we encounter the Feistel structure of the DES algorithm (also known as the Feistel network). If this feistel structure is carefully designed, very strong passwords can be created. In addition to their cryptographic power, an advantage of Feistel networks is that encryption and decryption are almost the same process.

The two fundamental properties of passwords mentioned above, namely hashing and diffusion, are implemented within the f-function. Round is taken as the number of rounds and K1, K2,..KN are taken as subkeys for rounds 1,2,..,n respectively. Then, the Ciphertext blocks are divided into 2 equal parts, L and R, and processed within the function. Then, input R is output as L, input L is output as R, and this process is repeated n times.
The diagram shows both encryption and decryption. It is worth noting that the subkey order is reversed for decryption; This is the only difference between encryption and decryption.
Once the f-function is securely designed, the security of the Feistel cipher increases with the number of keys and block length. The more the number of keys, the more the number of rounds and the more confusion and diffusion we get. Likewise, the longer the block length, the longer the password spreads and the harder it is to crack.
####AES
Advanced Encryption Standard (AES) is the most widely used symmetric cipher today. Software that incorporates AES includes Internet security standard IPsec, TLS, Wi-Fi encryption standard IEEE 802.11i, secure shell network protocol SSH (Secure Shell), Internet telephony Skype, and numerous security products worldwide.
Unlike DES, the AES algorithm does not have a Feistel structure. Feistel networks do not encrypt an entire block per iteration, for example in DES 64/2 = 32 bits are encrypted in one round. AES, on the other hand, encrypts all 128 bits in one round. Therefore, the AES algorithm has a relatively small number of rounds.

AES algorithm
In the image above, the plaintext is x and the ciphertext is y.rak and number of rounds are shown as nr.
AES consists of layers. Each layer processes all 128 bits of the block. There are three different types of layers. These;
Key Addition(AddRoundKey) layer: In the key generator, the 128-bit subkey derived from the main key is XORed with state(x).
SubBytes layer:* Each byte in the state matrix is ​​updated according to a table and with a non-linear transformation.
Diffusion layer: Provides diffusion over text bits. It consists of two sublayers, both of which perform linear operations:
- **Row Shift (ShiftRows) layer, each row is shifted circularly a certain number of times.
- The Column Mixing (MixColumn) layer mixes the four-byte blocks in each column. Last round, the MixColumn transform is not used.
In the AES encryption algorithm, the reverse process is done to decrypt.
Asymmetric Encryption
Asymmetric Encryption is an encryption technique in which a user has a private key and also a public key. Asymmetric algorithms can be used for digital signatures, key generation, and classical data encryption.
It was introduced in 1976 as a completely different type of cipher by Whitfield Diffie, Martin Hellman and Ralph Merkle. Also known as public key encryption.

Asymmetric Encryption
Asymmetric cryptography, also known as public key cryptography, is a fairly new encryption technique. It was introduced in 1976 by Whitfield Diffie, Martin Hellman and Ralph Merkle. In asymmetric encryption, each user has a private key and a public key. The way these keys are used is as follows:
- Message + public key = Encrypted message
- Encrypted message + secret key = Decrypted message
- Message + secret key = Signed message
- Signed message + public key = Authentication
In asymmetric encryption, a message encrypted with a user's public key can only be decrypted with that user's private key. This method is used to send a message to that user. If a user has encrypted the message with his private key, we can decrypt this message with that user's public key. This method is also used in authentication, if the message can be decrypted with that user's public key, his identity is confirmed.
Before moving on to the actual public key encryption algorithms, let's take a look at the mathematical basis of these algorithms.
Public Key Algorithm Families
Integer-Factorization Schemes: Many public-key schemes rely on the fact that it is difficult to factor large integers. The most well-known representative of this family of algorithms is RSA.
Discrete Logarithm Schemes: Based on mathematics known as the discrete logarithm problem in finite fields. Examples of this are Diffie-Hellman key exchange, Elgamal encryption or Digital Signature Algorithm (DSA).
Elliptic Curve (EC) Schemes: A generalization of discrete logarithms are elliptic curve public key schemes. The most popular examples include Elliptic Curve Diffie-Hellman key exchange (ECDH) and Elliptic Curve Digital Signature Algorithm (ECDSA).
The first two families appeared in the mid-1970s. Elliptic curves were introduced in the mid-1980s. There are no known attacks against either scheme if parameters and key lengths are chosen carefully.
RSA
RSA is an encryption technique developed considering the algorithmic difficulty of factoring very large integers. There are many applications where RSA is used, but in practice it is most commonly used for digital signatures, digital certificates, and encryption of small pieces of data. Additionally, RSA is the most widely used asymmetric encryption scheme today.
It should be noted that RSA encryption is not intended to replace symmetric ciphers, as it is several times slower than symmetric ciphers such as AES. This is due to the many calculations involved in performing RSA (or any other public key algorithm). Therefore, the main use of the encryption feature is to securely exchange a key with a symmetric cipher (key transfer). In practice, RSA is often used in conjunction with a symmetric cipher such as AES, where the symmetric cipher does the actual bulk data encryption.
The underlying one-way function of RSA is the integer factorization problem:
 Multiplying two large prime numbers is computationally easy (you can actually do it with paper and pencil).niz), but it is very difficult to factor the resulting product. Euler's theorem and Euler's phi function play important roles in RSA. Now, let's look at how encryption, decryption, and key generation work with RSA.

RSA encryption algorithm
e: encryption exponent, d: decryption exponent, n: length
Modular computations play an important role in RSA encryption and decryption. In practice x, y, n and d are very long numbers (usually 1024 bits).
A distinctive feature of all asymmetric schemes is that there is a setup phase in which the public and private key are calculated. Depending on the public key scheme, key generation can be quite complex. Let's take a look at the steps involved in calculating the public and private key for an RSA encryption system:
- N = p.q
 Two different and large prime numbers are determined, which will form the very large integer that we will denote by N. These numbers are called p and q. - φ(N) = (p-1)(q-1)
 The totient value of number N is calculated. Totient is a function in number theory that indicates the number of numbers that are smaller than an integer and prime to that number. - 1 < e < φ(N) and GCF(e, φ(N)) = 1
 As can be understood from the mathematical expression above, an integer between 1 and the Totient value, which is prime between the Totient value and the Totient value, is selected and named e. Choosing a small number of e to be chosen here provides performance gains when performing operations such as mod and exponentiation, but in some cases it reduces security. - d.e ≡ 1 (mod φ(N)
 The number d that provides equivalence and will be used to create the secret key is found. The process to be done here is to find the inverse of the number e in mod φ(N).
We have obtained all the values necessary to create the public and private key. Provided that the numbers (p,q, φ(N)) used in calculating the number d constituting the private key remain secret, the pair (N,e) is the public key; The (N,d) pair constitutes the secret key.
As you can see, doing these operations can be very long and tiring. For this purpose, some practical methods are used in advanced systems. When designing the RSA scheme, if the e and d values are too large, it may cause slow encryption. On the other hand, if these values are too small, this brings security problems.
Protocols
Cryptographic Protocols are encryption methods created by applying and standardizing cryptographic algorithms. Symmetric and asymmetric algorithms are the building blocks of secure Internet communications. A protocol defines how to use these algorithms.
Digital signature
Digital signature is a legal authentication method used for authentication purposes in the electronic environment. It can be roughly defined as a signature made electronically. As with traditional handwritten signatures, only the person creating the digital message must be able to produce a valid signature. To achieve this with cryptographic primi-262 10 Digital Signatures we need to implement public key cryptography. The basic idea is that the person signing the message uses a private key and the receiving party uses the matching public key. The principle of the digital signature scheme is shown in the figure.

Digital Signature
The key feature of digital signatures is this: Since a valid signature can only be calculated with the signer's private key, a signed message can be unambiguously traced back to its origin. Only the signer has the authority to create a signature in his or her own name. Therefore, we can prove that the signing party actually created the message.
 Each of three popular families of public key algorithms, namely integer factorization, discrete logarithms, and elliptic curves, allow us to create digital signatures.
Summary Functions
Hash functions, also known as hash functions, are an important cryptographic protocol. It is extremely useful and appears in almost all information security applications. For a given message, the message digest or hash value can be viewed as a message fingerprint, that is, a unique representation of a message. Unlike other crypto algorithms, hash functions do not have a key.

Summary Function
Hash functions are mathematical functions that convert a numerical input value into another compressed numerical value.Zion. The input of the hash function is of arbitrary length, but the output is always fixed length. The values ​​returned by a hash function are called message digests or simply hash values. Regardless of the input, all output strings produced by a given hash function are the same length. The length is defined by the type of hashing technology used. The output strings are created from a sequence of characters defined in the hash function.
The uses of hash functions in cryptography are very diverse. Hash functions are an important part of digital signature schemes and message authentication codes. It is also widely used for other cryptographic applications, for example, storing password hashes or key derivation.
Features of hash functions
- One-way: Once a hash value is created, it should be impossible to convert it back to the original data.
- Conflict-free: For a hash function to be conflict-free, the hash value of two different data values ​​must not be the same. In other words, each input sequence must produce a unique output sequence.
- Fast: If a hash function takes too long to calculate hash values, it is of little use. Hash functions must therefore be very fast.
Popular Hash Functions
Message Digest (MD)
The MD family consists of hash functions MD2, MD4, MD5 and MD6. Adopted as Internet Standard RFC 1321. It is a 128-bit hash function. The most popular member of the family is MD5.
MD5 was the most popular and widely used hash function for many years. MD5 digests are widely used in the software world to provide assurance about the integrity of the transferred file. For example, file servers often provide a pre-computed MD5 hash for files, so a user can compare the hash of the downloaded file with the provided value. In 2004, conflicts were found in MD5. An analytics attack using the computer cluster was reported to be successful in just an hour. This collision attack resulted in MD5 being an unreliable algorithm and therefore its use is no longer recommended.
Secure Hash Function (SHA)
The SHA family consists of four SHA algorithms; SHA-0, SHA-1, SHA-2 and SHA-3. Although they are from the same family, they have structurally different algorithms.
The original version is SHA-0, a 160-bit hash function, and was published by the National Institute of Standards and Technology (NIST) in 1993. It had a few weaknesses and did not become very popular. Later in 1995, SHA-1 was designed to fix the alleged weaknesses of SHA-0.
SHA-1 is the most widely used of the existing SHA hash functions. It is used in many commonly used applications and protocols, including Secure Sockets Layer (SSL) security. In 2005, a method was found for SHA-1 to expose conflicts within the practical time frame, making the long-term usability of SHA-1 questionable.
The SHA-2 family has four SHA variants, SHA-224, SHA-256, SHA-384, and SHA-512, depending on the number of bits in the hash values. No successful attack on the SHA-2 hash function has yet been reported. Although SHA-2 is a powerful hash function and is significantly different, its basic design is still similar to that of SHA-1. Therefore, NIST has called for new hash function designs.
In October 2012, NIST selected the Keccak algorithm as the new SHA-3 standard. Keccak offers many advantages to its users, such as efficient performance and strong resistance to attacks.
RIPEMD
RIPEMD is the abbreviation for RACE Integrity Primitives Assessment Message Digest. This set of hash functions was designed by the open research community and is commonly known as a family of European hash functions. The family has 3 members. These; RIPEMD, RIPEMD-128 and RIPEMD-160. 256 and 320 bit versions of this algorithm are also available.
The original RIPEMD (128 bit) was based on the design principles used in MD4 and security issues were found. RIPEMD 128-bit version came as a quick fix to overcome vulnerabilities in the original RIPEMD.
RIPEMD-160 is an improved version and is the most used version in the family. The 256- and 320-bit versions reduce the likelihood of conflicts, but do not have higher security levels compared to RIPEMD-128 and RIPEMD-160, respectively.
####Whirlpool
Whirlpool, 512 bIt is a hash function. It is derived from a modified version of the Advanced Encryption Standard (AES). One of the designers was Vincent Rijmen, co-creator of AES. Three versions of Whirlpool have been released. These; They are WHIRLPOOL-0, WHIRLPOOL-T and WHIRLPOOL.
Key Distribution Protocol
Key da protocol is an encryption protocol in which some secret values are shared among several members of a group. The secret value can also be used, for example, as a secret session key for a secure communication channel between members of the group. Roughly speaking, key distribution protocol deals with creating a shared key between two or more parties. For this, key transport or key agreement methods can be used. A key transport protocol is a technique by which one party securely transfers a secret value to others. In a key agreement protocol, two (or more) parties derive the public key, with all parties contributing the key. Ideally, neither party can control what the final public key will be.

Key Agreement
In cryptography, a key agreement protocol is a protocol in which two or more parties can agree on a key in a way that both affects the outcome. If done properly, this prevents unintended third parties from imposing a choice on contracting parties. In practice, advanced protocols do not reveal to any eavesdropping party what key has been agreed upon.
Key Transport
In many key transport protocols, one party simply generates the key and sends that key to the other party; the other side has no influence on the key.
Using a key agreement protocol avoids some of the key distribution problems associated with such systems. Protocols where both parties influence the final derived key are the only way to implement perfect forward secrecy.

In this article, I talked about cryptography. In my next article, I will talk about cryptanalysis. You can find the list of the series on my profile.
Part 4
Hello, in this article of the cryptology basics series, I will talk about what blockchain is, how it works and where it is used.
What is Blockchain?
Blockchain(blockchain) is an ever-growing list of records blocks, linked and secured using cryptography.
Blockchain technology was invented by Satoshi Nakamoto in 2008. Since it has gained great importance in the last few years, many countries have started working to develop the technology and use it in various fields. Blockchain is highly appreciated by FinTech organizations. Practical applications of Blockchain Technology such as Digital Identities, Bitcoin and Ethereum have made it clear that this technology is here to stay. It is a combination of various technologies, including distributed data storage, encryption algorithms and consensus mechanism. Technology has the ability to revolutionize the working models of departments such as finance, banking and cybersecurity departments.
Some of the advantages of blockchain technology:
- No third party intervention.
- Data cannot be modified or deleted.
- Secure data notebook.
- All blocks in the blockchain are timestamped.
- Transparent transactions.
- Distributed to each node in the blockchain.
- There is no risk of duplication or fraud.
How Does Blockchain Work?
Briefly, the blockchain works like this: Each block typically contains transaction data, the hash of the previous block, and a timestamp. By design, a blockchain is resistant to subsequent modification of records. The ledger used is "an open, distributed ledger that can record transactions between two parties in an efficient, verifiable and persistent manner." For use as a distributed ledger, a blockchain is typically managed by a peer-to-peer network for inter-node communication and validating new blocks, collectively tied to a protocol. If the data in any block is wanted to be changed later, the block containing the data and all subsequent blocks will need to be changed. This requires being elected in the node selection for each block write and approval by the majority of the nodes in the network each time before the next node is written. In addition, since it is clear who modified each block, it is possible to detect possible abuse.
Blockchain works on three leading technologies:
1- Cryptography keys
Cryptography keys are of two types â€" Private key and Public key. Both parties in a network have these two keys, thus helping to create a secure digital identity. These keys help in the successful execution of transactions between these two people. This secure identity is the most important aspect of Blockchain technology, called a 'digital signature' when it comes to cryptocurrency.
2- A peer-to-peer network with a shared ledger
The digital signature is then combined with a peer-to-peer network; A large number of individuals acting as authorities and using the digital signature to reach the consensus of others on transactions, among all other matters.
3- A computing tool for sharing the records and transactions of the network
Once they all consent to an agreement, it is confirmed by a mathematical verification that results in a secure transaction between two parties on a shared network.
Thus, in Blockchain technology, users use cryptography keys to perform different digital transactions over a peer-to-peer network.
Where is Blockchain Used?
Blockchain technology can be integrated into multiple domains. The primary use of blockchains today is cryptocurrencies, most notably bitcoin.
Blockchain technology has great potential to transform business operating models in the long term. Blockchain distributed ledger technology is typically a "low cost" technology based on its potential to create new foundations for global economic and social systems.It is a more fundamental technology than a disruptive technology that attacks a traditional business model with a costly solution and quickly consumes incumbents. The use of blockchains promises to bring significant efficiency to global supply chains, financial transactions, ledgers of assets, and decentralized social networks.
Smart contracts
Blockchain-based smart contracts are contracts that can be executed or enforced in whole or in part without human interaction. One of the main purposes of a smart contract is automatic escrow. The IMF believes that blockchains can reduce moral damages and optimize the use of contracts in general. Its legal status is unclear due to lack of widespread use.
Decentralized networks
- The Backfeed project develops a distributed governance system for blockchain-based applications that enables collaborative creation and distribution of value across networks of simultaneously occurring peers.
- The Alexandria project is a blockchain-based Distributed Library.
- Tezos is a blockchain project that governs itself through the vote of token holders. Bitcoin implements the blockchain as a cryptocurrency and payment system. The Ethereum blockchain added a smart contract system on top of a blockchain. The Tezos blockchain will add an autonomy system â€" a decentralized code Development function on top of both the bitcoin and Ethereum blockchains.
Governments and national currencies
Jose Arrieta, Operations Manager for IT Contract Planning at the U.S. General Services Administration, explained at the ACT-IAC (American Technology Council and Industry Advisory Council) Forum in September 2017 that the organization is using blockchain distributed ledger technology through automation to streamline the FASt Lane process of IT Schedule 70 contracts.
The Commercial Clearance Advisory Committee, a subcommittee of U.S. Customs and Border Protection, is working to find practical ways blockchain can be applied to its missions.
Banks
Large parts of the financial industry are implementing distributed ledgers for use in banking, and according to a September 2016 IBM study, this is happening faster than expected. Banks are interested in this technology because it has the potential to speed up back-office settlement systems.
Other financial companies
Credit and debit payment company MasterCard has added three blockchain-based APIs for programmers to enhance both person-to-person (P2P) and business-to-business (B2B) payment systems.
CLS Group is using blockchain technology to increase the number of foreign exchange deals it can extend.
VISA payment systems, Mastercard, Unionpay and SWIFT have announced their plans and developments to use blockchain technology.
Blockchain Types
Currently, there are three types of blockchain networks:
public blockchains, private blockchains and consortium blockchains.
Public blockchains
A public blockchain has absolutely no access restrictions. Anyone with an Internet connection can make transactions and gain validity (that is, participate in the execution of a consensus protocol). Often, such networks offer economic incentives for people who secure them and use a Proof of Stake or Proof of Work algorithm.
Some of the largest, best-known public blockchains are Bitcoin and Ethereum.
Private blockchains
These types of blockchains can be considered a middle ground for companies interested in blockchain technology in general but not comfortable with a level of control offered by public networks. Typically, they try not to incorporate blockchain into accounting and record-keeping procedures without compromising their autonomy and exposing sensitive data to public internet risk.
Consortium blockchains
A consortium blockchain is often said to be semi-decentralized. He is also on leave; But instead of a single organization controlling it, each company can operate a node in such a network. Administrators of a consortium chain restrict users' read rights as they see fit, allowing only a limited number of trusted nodes to execute a consortium protocol.
In this article, I talked about blockchain. You can find the list of the series on my profile.
Part 5
Cryptology Fundamentals:#5 Applications
Hello, in this last article of the cryptology basics series, I will talk about how cryptographic protocols are implemented. I will use the Java programming language during the implementation phase.
MD5 Application
MD5 is a widely used hash function that can produce a fixed-size output (128 bits) for any input data. In Java, you can calculate the MD5 digest of a string or file using the MessageDigest class, which is part of the Java Security API.
Here is an example of how to calculate the MD5 hash of a string in Java:
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public class MD5Example {
public static void main(String[] args) {
String input = "Hello, world!";
String md5Hash = calculateMD5(input);
System.out.println("MD5 hash of '" + input + "' is: " + md5Hash);
}
public static String calculateMD5(String input) {
try {
MessageDigest md = MessageDigest.getInstance("MD5");
byte[] hash = md.digest(input.getBytes());
StringBuilder sb = new StringBuilder();
for (byte b : hash) {
sb.append(String.format("%02x", b));
}
return sb.toString();
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException("MD5 algorithm not available", e);
}
}
}
In this example, we first import the MessageDigest class and define a calculateMD5 method that takes a string input and returns the MD5 value as a string.
Inside the calculateMD5 method, we first create a new instance of the MessageDigest class by using the getInstance method and giving the "MD5" algorithm as a parameter. Next, we call the hash method on the MessageDigest object and pass the input string as a byte array to calculate the MD5 digest.
Finally, we convert the byte array to a string using a StringBuilder object and the String.format method to format each byte as a two-digit hexadecimal number. We then return the resulting string as an MD5 digest.
SHA-1 Implementation
SHA-1 (Secure HashAlgorithm 1) is a widely used hash function that can create a fixed-size output (160 bits) for any input data. In Java, you can calculate the SHA-1 digest of a string or file using the MessageDigest class, which is part of the Java Security API.
Here is an example of how to calculate the SHA-1 hash of a string in Java:
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public class SHA1Example {
public static void main(String[] args) {
String input = "Hello, world!";
String sha1Hash = calculateSHA1(input);
System.out.println("SHA-1 hash of '" + input + "' is: " + sha1Hash);
}
public static String calculateSHA1(String input) {
try {
MessageDigest md = MessageDigest.getInstance("SHA-1");
byte[] hash = md.digest(input.getBytes());
StringBuilder sb = new StringBuilder();
for (byte b : hash) {
sb.append(String.format("%02x", b));
}
return sb.toString();
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException("SHA-1 algorithm not available", e);
}
}
}
In this example, we first import the MessageDigest class and define a calculateSHA1 method that takes a string input and returns the SHA-1 digest as a string.
Inside the calculateSHA1 method, we first create a new instance of the MessageDigest class by using the getInstance method and giving the "SHA-1" algorithm as a parameter. Next, we call the hash method on the MessageDigest object and pass the input string as a byte array to calculate the SHA-1 hash value.
Finally, we convert the byte array to a string by using a StringBuilder object and the String.format method to format each byte as a two-digit hexadecimal number. We then return the resulting string as a SHA-1 digest.
DES Application
DES (Data Encryption Standard) is a symmetric key encryption system that can be used to encrypt and decrypt data.me algorithm. In Java, you can use the Cipher class from the Java Cryptography Architecture (JCA) to implement DES encryption and decryption.
Here is an example of how to encrypt and decrypt a string using DES in Java:
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
public class DESExample {
public static void main(String[] args) throws Exception {
String originalString = "Hello, world!";
String secretKey = "mysecretkey";
// Encrypt the original string
String encryptedString = encrypt(originalString, secretKey);
System.out.println("Encrypted string: " + encryptedString);
// Decrypt the encrypted string
String decryptedString = decrypt(encryptedString, secretKey);
System.out.println("Decrypted string: " + decryptedString);
}
public static String encrypt(String plainText, String secretKey) throws Exception {
Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
SecretKeySpec secretKeySpec = new SecretKeySpec(secretKey.getBytes(StandardCharsets.UTF_8), "DES");
cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);
byte[] encryptedBytes = cipher.doFinal(plainText.getBytes(StandardCharsets.UTF_8));
return Base64.getEncoder().encodeToString(encryptedBytes);
}
public static String decrypt(String encryptedText, String secretKey) throws Exception {
Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
SecretKeySpec secretKeySpec = new SecretKeySpec(secretKey.getBytes(StandardCharsets.UTF_8), "DES");
cipher.init(Cipher.DECRYPT_MODE, secretKeySpec);
byte[] decodedBytes = Base64.getDecoder().decode(encryptedText);
byte[] decryptedBytes = cipher.doFinal(decodedBytes);
return new String(decryptedBytes, StandardCharsets.UTF_8);
}
}
In this example, we first import the required classes and define the encrypt and decrypt methods, which take a plaintext string and a secret key string as input and return the corresponding encrypted or decrypted string.
Inside each method, we first create a Cipher object using the "DES/ECB/PKCS5Padding" conversion string, which specifies the DES encryption algorithm with Electronic Code Book (ECB) mode and PKCS5 padding.
We then create a SecretKeySpec object using the secret key string and the "DES" algorithm and initialize the cipher object with the secret key using the init method with the appropriate mode (Cipher.ENCRYPT_MODE or Cipher.DECRYPT_MODE).
For encryption, we convert the plaintext string into a byte array and call the doFinal method on the cipher object to encrypt the data. Then, we convert the resulting byte array to a base64-encoded string using the Base64 class and return the encrypted string.
For decryption, we decode the base64-encoded string back into a byte array using the Base64 class, call the doFinal method on the cipher object to decrypt the data, and convert the resulting byte array into a string using the appropriate character set (in this case, StandardCharsets.UTF_8). We then return the decrypted string.
AES Implementation
AES (Advanced Encryption Standard) is a symmetric key encryption algorithm that can be used to encrypt and decrypt data. In Java, you can use the Cipher class from the Java Cryptography Architecture (JCA) to implement AES encryption and decryption.
Here is an example of how to encrypt and decrypt a string using AES in Java:
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
public class AESExample {
public static void main(String[] args) throws Exception {
String originalString = "Hello, world!";
String secretKey = "mysecretkey";
// Encrypt the original string
String encryptedString = encrypt(originalString, secretKey);
System.out.println("Encrypted string: " + encryptedString);
// Decrypt the encrypted string
String decryptedString = decrypt(encryptedString, secretKey);
System.out.println("Decrypted string: " + decryptedString);
}
public static String encrypt(String plainText, String secretKey) throws Exception {
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
SecretKeySpec secretKeySpec = new SecretKeySpec(secretKey.getBytes(StandardCharsets.UTF_8), "AES");
cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);
byte[] encryptedBytes = cipher.doFinal(plainText.getBytes(StandardCharsets.UTF_8));
return Base64.getEncoder().encodeToString(encryptedBytes);
}
public static String decrypt(String encryptedText, String secretKey) throws Exception {
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
SecretKeySpec secretKeySpec = new SecretKeySpec(secretKey.getBytes(StandardCharsets.UTF_8), "AES");
cipher.init(Cipher.DECRYPT_MODE, secretKeySpec);
byte[] decodedBytes = Base64.getDecoder().decode(encryptedText);
byte[] decryptedBytes = cipher.doFinal(decodedBytes);
return new String(decryptedBytes, StandardCharsets.UTF_8);
}
}
In this example, we first import the required classes and define the encrypt and decrypt methods, which take a plaintext string and a secret key string as input and return the corresponding encrypted or decrypted string.
Inside each method, we first create a Cipher object using the "AES/ECB/PKCS5Padding" transform string, which specifies the AES encryption algorithm with Electronic Code Book (ECB) mode and PKCS5 padding.
We then create a SecretKeySpec object using the secret key string and the "AES" algorithm and initialize the cipher object with the secret key using the init method with the appropriate mode (Cipher.ENCRYPT_MODE or Cipher.DECRYPT_MODE).
For encryption, we convert the plaintext string into a byte string and call the doFinal method on the cipher object to encrypt the data. Then, we convert the resulting byte array to a base64-encoded string using the Base64 class and return the encrypted string.
For decryption, we decode the base64-encoded string back into a byte array using the Base64 class, call the doFinal method on the cipher object to decrypt the data, and convert the resulting byte array into a string using the appropriate character set (in this case, StandardCharsets.UTF_8). We then return the decrypted string.
RSA Implementation
RSA (Rivestâ€"Shamirâ€"Adleman) is a public key encryption algorithm that can be used to securely encrypt and decrypt data. In Java, you can use the KeyPairGenerator and Cipher classes from the Java Cryptography Architecture (JCA) to implement RSA encryption and decryption.
Here is an example of how to create an RSA key pair in Java, encrypt a string using the public key, and decrypt the encrypted string:
import javax.crypto.Cipher;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.util.Base64;
public class RSAExample {
public static void main(String[] args) throws Exception {
String originalString = "Hello, world!";
// Generate an RSA key pair
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
keyPairGenerator.initialize(2048);
KeyPair keyPair = keyPairGenerator.generateKeyPair();
// Get the public and private keys from the key pair
byte[] publicKeyBytes = keyPair.getPublic().getEncoded();
byte[] privateKeyBytes = keyPair.getPrivate().getEncoded();
// Encrypt the original string using the public key
byte[] encryptedBytes = encrypt(originalString.getBytes(), publicKeyBytes);
String encryptedString = Base64.getEncoder().encodeToString(encryptedBytes);
System.out.println("Encrypted string: " + encryptedString);
// Decrypt the encrypted string using the private key
byte[] decryptedBytes = decrypt(Base64.getDecoder().decode(encryptedString), privateKeyBytes);
String decryptedString = new String(decryptedBytes);
System.out.println("Decrypted string: " + decryptedString);
}
public static byte[] encrypt(byte[] plainBytes, byte[] publicKeyBytes) throws Exception {
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.ENCRYPT_MODE, KeyFactory.getInstance("RSA").generatePublic(new X509EncodedKeySpec(publicKeyBytes)));
return cipher.doFinal(plainBytes);
}
public static byte[] decrypt(byte[] encryptedBytes, byte[] privateKeyBytes) throws Exception {
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.DECRYPT_MODE, KeyFactory.getInstance("RSA").generatePrivate(new PKCS8EncodedKeySpec(privateKeyBytes)));
return cipher.doFinal(encryptedBytes);
}
}
In this example, we first import the required classes and define the encrypt and decrypt methods, which take a byte array of plaintext or encrypted data and a byte array of public or private key as input and return the corresponding encrypted or decrypted byte array. .
In the main method, we first create an RSA key pair using the KeyPairGenerator class with the "RSA" algorithm and a key size of 2048 bits. We then extract the public and private keys from the key pair as byte arrays using the getEncoded method.
For encryption, we call the encrypt method with the original string converted to a byte array and the public key byte array as input. We create a Cipher object using the "RSA" algorithm in the Encrypt method and initialize it with the public key using the appropriate mode (Cipher.ENCRYPT_MODE) using the init method. Next, we call the doFinal method on the cipher object to encrypt the data and return the resulting byte array.
For decryption, we call the decrypt method with the base64-decrypted encrypted string converted to a byte array and the private key byte array as input. Inside the Decrypt method, we create another Cipher object using the "RSA" algorithm and initialize it with the private key using the appropriate mode and init method.
ECDH Application
ECDH (Elliptic Curve Diffie-Hellman) is a key agreement protocol that allows two parties to establish a shared secret over an unsecured communication channel. In Java, you can use the KeyAgreement and KeyPairGenerator classes from the Java Cryptography Architecture (JCA) to implement ECDH key exchange using elliptic curve cryptography.
Here's an example of creating an ECDH key pair, performing a key exchange with another party, and deriving a shared key using Java:
import javax.crypto.KeyAgreement;
import javax.crypto.SecretKey;
import javax.crypto.spec.ECGenParameterSpec;
import java.security.*;
import java.security.spec.ECParameterSpec;
import java.security.spec.ECPublicKeySpec;
import java.security.spec.InvalidKeySpecException;
public class ECDHExample {
public static void main(String[] args) throws Exception {
// Generate an ECDH key pair
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("EC");
ECGenParameterSpec ecGenParameterSpec = new ECGenParameterSpec("secp256r1");
keyPairGenerator.initialize(ecGenParameterSpec);
KeyPair keyPair = keyPairGenerator.generateKeyPair();
PrivateKey privateKey = keyPair.getPrivate();
PublicKey publicKey = keyPair.getPublic();
// Simulate the other party by generating its own ECDH key pair
KeyPair otherKeyPair = keyPairGenerator.generateKeyPair();
PrivateKey otherPrivateKey = otherKeyPair.getPrivate();
PublicKey otherPublicKey = otherKeyPair.getPublic();
// Perform key exchange with the other party
KeyAgreement keyAgreement = KeyAgreement.getInstance("ECDH");
keyAgreement.init(privateKey);
keyAgreement.doPhase(otherPublicKey, true);
// Derive the shared secret
byte[] sharedSecret = keyAgreement.generateSecret();
// Simulate the other party deriving the shared secret using its private key
KeyFactory keyFactory = KeyFactory.getInstance("EC");
ECParameterSpec ecParameterSpec = ((ECPublicKeySpec) otherPublicKey.getKeySpec(ECPublicKeySpec.class)).getParams();
PublicKey simulatedOtherPublicKey = keyFactory.generatePublic(new ECPublicKeySpec(((java.security.spec.ECPoint) otherPublicKey).getW(), ecParameterSpec));
KeyAgreement simulatedKeyAgreement = KeyAgreement.getInstance("ECDH");
simulatedKeyAgreement.init(otherPrivateKey);simulatedKeyAgreement.doPhase(publicKey, true);
byte[] simulatedSharedSecret = simulatedKeyAgreement.generateSecret();
// Compare the two shared secrets (should be equal)
System.out.println("Shared secret: " + bytesToHex(sharedSecret));
System.out.println("Simulated shared secret: " + bytesToHex(simulatedSharedSecret));
System.out.println("Shared secrets match: " + bytesToHex(sharedSecret).equals(bytesToHex(simulatedSharedSecret)));
}
public static String bytesToHex(byte[] bytes) {
StringBuilder sb = new StringBuilder();
for (byte b : bytes) {
sb.append(String.format("%02X", b));
}
return sb.toString();
}
}
In this example, we first import the required classes and define a bytesToHex method to convert a byte array to a hexadecimal string.
Inside the main method, we first create an ECDH key pair using the KeyPairGenerator class with the "EC" algorithm and the "secp256r1" elliptic curve parameter property. We then extract the private and public keys from the key pair.
We simulate the counterparty by creating its own ECDH key pair using the same curve parameters.
ECDSA Application
ECDSA (Elliptic Curve Digital Signature Algorithm) is a digital signature algorithm based on elliptic curve cryptography. In Java, you can use the Signature and KeyPairGenerator classes from the Java Cryptography Architecture (JCA) to implement ECDSA.
Here's an example of how to create an ECDSA key pair using Java, sign a message with the private key, and verify the signature with the public key:
import java.security.*;
import java.security.spec.ECGenParameterSpec;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
public class ECDSAExample {
public static void main(String[] args) throws Exception {
// Generate an ECDSA key pair
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("EC");
ECGenParameterSpec ecGenParameterSpec = new ECGenParameterSpec("secp256r1");
keyPairGenerator.initialize(ecGenParameterSpec);
KeyPair keyPair = keyPairGenerator.generateKeyPair();
PrivateKey privateKey = keyPair.getPrivate();
PublicKey publicKey = keyPair.getPublic();
// Sign a message with the private key
byte[] message = "Hello, world!".getBytes();
Signature signature = Signature.getInstance("SHA256withECDSA");
signature.initSign(privateKey);
signature.update(message);
byte[] signatureBytes = signature.sign();
// Verify the signature with the public key
Signature verifier = Signature.getInstance("SHA256withECDSA");
verifier.initVerify(publicKey);
verifier.update(message);
boolean signatureValid = verifier.verify(signatureBytes);
System.out.println("Signature valid: " + signatureValid);
}
}
In this example, we first import the necessary classes.
Inside the main method, we generate an ECDSA key pair using the KeyPairGenerator class with the "EC" algorithm and the elliptic curve parameter property "secp256r1". We extract the private and public keys from the key pair.
We then create a message to sign and use the Signature class to sign the message with the private key. To use SHA-256 as the hash function, we specify the "SHA256withECDSA" algorithm.
Next, we create a validator object using the Signature class and initialize it with the public key. We update the validator with the same message and verify the signature using the verification method. We compare the result to true to determine whether the signature is valid.
Note that in a real-world scenario, you will typically transmit the signed message and the public key separately to the verifier to ensure that the signature has not been tampered with during transmission.
In this article, I made cryptology applications with Java. You can access the article series from my profile. Don't forget to like and follow.
Part 2
Cryptology Fundamentals:#3 Cryptanalysis
Hello, in this article of the cryptology basics series, I will talk about what cryptanalysis is, password cracking techniques and social engineering methods.
Cryptanalysis Overview
Cryptanalysis is the science of breaking and deciphering crypto systems. It is the branch of cryptology that investigates the decryption of encrypted texts. Cryptanalysis is used to find unknown keys.

Cryptanalysis; We can divide Application Attacks into three areas: classical cryptanalysis and social engineering. Now let's look at these areas and the methods used.
Application Attacks
Cryptanalysis methods that attempt to obtain the secret key through reverse engineering or password attacks are types of attacks.
Brute-Force Attacks
This type of password attack uses trial and error methods to guess the target user's password information. The attacker tries as many permutations as possible to correctly guess the user's password. Although it is a relatively old method that requires a lot of patience and time, a brute force attack is still one of the most used methods because it is automatic and straightforward.

There are several types of brute force attacks:
1. Simple brute force attacks: Uses data about a user to guess the most likely password. This technique is used for simple passwords, such as those containing a combination of pet name-year and birth.
2. Credential stuffing: Involves the use of previously compromised login combinations maliciously obtained from vulnerable websites. These types of attacks take advantage of target users' tendency to reuse username-password combinations across multiple services.
3. Reverse brute force attacks: It starts with a known password and then looks for usernames that match that password. Since threat actors often have access to multiple databases of leaked credentials, it is easy to identify common passwords within a given group of users.
Dictionary Attacks
This attack method uses a predefined list of words that are likely to be used as passwords by a particular target network.
The predefined list is created from a website user's behavioral patterns and passwords obtained from previous data breaches. Lists common password combinations by case;
- By changing
- By adding numeric suffixes and prefixes
- Using common expressions
is created. These lists are passed to tools that attempt to authenticate against a list of known usernames.
Here are the tools that can be used to create a password list.
Password Spraying Attacks
In this attack, the hacker attempts to authenticate using the same password across several accounts before switching to another password. Since most website users set simple passwords, password spraying is the most effective technique.
Attackers often use the password spraying attack on websites where administrators set a standard default password for new users and unregistered accounts.
Keylogging
When conducting a Keylogging attack, the attacker installs keyboard monitoring software on the user's computer to record the keys the user secretly types. A keylogger records all the information users type into login forms and then sends them to the malicious attacker.
Computer Forensics
From the memory, disk or processor of a system to which we have physical access; It involves obtaining the secret key using various forensic methods such as string analysis and signal measurement. In cases where I do not have physical access, such as a remote server, we do not need to worry about this attack.
Application Attacks Tools
- CrackStation
- John the Ripper
- Hashcat
- Medusa
- Hydra
- Brutus
- RainbowCrack
- L0phtCrack
- OphCrack
Classical Cryptanalysis
Classical cryptanalysis is the science of recovering the plaintext from its ciphertext or, alternatively, finding the key from its ciphertext. It uses mathematical analysis that takes advantage of the internal structure of the encryption method.
Encryption Decryption
An encryption process consists of 3 elements. These are: clear text, encrypted text and key. If we have any two of these elements, we can easily find the third. However, the main function of cryptanalysis is the ability to find others when only the ciphertext is available. It uses various mathematical methods for this.
These methods are:
- Known Plaintext Analysis (KPA): In this type of attack, some plaintext-ciphertext pairs are already known. The attacker maps them to find the encryption key. This attack is easier to use because a lot of information is already available.
- Chosen Plaintext Analysis (CPA): In this type of attack, the attacker selects random plaintexts and retrieves the corresponding ciphertexts and tries to find the encryption key. Like KPA, it is very simple to implement, but its success rate is quite low.
- Ciphertext Analysis Only (COA): In this type of attack, only some ciphertexts are known and the attacker tries to find the corresponding encryption key and plaintext. It is the most difficult to implement, but the most likely attack since only ciphertext is required.
- Adaptive Selected Plaintext Analysis (ACPA): This attack is similar to CPA. Here the attacker, after having the ciphertexts for some texts, requests the ciphertexts of additional plaintexts.
- Birthday attack: This attack exploits the possibility of two or more people in a group of people sharing the same birthday. In cryptography, this attack is used to find collisions in a hash function.
- Differential cryptanalysis: This type of attack involves comparing pairs of plaintexts and their corresponding ciphertexts to find patterns in the encryption algorithm. It can be effective against block ciphers with certain properties.
- Integral cryptanalysis: It is a method used on block cipher methods based on Replacement-Scrambling functions.
Social Engineering
No matter how strong the crypto system we have established, risks arising from human factors should not be ignored. Bribery, blackmail, deception or classic espionage can be used to obtain a secret key. For example, holding a gun to a person's head and forcing them to tell the password can be quite successful. Another less violent attack is social engineering techniques such as calling the people we want to attack and saying, "We're calling from your company's IT department. We need your password for important software updates." It is surprising that there are no small number of people who are naive enough to actually give their passwords in such cases.
The attacker is always looking for the weakest link in your crypto system. For this, we need to choose strong algorithms and ensure that social engineering and application attacks are impractical. Both application attacks and social engineering attacks can be quite powerful in practice.
Phishing Attacks
It involves a social engineering technique in which the attacker disguises himself as a trusted site by sending a malicious link to the victim. Once the victim assumes they are authenticating with a legitimate web server, they click on that link, providing the attacker with their account information. In this way, the attacker obtains the account information of the target user, and the victim is phished.
Aside from identity theft, phishing attacks enable an attacker to obtain a user's permissions, allowing them to compromise deeper components of the system before the attack is detected. In phishing attacks, attackers often use multiple methods to trick the user into clicking the malicious link:
- DNS cache poisoning: Attackers exploit the application's DNS server to redirect user requests to a malicious site with a similar-sounding domain name.It exploits the security vulnerabilities in its mind.
- URL hijacking/typo: The attacker creates a real-looking URL with subtle differences from the website they want to impersonate. The attack relies on users making typos, so they land on the malicious page.
- Tabbing: The attacker rewrites unattended browser tabs with malicious sites disguised as legitimate web pages.
- UI fix/iFrame overlay: Using transparent layers, the attacker places a link to the malicious page over a legitimate, clickable button.
- Clone phishing : In this attack, the attacker sends a copy of a legitimate email to malicious sites where the links in the original email are replaced with URLs.
In this article, I talked about cryptanalysis. In my next article, I will talk about cryptography. You can find the list of the series on my profile.
Part 3
Cryptology Fundamentals:#2 Cryptography
Hello, in this article of the cryptology basics series, I will talk about what cryptography is, encryption techniques and cryptographic protocols.
Cryptography Overview
Cryptography is the science of secret writing for the purpose of hiding the meaning of a message. Cryptography is a set of mathematical methods and is intended to provide conditions such as confidentiality, authenticity, authentication, and prevention of false rejection necessary for the security of important information. These methods aim to protect the information â€" and therefore the interests of the sender, receiver, carrier of the information, its subjects, and any other parties â€" from active attacks or passive perceptions that may be encountered during the transmission and storage of information.

Cryptography; We can divide it into 3 areas: symmetric encryption, asymmetric encryption and cryptographic protocols. Now let's look at these areas and the methods used.

Basic Classification Diagram for Cryptographic Algorithms
Symmetric Encryption
Symmetric Encryption** is an encryption technique where both parties use the same encryption and decryption method. There is only one common secret key to be used in this encryption method.
All cryptography from ancient times until 1976 was based solely on symmetric methods, and symmetric ciphers are still widely used. It is especially useful for encryption and integrity control of messages.

Symmetric Encryption
In the computer system; All data such as text, images, music are expressed as 1â€"0s, and each 1â€"0 is called a bit.
Symmetric encryption is divided into block ciphers and stream ciphers. Although stream cipher and block cipher are symmetric encryption techniques, there are some important differences. While block ciphers encrypt fixed-length blocks of bits, stream ciphers combine plaintext bits into a text encryption stream using the XOR operation.

Stream Encryption
In stream encryption, bits are encrypted individually. Each bit is encrypted by XORing the bit coming from the bit stream generator. If the encrypted text is XORed with the cipher stream, the plain text is found and decrypted. For this reason, in the stream encryption technique, there is no need for different algorithms for encryption and decryption operations, these operations are performed with the same algorithm.

XOR operation
The most important point in stream encryption algorithms is the bit stream generator. The bitstream generator creates a bitstream based on the key given to it. The complexity and randomness of this bitstream are of great importance to the reliability of the encryption. At this point, different stream encryption algorithms with different bit stream generators have been developed.
ChaCha20
ChaCha20 algorithm is a stream encryption algorithm. Supports 128 and 256 bits. It has similar features to its predecessor Salsa20. It has a primitive function consisting of 12 or 20 different rounds. It was standardized by the IETF in RFC 7539 and is among the most used algorithms today because it is much more efficient and faster than AES in software applications.
Google has a big part in making ChaCha20 so popular. Until a few years ago, Google used AES-GCM as the symmetric encryption algorithm for Chrome and Android. However, due to the use of ARM-based processors in mobile devices and the lack of AES configurations in these processors as in Intel-based processors, encryption was relatively slow. For this reason, Google was working on a more up-to-date, secure and faster encryption algorithm.

ChaCha20-Poly1305
The jumping off point for ChaCha20 was when the android version of Chrome started using ChaCha20 for encryption and Poly1305 for authentication. The main reason for this was that ChaCha20 achieved three times the performance of slightly older protocols such as AES.
ChaCha20, HTTPS connectionsIt is widely used for SSH connections and managing servers. Even the popular WireGuard VPN protocol uses only ChaCha20 for symmetric data encryption. It is very likely that we will soon see ChaCha20 in IPsec connections as well.
Block Cipher
In block ciphering, an entire block of plaintext bits is encrypted at a time. This requires a key bit block that is the same length as the text bit block. In practice, keys with a block length of 128 bits (16 bytes) or 64 bits (8 bytes) are used. The longer the key length, the more reliable the encryption process.
In block ciphering, encryption and decryption algorithms are different algorithms. The decryption algorithm does the exact opposite of what is done in the encryption algorithm.

Block Cipher
There are two key features that make block cipher algorithms reliable. These are the concepts of confusion and diffusion
**Confusion is an encryption process in which the relationship between the key and the ciphertext is hidden.
**Diffusion is an encryption process in which the effect of one plaintext symbol is spread across many ciphertext symbols in order to hide statistical properties of the plaintext.
Algorithms that perform only propagation or only confusion are not secure. However, strong passwords can be created by using a combination of such processes. Today's block cipher algorithms consist of loops that repeatedly apply these operations to the data.
There are two standardized algorithms widely used in the block cipher technique. These; advanced encryption standard (AES) and data encryption standard (DES) algorithms.
DES
Data Encryption Standard (DES) has been by far the most popular block cipher method for most of the last 30 years. Although DES is not considered secure today because its key length is very short, it is still used in old applications.
DES is an algorithm that encrypts 64-bit blocks with a 56-bit key. This algorithm completes the encryption process in 16 rounds, all performing the same operation. A different subkey is used in each round, and all subkeys are derived from the main key k.

If we look in more detail at the transactions made in each round, we encounter the Feistel structure of the DES algorithm (also known as the Feistel network). If this feistel structure is carefully designed, very strong passwords can be created. In addition to their cryptographic power, an advantage of Feistel networks is that encryption and decryption are almost the same process.

The two fundamental properties of passwords mentioned above, namely hashing and diffusion, are implemented within the f-function. Round is taken as the number of rounds and K1, K2,..KN are taken as subkeys for rounds 1,2,..,n respectively. Then, the Ciphertext blocks are divided into 2 equal parts, L and R, and processed within the function. Then, input R is output as L, input L is output as R, and this process is repeated n times.
The diagram shows both encryption and decryption. It is worth noting that the subkey order is reversed for decryption; This is the only difference between encryption and decryption.
Once the f-function is securely designed, the security of the Feistel cipher increases with the number of keys and block length. The more the number of keys, the more the number of rounds and the more confusion and diffusion we get. Likewise, the longer the block length, the longer the password spreads and the harder it is to crack.
####AES
Advanced Encryption Standard (AES) is the most widely used symmetric cipher today. Software that incorporates AES includes Internet security standard IPsec, TLS, Wi-Fi encryption standard IEEE 802.11i, secure shell network protocol SSH (Secure Shell), Internet telephony Skype, and numerous security products worldwide.
Unlike DES, the AES algorithm does not have a Feistel structure. Feistel networks do not encrypt an entire block per iteration, for example in DES 64/2 = 32 bits are encrypted in one round. AES, on the other hand, encrypts all 128 bits in one round. Therefore, the AES algorithm has a relatively small number of rounds.

AES algorithm
In the image above, the plaintext is x and the ciphertext is y.rak and number of rounds are shown as nr.
AES consists of layers. Each layer processes all 128 bits of the block. There are three different types of layers. These;
Key Addition(AddRoundKey) layer: In the key generator, the 128-bit subkey derived from the main key is XORed with state(x).
SubBytes layer:* Each byte in the state matrix is ​​updated according to a table and with a non-linear transformation.
Diffusion layer: Provides diffusion over text bits. It consists of two sublayers, both of which perform linear operations:
- **Row Shift (ShiftRows) layer, each row is shifted circularly a certain number of times.
- The Column Mixing (MixColumn) layer mixes the four-byte blocks in each column. Last round, the MixColumn transform is not used.
In the AES encryption algorithm, the reverse process is done to decrypt.
Asymmetric Encryption
Asymmetric Encryption is an encryption technique in which a user has a private key and also a public key. Asymmetric algorithms can be used for digital signatures, key generation, and classical data encryption.
It was introduced in 1976 as a completely different type of cipher by Whitfield Diffie, Martin Hellman and Ralph Merkle. Also known as public key encryption.

Asymmetric Encryption
Asymmetric cryptography, also known as public key cryptography, is a fairly new encryption technique. It was introduced in 1976 by Whitfield Diffie, Martin Hellman and Ralph Merkle. In asymmetric encryption, each user has a private key and a public key. The way these keys are used is as follows:
- Message + public key = Encrypted message
- Encrypted message + secret key = Decrypted message
- Message + secret key = Signed message
- Signed message + public key = Authentication
In asymmetric encryption, a message encrypted with a user's public key can only be decrypted with that user's private key. This method is used to send a message to that user. If a user has encrypted the message with his private key, we can decrypt this message with that user's public key. This method is also used in authentication, if the message can be decrypted with that user's public key, his identity is confirmed.
Before moving on to the actual public key encryption algorithms, let's take a look at the mathematical basis of these algorithms.
Public Key Algorithm Families
Integer-Factorization Schemes: Many public-key schemes rely on the fact that it is difficult to factor large integers. The most well-known representative of this family of algorithms is RSA.
Discrete Logarithm Schemes: Based on mathematics known as the discrete logarithm problem in finite fields. Examples of this are Diffie-Hellman key exchange, Elgamal encryption or Digital Signature Algorithm (DSA).
Elliptic Curve (EC) Schemes: A generalization of discrete logarithms are elliptic curve public key schemes. The most popular examples include Elliptic Curve Diffie-Hellman key exchange (ECDH) and Elliptic Curve Digital Signature Algorithm (ECDSA).
The first two families appeared in the mid-1970s. Elliptic curves were introduced in the mid-1980s. There are no known attacks against either scheme if parameters and key lengths are chosen carefully.
RSA
RSA is an encryption technique developed considering the algorithmic difficulty of factoring very large integers. There are many applications where RSA is used, but in practice it is most commonly used for digital signatures, digital certificates, and encryption of small pieces of data. Additionally, RSA is the most widely used asymmetric encryption scheme today.
It should be noted that RSA encryption is not intended to replace symmetric ciphers, as it is several times slower than symmetric ciphers such as AES. This is due to the many calculations involved in performing RSA (or any other public key algorithm). Therefore, the main use of the encryption feature is to securely exchange a key with a symmetric cipher (key transfer). In practice, RSA is often used in conjunction with a symmetric cipher such as AES, where the symmetric cipher does the actual bulk data encryption.
The underlying one-way function of RSA is the integer factorization problem:
 Multiplying two large prime numbers is computationally easy (you can actually do it with paper and pencil).niz), but it is very difficult to factor the resulting product. Euler's theorem and Euler's phi function play important roles in RSA. Now, let's look at how encryption, decryption, and key generation work with RSA.

RSA encryption algorithm
e: encryption exponent, d: decryption exponent, n: length
Modular computations play an important role in RSA encryption and decryption. In practice x, y, n and d are very long numbers (usually 1024 bits).
A distinctive feature of all asymmetric schemes is that there is a setup phase in which the public and private key are calculated. Depending on the public key scheme, key generation can be quite complex. Let's take a look at the steps involved in calculating the public and private key for an RSA encryption system:
- N = p.q
 Two different and large prime numbers are determined, which will form the very large integer that we will denote by N. These numbers are called p and q. - φ(N) = (p-1)(q-1)
 The totient value of number N is calculated. Totient is a function in number theory that indicates the number of numbers that are smaller than an integer and prime to that number. - 1 < e < φ(N) and GCF(e, φ(N)) = 1
 As can be understood from the mathematical expression above, an integer between 1 and the Totient value, which is prime between the Totient value and the Totient value, is selected and named e. Choosing a small number of e to be chosen here provides performance gains when performing operations such as mod and exponentiation, but in some cases it reduces security. - d.e ≡ 1 (mod φ(N)
 The number d that provides equivalence and will be used to create the secret key is found. The process to be done here is to find the inverse of the number e in mod φ(N).
We have obtained all the values necessary to create the public and private key. Provided that the numbers (p,q, φ(N)) used in calculating the number d constituting the private key remain secret, the pair (N,e) is the public key; The (N,d) pair constitutes the secret key.
As you can see, doing these operations can be very long and tiring. For this purpose, some practical methods are used in advanced systems. When designing the RSA scheme, if the e and d values are too large, it may cause slow encryption. On the other hand, if these values are too small, this brings security problems.
Protocols
Cryptographic Protocols are encryption methods created by applying and standardizing cryptographic algorithms. Symmetric and asymmetric algorithms are the building blocks of secure Internet communications. A protocol defines how to use these algorithms.
Digital signature
Digital signature is a legal authentication method used for authentication purposes in the electronic environment. It can be roughly defined as a signature made electronically. As with traditional handwritten signatures, only the person creating the digital message must be able to produce a valid signature. To achieve this with cryptographic primi-262 10 Digital Signatures we need to implement public key cryptography. The basic idea is that the person signing the message uses a private key and the receiving party uses the matching public key. The principle of the digital signature scheme is shown in the figure.

Digital Signature
The key feature of digital signatures is this: Since a valid signature can only be calculated with the signer's private key, a signed message can be unambiguously traced back to its origin. Only the signer has the authority to create a signature in his or her own name. Therefore, we can prove that the signing party actually created the message.
 Each of three popular families of public key algorithms, namely integer factorization, discrete logarithms, and elliptic curves, allow us to create digital signatures.
Summary Functions
Hash functions, also known as hash functions, are an important cryptographic protocol. It is extremely useful and appears in almost all information security applications. For a given message, the message digest or hash value can be viewed as a message fingerprint, that is, a unique representation of a message. Unlike other crypto algorithms, hash functions do not have a key.

Summary Function
Hash functions are mathematical functions that convert a numerical input value into another compressed numerical value.Zion. The input of the hash function is of arbitrary length, but the output is always fixed length. The values ​​returned by a hash function are called message digests or simply hash values. Regardless of the input, all output strings produced by a given hash function are the same length. The length is defined by the type of hashing technology used. The output strings are created from a sequence of characters defined in the hash function.
The uses of hash functions in cryptography are very diverse. Hash functions are an important part of digital signature schemes and message authentication codes. It is also widely used for other cryptographic applications, for example, storing password hashes or key derivation.
Features of hash functions
- One-way: Once a hash value is created, it should be impossible to convert it back to the original data.
- Conflict-free: For a hash function to be conflict-free, the hash value of two different data values ​​must not be the same. In other words, each input sequence must produce a unique output sequence.
- Fast: If a hash function takes too long to calculate hash values, it is of little use. Hash functions must therefore be very fast.
Popular Hash Functions
Message Digest (MD)
The MD family consists of hash functions MD2, MD4, MD5 and MD6. Adopted as Internet Standard RFC 1321. It is a 128-bit hash function. The most popular member of the family is MD5.
MD5 was the most popular and widely used hash function for many years. MD5 digests are widely used in the software world to provide assurance about the integrity of the transferred file. For example, file servers often provide a pre-computed MD5 hash for files, so a user can compare the hash of the downloaded file with the provided value. In 2004, conflicts were found in MD5. An analytics attack using the computer cluster was reported to be successful in just an hour. This collision attack resulted in MD5 being an unreliable algorithm and therefore its use is no longer recommended.
Secure Hash Function (SHA)
The SHA family consists of four SHA algorithms; SHA-0, SHA-1, SHA-2 and SHA-3. Although they are from the same family, they have structurally different algorithms.
The original version is SHA-0, a 160-bit hash function, and was published by the National Institute of Standards and Technology (NIST) in 1993. It had a few weaknesses and did not become very popular. Later in 1995, SHA-1 was designed to fix the alleged weaknesses of SHA-0.
SHA-1 is the most widely used of the existing SHA hash functions. It is used in many commonly used applications and protocols, including Secure Sockets Layer (SSL) security. In 2005, a method was found for SHA-1 to expose conflicts within the practical time frame, making the long-term usability of SHA-1 questionable.
The SHA-2 family has four SHA variants, SHA-224, SHA-256, SHA-384, and SHA-512, depending on the number of bits in the hash values. No successful attack on the SHA-2 hash function has yet been reported. Although SHA-2 is a powerful hash function and is significantly different, its basic design is still similar to that of SHA-1. Therefore, NIST has called for new hash function designs.
In October 2012, NIST selected the Keccak algorithm as the new SHA-3 standard. Keccak offers many advantages to its users, such as efficient performance and strong resistance to attacks.
RIPEMD
RIPEMD is the abbreviation for RACE Integrity Primitives Assessment Message Digest. This set of hash functions was designed by the open research community and is commonly known as a family of European hash functions. The family has 3 members. These; RIPEMD, RIPEMD-128 and RIPEMD-160. 256 and 320 bit versions of this algorithm are also available.
The original RIPEMD (128 bit) was based on the design principles used in MD4 and security issues were found. RIPEMD 128-bit version came as a quick fix to overcome vulnerabilities in the original RIPEMD.
RIPEMD-160 is an improved version and is the most used version in the family. The 256- and 320-bit versions reduce the likelihood of conflicts, but do not have higher security levels compared to RIPEMD-128 and RIPEMD-160, respectively.
####Whirlpool
Whirlpool, 512 bIt is a hash function. It is derived from a modified version of the Advanced Encryption Standard (AES). One of the designers was Vincent Rijmen, co-creator of AES. Three versions of Whirlpool have been released. These; They are WHIRLPOOL-0, WHIRLPOOL-T and WHIRLPOOL.
Key Distribution Protocol
Key da protocol is an encryption protocol in which some secret values are shared among several members of a group. The secret value can also be used, for example, as a secret session key for a secure communication channel between members of the group. Roughly speaking, key distribution protocol deals with creating a shared key between two or more parties. For this, key transport or key agreement methods can be used. A key transport protocol is a technique by which one party securely transfers a secret value to others. In a key agreement protocol, two (or more) parties derive the public key, with all parties contributing the key. Ideally, neither party can control what the final public key will be.

Key Agreement
In cryptography, a key agreement protocol is a protocol in which two or more parties can agree on a key in a way that both affects the outcome. If done properly, this prevents unintended third parties from imposing a choice on contracting parties. In practice, advanced protocols do not reveal to any eavesdropping party what key has been agreed upon.
Key Transport
In many key transport protocols, one party simply generates the key and sends that key to the other party; the other side has no influence on the key.
Using a key agreement protocol avoids some of the key distribution problems associated with such systems. Protocols where both parties influence the final derived key are the only way to implement perfect forward secrecy.

In this article, I talked about cryptography. In my next article, I will talk about cryptanalysis. You can find the list of the series on my profile.
Part 4
Hello, in this article of the cryptology basics series, I will talk about what blockchain is, how it works and where it is used.
What is Blockchain?
Blockchain(blockchain) is an ever-growing list of records blocks, linked and secured using cryptography.
Blockchain technology was invented by Satoshi Nakamoto in 2008. Since it has gained great importance in the last few years, many countries have started working to develop the technology and use it in various fields. Blockchain is highly appreciated by FinTech organizations. Practical applications of Blockchain Technology such as Digital Identities, Bitcoin and Ethereum have made it clear that this technology is here to stay. It is a combination of various technologies, including distributed data storage, encryption algorithms and consensus mechanism. Technology has the ability to revolutionize the working models of departments such as finance, banking and cybersecurity departments.
Some of the advantages of blockchain technology:
- No third party intervention.
- Data cannot be modified or deleted.
- Secure data notebook.
- All blocks in the blockchain are timestamped.
- Transparent transactions.
- Distributed to each node in the blockchain.
- There is no risk of duplication or fraud.
How Does Blockchain Work?
Briefly, the blockchain works like this: Each block typically contains transaction data, the hash of the previous block, and a timestamp. By design, a blockchain is resistant to subsequent modification of records. The ledger used is "an open, distributed ledger that can record transactions between two parties in an efficient, verifiable and persistent manner." For use as a distributed ledger, a blockchain is typically managed by a peer-to-peer network for inter-node communication and validating new blocks, collectively tied to a protocol. If the data in any block is wanted to be changed later, the block containing the data and all subsequent blocks will need to be changed. This requires being elected in the node selection for each block write and approval by the majority of the nodes in the network each time before the next node is written. In addition, since it is clear who modified each block, it is possible to detect possible abuse.
Blockchain works on three leading technologies:
1- Cryptography keys
Cryptography keys are of two types â€" Private key and Public key. Both parties in a network have these two keys, thus helping to create a secure digital identity. These keys help in the successful execution of transactions between these two people. This secure identity is the most important aspect of Blockchain technology, called a 'digital signature' when it comes to cryptocurrency.
2- A peer-to-peer network with a shared ledger
The digital signature is then combined with a peer-to-peer network; A large number of individuals acting as authorities and using the digital signature to reach the consensus of others on transactions, among all other matters.
3- A computing tool for sharing the records and transactions of the network
Once they all consent to an agreement, it is confirmed by a mathematical verification that results in a secure transaction between two parties on a shared network.
Thus, in Blockchain technology, users use cryptography keys to perform different digital transactions over a peer-to-peer network.
Where is Blockchain Used?
Blockchain technology can be integrated into multiple domains. The primary use of blockchains today is cryptocurrencies, most notably bitcoin.
Blockchain technology has great potential to transform business operating models in the long term. Blockchain distributed ledger technology is typically a "low cost" technology based on its potential to create new foundations for global economic and social systems.It is a more fundamental technology than a disruptive technology that attacks a traditional business model with a costly solution and quickly consumes incumbents. The use of blockchains promises to bring significant efficiency to global supply chains, financial transactions, ledgers of assets, and decentralized social networks.
Smart contracts
Blockchain-based smart contracts are contracts that can be executed or enforced in whole or in part without human interaction. One of the main purposes of a smart contract is automatic escrow. The IMF believes that blockchains can reduce moral damages and optimize the use of contracts in general. Its legal status is unclear due to lack of widespread use.
Decentralized networks
- The Backfeed project develops a distributed governance system for blockchain-based applications that enables collaborative creation and distribution of value across networks of simultaneously occurring peers.
- The Alexandria project is a blockchain-based Distributed Library.
- Tezos is a blockchain project that governs itself through the vote of token holders. Bitcoin implements the blockchain as a cryptocurrency and payment system. The Ethereum blockchain added a smart contract system on top of a blockchain. The Tezos blockchain will add an autonomy system â€" a decentralized code Development function on top of both the bitcoin and Ethereum blockchains.
Governments and national currencies
Jose Arrieta, Operations Manager for IT Contract Planning at the U.S. General Services Administration, explained at the ACT-IAC (American Technology Council and Industry Advisory Council) Forum in September 2017 that the organization is using blockchain distributed ledger technology through automation to streamline the FASt Lane process of IT Schedule 70 contracts.
The Commercial Clearance Advisory Committee, a subcommittee of U.S. Customs and Border Protection, is working to find practical ways blockchain can be applied to its missions.
Banks
Large parts of the financial industry are implementing distributed ledgers for use in banking, and according to a September 2016 IBM study, this is happening faster than expected. Banks are interested in this technology because it has the potential to speed up back-office settlement systems.
Other financial companies
Credit and debit payment company MasterCard has added three blockchain-based APIs for programmers to enhance both person-to-person (P2P) and business-to-business (B2B) payment systems.
CLS Group is using blockchain technology to increase the number of foreign exchange deals it can extend.
VISA payment systems, Mastercard, Unionpay and SWIFT have announced their plans and developments to use blockchain technology.
Blockchain Types
Currently, there are three types of blockchain networks:
public blockchains, private blockchains and consortium blockchains.
Public blockchains
A public blockchain has absolutely no access restrictions. Anyone with an Internet connection can make transactions and gain validity (that is, participate in the execution of a consensus protocol). Often, such networks offer economic incentives for people who secure them and use a Proof of Stake or Proof of Work algorithm.
Some of the largest, best-known public blockchains are Bitcoin and Ethereum.
Private blockchains
These types of blockchains can be considered a middle ground for companies interested in blockchain technology in general but not comfortable with a level of control offered by public networks. Typically, they try not to incorporate blockchain into accounting and record-keeping procedures without compromising their autonomy and exposing sensitive data to public internet risk.
Consortium blockchains
A consortium blockchain is often said to be semi-decentralized. He is also on leave; But instead of a single organization controlling it, each company can operate a node in such a network. Administrators of a consortium chain restrict users' read rights as they see fit, allowing only a limited number of trusted nodes to execute a consortium protocol.
In this article, I talked about blockchain. You can find the list of the series on my profile.
Part 5
Cryptology Fundamentals:#5 Applications
Hello, in this last article of the cryptology basics series, I will talk about how cryptographic protocols are implemented. I will use the Java programming language during the implementation phase.
MD5 Application
MD5 is a widely used hash function that can produce a fixed-size output (128 bits) for any input data. In Java, you can calculate the MD5 digest of a string or file using the MessageDigest class, which is part of the Java Security API.
Here is an example of how to calculate the MD5 hash of a string in Java:
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public class MD5Example {
public static void main(String[] args) {
String input = "Hello, world!";
String md5Hash = calculateMD5(input);
System.out.println("MD5 hash of '" + input + "' is: " + md5Hash);
}
public static String calculateMD5(String input) {
try {
MessageDigest md = MessageDigest.getInstance("MD5");
byte[] hash = md.digest(input.getBytes());
StringBuilder sb = new StringBuilder();
for (byte b : hash) {
sb.append(String.format("%02x", b));
}
return sb.toString();
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException("MD5 algorithm not available", e);
}
}
}
In this example, we first import the MessageDigest class and define a calculateMD5 method that takes a string input and returns the MD5 value as a string.
Inside the calculateMD5 method, we first create a new instance of the MessageDigest class by using the getInstance method and giving the "MD5" algorithm as a parameter. Next, we call the hash method on the MessageDigest object and pass the input string as a byte array to calculate the MD5 digest.
Finally, we convert the byte array to a string using a StringBuilder object and the String.format method to format each byte as a two-digit hexadecimal number. We then return the resulting string as an MD5 digest.
SHA-1 Implementation
SHA-1 (Secure HashAlgorithm 1) is a widely used hash function that can create a fixed-size output (160 bits) for any input data. In Java, you can calculate the SHA-1 digest of a string or file using the MessageDigest class, which is part of the Java Security API.
Here is an example of how to calculate the SHA-1 hash of a string in Java:
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public class SHA1Example {
public static void main(String[] args) {
String input = "Hello, world!";
String sha1Hash = calculateSHA1(input);
System.out.println("SHA-1 hash of '" + input + "' is: " + sha1Hash);
}
public static String calculateSHA1(String input) {
try {
MessageDigest md = MessageDigest.getInstance("SHA-1");
byte[] hash = md.digest(input.getBytes());
StringBuilder sb = new StringBuilder();
for (byte b : hash) {
sb.append(String.format("%02x", b));
}
return sb.toString();
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException("SHA-1 algorithm not available", e);
}
}
}
In this example, we first import the MessageDigest class and define a calculateSHA1 method that takes a string input and returns the SHA-1 digest as a string.
Inside the calculateSHA1 method, we first create a new instance of the MessageDigest class by using the getInstance method and giving the "SHA-1" algorithm as a parameter. Next, we call the hash method on the MessageDigest object and pass the input string as a byte array to calculate the SHA-1 hash value.
Finally, we convert the byte array to a string by using a StringBuilder object and the String.format method to format each byte as a two-digit hexadecimal number. We then return the resulting string as a SHA-1 digest.
DES Application
DES (Data Encryption Standard) is a symmetric key encryption system that can be used to encrypt and decrypt data.me algorithm. In Java, you can use the Cipher class from the Java Cryptography Architecture (JCA) to implement DES encryption and decryption.
Here is an example of how to encrypt and decrypt a string using DES in Java:
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
public class DESExample {
public static void main(String[] args) throws Exception {
String originalString = "Hello, world!";
String secretKey = "mysecretkey";
// Encrypt the original string
String encryptedString = encrypt(originalString, secretKey);
System.out.println("Encrypted string: " + encryptedString);
// Decrypt the encrypted string
String decryptedString = decrypt(encryptedString, secretKey);
System.out.println("Decrypted string: " + decryptedString);
}
public static String encrypt(String plainText, String secretKey) throws Exception {
Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
SecretKeySpec secretKeySpec = new SecretKeySpec(secretKey.getBytes(StandardCharsets.UTF_8), "DES");
cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);
byte[] encryptedBytes = cipher.doFinal(plainText.getBytes(StandardCharsets.UTF_8));
return Base64.getEncoder().encodeToString(encryptedBytes);
}
public static String decrypt(String encryptedText, String secretKey) throws Exception {
Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
SecretKeySpec secretKeySpec = new SecretKeySpec(secretKey.getBytes(StandardCharsets.UTF_8), "DES");
cipher.init(Cipher.DECRYPT_MODE, secretKeySpec);
byte[] decodedBytes = Base64.getDecoder().decode(encryptedText);
byte[] decryptedBytes = cipher.doFinal(decodedBytes);
return new String(decryptedBytes, StandardCharsets.UTF_8);
}
}
In this example, we first import the required classes and define the encrypt and decrypt methods, which take a plaintext string and a secret key string as input and return the corresponding encrypted or decrypted string.
Inside each method, we first create a Cipher object using the "DES/ECB/PKCS5Padding" conversion string, which specifies the DES encryption algorithm with Electronic Code Book (ECB) mode and PKCS5 padding.
We then create a SecretKeySpec object using the secret key string and the "DES" algorithm and initialize the cipher object with the secret key using the init method with the appropriate mode (Cipher.ENCRYPT_MODE or Cipher.DECRYPT_MODE).
For encryption, we convert the plaintext string into a byte array and call the doFinal method on the cipher object to encrypt the data. Then, we convert the resulting byte array to a base64-encoded string using the Base64 class and return the encrypted string.
For decryption, we decode the base64-encoded string back into a byte array using the Base64 class, call the doFinal method on the cipher object to decrypt the data, and convert the resulting byte array into a string using the appropriate character set (in this case, StandardCharsets.UTF_8). We then return the decrypted string.
AES Implementation
AES (Advanced Encryption Standard) is a symmetric key encryption algorithm that can be used to encrypt and decrypt data. In Java, you can use the Cipher class from the Java Cryptography Architecture (JCA) to implement AES encryption and decryption.
Here is an example of how to encrypt and decrypt a string using AES in Java:
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
public class AESExample {
public static void main(String[] args) throws Exception {
String originalString = "Hello, world!";
String secretKey = "mysecretkey";
// Encrypt the original string
String encryptedString = encrypt(originalString, secretKey);
System.out.println("Encrypted string: " + encryptedString);
// Decrypt the encrypted string
String decryptedString = decrypt(encryptedString, secretKey);
System.out.println("Decrypted string: " + decryptedString);
}
public static String encrypt(String plainText, String secretKey) throws Exception {
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
SecretKeySpec secretKeySpec = new SecretKeySpec(secretKey.getBytes(StandardCharsets.UTF_8), "AES");
cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);
byte[] encryptedBytes = cipher.doFinal(plainText.getBytes(StandardCharsets.UTF_8));
return Base64.getEncoder().encodeToString(encryptedBytes);
}
public static String decrypt(String encryptedText, String secretKey) throws Exception {
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
SecretKeySpec secretKeySpec = new SecretKeySpec(secretKey.getBytes(StandardCharsets.UTF_8), "AES");
cipher.init(Cipher.DECRYPT_MODE, secretKeySpec);
byte[] decodedBytes = Base64.getDecoder().decode(encryptedText);
byte[] decryptedBytes = cipher.doFinal(decodedBytes);
return new String(decryptedBytes, StandardCharsets.UTF_8);
}
}
In this example, we first import the required classes and define the encrypt and decrypt methods, which take a plaintext string and a secret key string as input and return the corresponding encrypted or decrypted string.
Inside each method, we first create a Cipher object using the "AES/ECB/PKCS5Padding" transform string, which specifies the AES encryption algorithm with Electronic Code Book (ECB) mode and PKCS5 padding.
We then create a SecretKeySpec object using the secret key string and the "AES" algorithm and initialize the cipher object with the secret key using the init method with the appropriate mode (Cipher.ENCRYPT_MODE or Cipher.DECRYPT_MODE).
For encryption, we convert the plaintext string into a byte string and call the doFinal method on the cipher object to encrypt the data. Then, we convert the resulting byte array to a base64-encoded string using the Base64 class and return the encrypted string.
For decryption, we decode the base64-encoded string back into a byte array using the Base64 class, call the doFinal method on the cipher object to decrypt the data, and convert the resulting byte array into a string using the appropriate character set (in this case, StandardCharsets.UTF_8). We then return the decrypted string.
RSA Implementation
RSA (Rivestâ€"Shamirâ€"Adleman) is a public key encryption algorithm that can be used to securely encrypt and decrypt data. In Java, you can use the KeyPairGenerator and Cipher classes from the Java Cryptography Architecture (JCA) to implement RSA encryption and decryption.
Here is an example of how to create an RSA key pair in Java, encrypt a string using the public key, and decrypt the encrypted string:
import javax.crypto.Cipher;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.util.Base64;
public class RSAExample {
public static void main(String[] args) throws Exception {
String originalString = "Hello, world!";
// Generate an RSA key pair
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
keyPairGenerator.initialize(2048);
KeyPair keyPair = keyPairGenerator.generateKeyPair();
// Get the public and private keys from the key pair
byte[] publicKeyBytes = keyPair.getPublic().getEncoded();
byte[] privateKeyBytes = keyPair.getPrivate().getEncoded();
// Encrypt the original string using the public key
byte[] encryptedBytes = encrypt(originalString.getBytes(), publicKeyBytes);
String encryptedString = Base64.getEncoder().encodeToString(encryptedBytes);
System.out.println("Encrypted string: " + encryptedString);
// Decrypt the encrypted string using the private key
byte[] decryptedBytes = decrypt(Base64.getDecoder().decode(encryptedString), privateKeyBytes);
String decryptedString = new String(decryptedBytes);
System.out.println("Decrypted string: " + decryptedString);
}
public static byte[] encrypt(byte[] plainBytes, byte[] publicKeyBytes) throws Exception {
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.ENCRYPT_MODE, KeyFactory.getInstance("RSA").generatePublic(new X509EncodedKeySpec(publicKeyBytes)));
return cipher.doFinal(plainBytes);
}
public static byte[] decrypt(byte[] encryptedBytes, byte[] privateKeyBytes) throws Exception {
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.DECRYPT_MODE, KeyFactory.getInstance("RSA").generatePrivate(new PKCS8EncodedKeySpec(privateKeyBytes)));
return cipher.doFinal(encryptedBytes);
}
}
In this example, we first import the required classes and define the encrypt and decrypt methods, which take a byte array of plaintext or encrypted data and a byte array of public or private key as input and return the corresponding encrypted or decrypted byte array. .
In the main method, we first create an RSA key pair using the KeyPairGenerator class with the "RSA" algorithm and a key size of 2048 bits. We then extract the public and private keys from the key pair as byte arrays using the getEncoded method.
For encryption, we call the encrypt method with the original string converted to a byte array and the public key byte array as input. We create a Cipher object using the "RSA" algorithm in the Encrypt method and initialize it with the public key using the appropriate mode (Cipher.ENCRYPT_MODE) using the init method. Next, we call the doFinal method on the cipher object to encrypt the data and return the resulting byte array.
For decryption, we call the decrypt method with the base64-decrypted encrypted string converted to a byte array and the private key byte array as input. Inside the Decrypt method, we create another Cipher object using the "RSA" algorithm and initialize it with the private key using the appropriate mode and init method.
ECDH Application
ECDH (Elliptic Curve Diffie-Hellman) is a key agreement protocol that allows two parties to establish a shared secret over an unsecured communication channel. In Java, you can use the KeyAgreement and KeyPairGenerator classes from the Java Cryptography Architecture (JCA) to implement ECDH key exchange using elliptic curve cryptography.
Here's an example of creating an ECDH key pair, performing a key exchange with another party, and deriving a shared key using Java:
import javax.crypto.KeyAgreement;
import javax.crypto.SecretKey;
import javax.crypto.spec.ECGenParameterSpec;
import java.security.*;
import java.security.spec.ECParameterSpec;
import java.security.spec.ECPublicKeySpec;
import java.security.spec.InvalidKeySpecException;
public class ECDHExample {
public static void main(String[] args) throws Exception {
// Generate an ECDH key pair
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("EC");
ECGenParameterSpec ecGenParameterSpec = new ECGenParameterSpec("secp256r1");
keyPairGenerator.initialize(ecGenParameterSpec);
KeyPair keyPair = keyPairGenerator.generateKeyPair();
PrivateKey privateKey = keyPair.getPrivate();
PublicKey publicKey = keyPair.getPublic();
// Simulate the other party by generating its own ECDH key pair
KeyPair otherKeyPair = keyPairGenerator.generateKeyPair();
PrivateKey otherPrivateKey = otherKeyPair.getPrivate();
PublicKey otherPublicKey = otherKeyPair.getPublic();
// Perform key exchange with the other party
KeyAgreement keyAgreement = KeyAgreement.getInstance("ECDH");
keyAgreement.init(privateKey);
keyAgreement.doPhase(otherPublicKey, true);
// Derive the shared secret
byte[] sharedSecret = keyAgreement.generateSecret();
// Simulate the other party deriving the shared secret using its private key
KeyFactory keyFactory = KeyFactory.getInstance("EC");
ECParameterSpec ecParameterSpec = ((ECPublicKeySpec) otherPublicKey.getKeySpec(ECPublicKeySpec.class)).getParams();
PublicKey simulatedOtherPublicKey = keyFactory.generatePublic(new ECPublicKeySpec(((java.security.spec.ECPoint) otherPublicKey).getW(), ecParameterSpec));
KeyAgreement simulatedKeyAgreement = KeyAgreement.getInstance("ECDH");
simulatedKeyAgreement.init(otherPrivateKey);simulatedKeyAgreement.doPhase(publicKey, true);
byte[] simulatedSharedSecret = simulatedKeyAgreement.generateSecret();
// Compare the two shared secrets (should be equal)
System.out.println("Shared secret: " + bytesToHex(sharedSecret));
System.out.println("Simulated shared secret: " + bytesToHex(simulatedSharedSecret));
System.out.println("Shared secrets match: " + bytesToHex(sharedSecret).equals(bytesToHex(simulatedSharedSecret)));
}
public static String bytesToHex(byte[] bytes) {
StringBuilder sb = new StringBuilder();
for (byte b : bytes) {
sb.append(String.format("%02X", b));
}
return sb.toString();
}
}
In this example, we first import the required classes and define a bytesToHex method to convert a byte array to a hexadecimal string.
Inside the main method, we first create an ECDH key pair using the KeyPairGenerator class with the "EC" algorithm and the "secp256r1" elliptic curve parameter property. We then extract the private and public keys from the key pair.
We simulate the counterparty by creating its own ECDH key pair using the same curve parameters.
ECDSA Application
ECDSA (Elliptic Curve Digital Signature Algorithm) is a digital signature algorithm based on elliptic curve cryptography. In Java, you can use the Signature and KeyPairGenerator classes from the Java Cryptography Architecture (JCA) to implement ECDSA.
Here's an example of how to create an ECDSA key pair using Java, sign a message with the private key, and verify the signature with the public key:
import java.security.*;
import java.security.spec.ECGenParameterSpec;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
public class ECDSAExample {
public static void main(String[] args) throws Exception {
// Generate an ECDSA key pair
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("EC");
ECGenParameterSpec ecGenParameterSpec = new ECGenParameterSpec("secp256r1");
keyPairGenerator.initialize(ecGenParameterSpec);
KeyPair keyPair = keyPairGenerator.generateKeyPair();
PrivateKey privateKey = keyPair.getPrivate();
PublicKey publicKey = keyPair.getPublic();
// Sign a message with the private key
byte[] message = "Hello, world!".getBytes();
Signature signature = Signature.getInstance("SHA256withECDSA");
signature.initSign(privateKey);
signature.update(message);
byte[] signatureBytes = signature.sign();
// Verify the signature with the public key
Signature verifier = Signature.getInstance("SHA256withECDSA");
verifier.initVerify(publicKey);
verifier.update(message);
boolean signatureValid = verifier.verify(signatureBytes);
System.out.println("Signature valid: " + signatureValid);
}
}
In this example, we first import the necessary classes.
Inside the main method, we generate an ECDSA key pair using the KeyPairGenerator class with the "EC" algorithm and the elliptic curve parameter property "secp256r1". We extract the private and public keys from the key pair.
We then create a message to sign and use the Signature class to sign the message with the private key. To use SHA-256 as the hash function, we specify the "SHA256withECDSA" algorithm.
Next, we create a validator object using the Signature class and initialize it with the public key. We update the validator with the same message and verify the signature using the verification method. We compare the result to true to determine whether the signature is valid.
Note that in a real-world scenario, you will typically transmit the signed message and the public key separately to the verifier to ensure that the signature has not been tampered with during transmission.
In this article, I made cryptology applications with Java. You can access the article series from my profile. Don't forget to like and follow.
Part 2
Cryptology Fundamentals:#3 Cryptanalysis
Hello, in this article of the cryptology basics series, I will talk about what cryptanalysis is, password cracking techniques and social engineering methods.
Cryptanalysis Overview
Cryptanalysis is the science of breaking and deciphering crypto systems. It is the branch of cryptology that investigates the decryption of encrypted texts. Cryptanalysis is used to find unknown keys.

Cryptanalysis; We can divide Application Attacks into three areas: classical cryptanalysis and social engineering. Now let's look at these areas and the methods used.
Application Attacks
Cryptanalysis methods that attempt to obtain the secret key through reverse engineering or password attacks are types of attacks.
Brute-Force Attacks
This type of password attack uses trial and error methods to guess the target user's password information. The attacker tries as many permutations as possible to correctly guess the user's password. Although it is a relatively old method that requires a lot of patience and time, a brute force attack is still one of the most used methods because it is automatic and straightforward.

There are several types of brute force attacks:
1. Simple brute force attacks: Uses data about a user to guess the most likely password. This technique is used for simple passwords, such as those containing a combination of pet name-year and birth.
2. Credential stuffing: Involves the use of previously compromised login combinations maliciously obtained from vulnerable websites. These types of attacks take advantage of target users' tendency to reuse username-password combinations across multiple services.
3. Reverse brute force attacks: It starts with a known password and then looks for usernames that match that password. Since threat actors often have access to multiple databases of leaked credentials, it is easy to identify common passwords within a given group of users.
Dictionary Attacks
This attack method uses a predefined list of words that are likely to be used as passwords by a particular target network.
The predefined list is created from a website user's behavioral patterns and passwords obtained from previous data breaches. Lists common password combinations by case;
- By changing
- By adding numeric suffixes and prefixes
- Using common expressions
is created. These lists are passed to tools that attempt to authenticate against a list of known usernames.
Here are the tools that can be used to create a password list.
Password Spraying Attacks
In this attack, the hacker attempts to authenticate using the same password across several accounts before switching to another password. Since most website users set simple passwords, password spraying is the most effective technique.
Attackers often use the password spraying attack on websites where administrators set a standard default password for new users and unregistered accounts.
Keylogging
When conducting a Keylogging attack, the attacker installs keyboard monitoring software on the user's computer to record the keys the user secretly types. A keylogger records all the information users type into login forms and then sends them to the malicious attacker.
Computer Forensics
From the memory, disk or processor of a system to which we have physical access; It involves obtaining the secret key using various forensic methods such as string analysis and signal measurement. In cases where I do not have physical access, such as a remote server, we do not need to worry about this attack.
Application Attacks Tools
- CrackStation
- John the Ripper
- Hashcat
- Medusa
- Hydra
- Brutus
- RainbowCrack
- L0phtCrack
- OphCrack
Classical Cryptanalysis
Classical cryptanalysis is the science of recovering the plaintext from its ciphertext or, alternatively, finding the key from its ciphertext. It uses mathematical analysis that takes advantage of the internal structure of the encryption method.
Encryption Decryption
An encryption process consists of 3 elements. These are: clear text, encrypted text and key. If we have any two of these elements, we can easily find the third. However, the main function of cryptanalysis is the ability to find others when only the ciphertext is available. It uses various mathematical methods for this.
These methods are:
- Known Plaintext Analysis (KPA): In this type of attack, some plaintext-ciphertext pairs are already known. The attacker maps them to find the encryption key. This attack is easier to use because a lot of information is already available.
- Chosen Plaintext Analysis (CPA): In this type of attack, the attacker selects random plaintexts and retrieves the corresponding ciphertexts and tries to find the encryption key. Like KPA, it is very simple to implement, but its success rate is quite low.
- Ciphertext Analysis Only (COA): In this type of attack, only some ciphertexts are known and the attacker tries to find the corresponding encryption key and plaintext. It is the most difficult to implement, but the most likely attack since only ciphertext is required.
- Adaptive Selected Plaintext Analysis (ACPA): This attack is similar to CPA. Here the attacker, after having the ciphertexts for some texts, requests the ciphertexts of additional plaintexts.
- Birthday attack: This attack exploits the possibility of two or more people in a group of people sharing the same birthday. In cryptography, this attack is used to find collisions in a hash function.
- Differential cryptanalysis: This type of attack involves comparing pairs of plaintexts and their corresponding ciphertexts to find patterns in the encryption algorithm. It can be effective against block ciphers with certain properties.
- Integral cryptanalysis: It is a method used on block cipher methods based on Replacement-Scrambling functions.
Social Engineering
No matter how strong the crypto system we have established, risks arising from human factors should not be ignored. Bribery, blackmail, deception or classic espionage can be used to obtain a secret key. For example, holding a gun to a person's head and forcing them to tell the password can be quite successful. Another less violent attack is social engineering techniques such as calling the people we want to attack and saying, "We're calling from your company's IT department. We need your password for important software updates." It is surprising that there are no small number of people who are naive enough to actually give their passwords in such cases.
The attacker is always looking for the weakest link in your crypto system. For this, we need to choose strong algorithms and ensure that social engineering and application attacks are impractical. Both application attacks and social engineering attacks can be quite powerful in practice.
Phishing Attacks
It involves a social engineering technique in which the attacker disguises himself as a trusted site by sending a malicious link to the victim. Once the victim assumes they are authenticating with a legitimate web server, they click on that link, providing the attacker with their account information. In this way, the attacker obtains the account information of the target user, and the victim is phished.
Aside from identity theft, phishing attacks enable an attacker to obtain a user's permissions, allowing them to compromise deeper components of the system before the attack is detected. In phishing attacks, attackers often use multiple methods to trick the user into clicking the malicious link:
- DNS cache poisoning: Attackers exploit the application's DNS server to redirect user requests to a malicious site with a similar-sounding domain name.It exploits the security vulnerabilities in its mind.
- URL hijacking/typo: The attacker creates a real-looking URL with subtle differences from the website they want to impersonate. The attack relies on users making typos, so they land on the malicious page.
- Tabbing: The attacker rewrites unattended browser tabs with malicious sites disguised as legitimate web pages.
- UI fix/iFrame overlay: Using transparent layers, the attacker places a link to the malicious page over a legitimate, clickable button.
- Clone phishing : In this attack, the attacker sends a copy of a legitimate email to malicious sites where the links in the original email are replaced with URLs.
In this article, I talked about cryptanalysis. In my next article, I will talk about cryptography. You can find the list of the series on my profile.
Part 3
Cryptology Fundamentals:#2 Cryptography
Hello, in this article of the cryptology basics series, I will talk about what cryptography is, encryption techniques and cryptographic protocols.
Cryptography Overview
Cryptography is the science of secret writing for the purpose of hiding the meaning of a message. Cryptography is a set of mathematical methods and is intended to provide conditions such as confidentiality, authenticity, authentication, and prevention of false rejection necessary for the security of important information. These methods aim to protect the information â€" and therefore the interests of the sender, receiver, carrier of the information, its subjects, and any other parties â€" from active attacks or passive perceptions that may be encountered during the transmission and storage of information.

Cryptography; We can divide it into 3 areas: symmetric encryption, asymmetric encryption and cryptographic protocols. Now let's look at these areas and the methods used.

Basic Classification Diagram for Cryptographic Algorithms
Symmetric Encryption
Symmetric Encryption** is an encryption technique where both parties use the same encryption and decryption method. There is only one common secret key to be used in this encryption method.
All cryptography from ancient times until 1976 was based solely on symmetric methods, and symmetric ciphers are still widely used. It is especially useful for encryption and integrity control of messages.

Symmetric Encryption
In the computer system; All data such as text, images, music are expressed as 1â€"0s, and each 1â€"0 is called a bit.
Symmetric encryption is divided into block ciphers and stream ciphers. Although stream cipher and block cipher are symmetric encryption techniques, there are some important differences. While block ciphers encrypt fixed-length blocks of bits, stream ciphers combine plaintext bits into a text encryption stream using the XOR operation.

Stream Encryption
In stream encryption, bits are encrypted individually. Each bit is encrypted by XORing the bit coming from the bit stream generator. If the encrypted text is XORed with the cipher stream, the plain text is found and decrypted. For this reason, in the stream encryption technique, there is no need for different algorithms for encryption and decryption operations, these operations are performed with the same algorithm.

XOR operation
The most important point in stream encryption algorithms is the bit stream generator. The bitstream generator creates a bitstream based on the key given to it. The complexity and randomness of this bitstream are of great importance to the reliability of the encryption. At this point, different stream encryption algorithms with different bit stream generators have been developed.
ChaCha20
ChaCha20 algorithm is a stream encryption algorithm. Supports 128 and 256 bits. It has similar features to its predecessor Salsa20. It has a primitive function consisting of 12 or 20 different rounds. It was standardized by the IETF in RFC 7539 and is among the most used algorithms today because it is much more efficient and faster than AES in software applications.
Google has a big part in making ChaCha20 so popular. Until a few years ago, Google used AES-GCM as the symmetric encryption algorithm for Chrome and Android. However, due to the use of ARM-based processors in mobile devices and the lack of AES configurations in these processors as in Intel-based processors, encryption was relatively slow. For this reason, Google was working on a more up-to-date, secure and faster encryption algorithm.

ChaCha20-Poly1305
The jumping off point for ChaCha20 was when the android version of Chrome started using ChaCha20 for encryption and Poly1305 for authentication. The main reason for this was that ChaCha20 achieved three times the performance of slightly older protocols such as AES.
ChaCha20, HTTPS connectionsIt is widely used for SSH connections and managing servers. Even the popular WireGuard VPN protocol uses only ChaCha20 for symmetric data encryption. It is very likely that we will soon see ChaCha20 in IPsec connections as well.
Block Cipher
In block ciphering, an entire block of plaintext bits is encrypted at a time. This requires a key bit block that is the same length as the text bit block. In practice, keys with a block length of 128 bits (16 bytes) or 64 bits (8 bytes) are used. The longer the key length, the more reliable the encryption process.
In block ciphering, encryption and decryption algorithms are different algorithms. The decryption algorithm does the exact opposite of what is done in the encryption algorithm.

Block Cipher
There are two key features that make block cipher algorithms reliable. These are the concepts of confusion and diffusion
**Confusion is an encryption process in which the relationship between the key and the ciphertext is hidden.
**Diffusion is an encryption process in which the effect of one plaintext symbol is spread across many ciphertext symbols in order to hide statistical properties of the plaintext.
Algorithms that perform only propagation or only confusion are not secure. However, strong passwords can be created by using a combination of such processes. Today's block cipher algorithms consist of loops that repeatedly apply these operations to the data.
There are two standardized algorithms widely used in the block cipher technique. These; advanced encryption standard (AES) and data encryption standard (DES) algorithms.
DES
Data Encryption Standard (DES) has been by far the most popular block cipher method for most of the last 30 years. Although DES is not considered secure today because its key length is very short, it is still used in old applications.
DES is an algorithm that encrypts 64-bit blocks with a 56-bit key. This algorithm completes the encryption process in 16 rounds, all performing the same operation. A different subkey is used in each round, and all subkeys are derived from the main key k.

If we look in more detail at the transactions made in each round, we encounter the Feistel structure of the DES algorithm (also known as the Feistel network). If this feistel structure is carefully designed, very strong passwords can be created. In addition to their cryptographic power, an advantage of Feistel networks is that encryption and decryption are almost the same process.

The two fundamental properties of passwords mentioned above, namely hashing and diffusion, are implemented within the f-function. Round is taken as the number of rounds and K1, K2,..KN are taken as subkeys for rounds 1,2,..,n respectively. Then, the Ciphertext blocks are divided into 2 equal parts, L and R, and processed within the function. Then, input R is output as L, input L is output as R, and this process is repeated n times.
The diagram shows both encryption and decryption. It is worth noting that the subkey order is reversed for decryption; This is the only difference between encryption and decryption.
Once the f-function is securely designed, the security of the Feistel cipher increases with the number of keys and block length. The more the number of keys, the more the number of rounds and the more confusion and diffusion we get. Likewise, the longer the block length, the longer the password spreads and the harder it is to crack.
####AES
Advanced Encryption Standard (AES) is the most widely used symmetric cipher today. Software that incorporates AES includes Internet security standard IPsec, TLS, Wi-Fi encryption standard IEEE 802.11i, secure shell network protocol SSH (Secure Shell), Internet telephony Skype, and numerous security products worldwide.
Unlike DES, the AES algorithm does not have a Feistel structure. Feistel networks do not encrypt an entire block per iteration, for example in DES 64/2 = 32 bits are encrypted in one round. AES, on the other hand, encrypts all 128 bits in one round. Therefore, the AES algorithm has a relatively small number of rounds.

AES algorithm
In the image above, the plaintext is x and the ciphertext is y.rak and number of rounds are shown as nr.
AES consists of layers. Each layer processes all 128 bits of the block. There are three different types of layers. These;
Key Addition(AddRoundKey) layer: In the key generator, the 128-bit subkey derived from the main key is XORed with state(x).
SubBytes layer:* Each byte in the state matrix is ​​updated according to a table and with a non-linear transformation.
Diffusion layer: Provides diffusion over text bits. It consists of two sublayers, both of which perform linear operations:
- **Row Shift (ShiftRows) layer, each row is shifted circularly a certain number of times.
- The Column Mixing (MixColumn) layer mixes the four-byte blocks in each column. Last round, the MixColumn transform is not used.
In the AES encryption algorithm, the reverse process is done to decrypt.
Asymmetric Encryption
Asymmetric Encryption is an encryption technique in which a user has a private key and also a public key. Asymmetric algorithms can be used for digital signatures, key generation, and classical data encryption.
It was introduced in 1976 as a completely different type of cipher by Whitfield Diffie, Martin Hellman and Ralph Merkle. Also known as public key encryption.

Asymmetric Encryption
Asymmetric cryptography, also known as public key cryptography, is a fairly new encryption technique. It was introduced in 1976 by Whitfield Diffie, Martin Hellman and Ralph Merkle. In asymmetric encryption, each user has a private key and a public key. The way these keys are used is as follows:
- Message + public key = Encrypted message
- Encrypted message + secret key = Decrypted message
- Message + secret key = Signed message
- Signed message + public key = Authentication
In asymmetric encryption, a message encrypted with a user's public key can only be decrypted with that user's private key. This method is used to send a message to that user. If a user has encrypted the message with his private key, we can decrypt this message with that user's public key. This method is also used in authentication, if the message can be decrypted with that user's public key, his identity is confirmed.
Before moving on to the actual public key encryption algorithms, let's take a look at the mathematical basis of these algorithms.
Public Key Algorithm Families
Integer-Factorization Schemes: Many public-key schemes rely on the fact that it is difficult to factor large integers. The most well-known representative of this family of algorithms is RSA.
Discrete Logarithm Schemes: Based on mathematics known as the discrete logarithm problem in finite fields. Examples of this are Diffie-Hellman key exchange, Elgamal encryption or Digital Signature Algorithm (DSA).
Elliptic Curve (EC) Schemes: A generalization of discrete logarithms are elliptic curve public key schemes. The most popular examples include Elliptic Curve Diffie-Hellman key exchange (ECDH) and Elliptic Curve Digital Signature Algorithm (ECDSA).
The first two families appeared in the mid-1970s. Elliptic curves were introduced in the mid-1980s. There are no known attacks against either scheme if parameters and key lengths are chosen carefully.
RSA
RSA is an encryption technique developed considering the algorithmic difficulty of factoring very large integers. There are many applications where RSA is used, but in practice it is most commonly used for digital signatures, digital certificates, and encryption of small pieces of data. Additionally, RSA is the most widely used asymmetric encryption scheme today.
It should be noted that RSA encryption is not intended to replace symmetric ciphers, as it is several times slower than symmetric ciphers such as AES. This is due to the many calculations involved in performing RSA (or any other public key algorithm). Therefore, the main use of the encryption feature is to securely exchange a key with a symmetric cipher (key transfer). In practice, RSA is often used in conjunction with a symmetric cipher such as AES, where the symmetric cipher does the actual bulk data encryption.
The underlying one-way function of RSA is the integer factorization problem:
 Multiplying two large prime numbers is computationally easy (you can actually do it with paper and pencil).niz), but it is very difficult to factor the resulting product. Euler's theorem and Euler's phi function play important roles in RSA. Now, let's look at how encryption, decryption, and key generation work with RSA.

RSA encryption algorithm
e: encryption exponent, d: decryption exponent, n: length
Modular computations play an important role in RSA encryption and decryption. In practice x, y, n and d are very long numbers (usually 1024 bits).
A distinctive feature of all asymmetric schemes is that there is a setup phase in which the public and private key are calculated. Depending on the public key scheme, key generation can be quite complex. Let's take a look at the steps involved in calculating the public and private key for an RSA encryption system:
- N = p.q
 Two different and large prime numbers are determined, which will form the very large integer that we will denote by N. These numbers are called p and q. - φ(N) = (p-1)(q-1)
 The totient value of number N is calculated. Totient is a function in number theory that indicates the number of numbers that are smaller than an integer and prime to that number. - 1 < e < φ(N) and GCF(e, φ(N)) = 1
 As can be understood from the mathematical expression above, an integer between 1 and the Totient value, which is prime between the Totient value and the Totient value, is selected and named e. Choosing a small number of e to be chosen here provides performance gains when performing operations such as mod and exponentiation, but in some cases it reduces security. - d.e ≡ 1 (mod φ(N)
 The number d that provides equivalence and will be used to create the secret key is found. The process to be done here is to find the inverse of the number e in mod φ(N).
We have obtained all the values necessary to create the public and private key. Provided that the numbers (p,q, φ(N)) used in calculating the number d constituting the private key remain secret, the pair (N,e) is the public key; The (N,d) pair constitutes the secret key.
As you can see, doing these operations can be very long and tiring. For this purpose, some practical methods are used in advanced systems. When designing the RSA scheme, if the e and d values are too large, it may cause slow encryption. On the other hand, if these values are too small, this brings security problems.
Protocols
Cryptographic Protocols are encryption methods created by applying and standardizing cryptographic algorithms. Symmetric and asymmetric algorithms are the building blocks of secure Internet communications. A protocol defines how to use these algorithms.
Digital signature
Digital signature is a legal authentication method used for authentication purposes in the electronic environment. It can be roughly defined as a signature made electronically. As with traditional handwritten signatures, only the person creating the digital message must be able to produce a valid signature. To achieve this with cryptographic primi-262 10 Digital Signatures we need to implement public key cryptography. The basic idea is that the person signing the message uses a private key and the receiving party uses the matching public key. The principle of the digital signature scheme is shown in the figure.

Digital Signature
The key feature of digital signatures is this: Since a valid signature can only be calculated with the signer's private key, a signed message can be unambiguously traced back to its origin. Only the signer has the authority to create a signature in his or her own name. Therefore, we can prove that the signing party actually created the message.
 Each of three popular families of public key algorithms, namely integer factorization, discrete logarithms, and elliptic curves, allow us to create digital signatures.
Summary Functions
Hash functions, also known as hash functions, are an important cryptographic protocol. It is extremely useful and appears in almost all information security applications. For a given message, the message digest or hash value can be viewed as a message fingerprint, that is, a unique representation of a message. Unlike other crypto algorithms, hash functions do not have a key.

Summary Function
Hash functions are mathematical functions that convert a numerical input value into another compressed numerical value.Zion. The input of the hash function is of arbitrary length, but the output is always fixed length. The values ​​returned by a hash function are called message digests or simply hash values. Regardless of the input, all output strings produced by a given hash function are the same length. The length is defined by the type of hashing technology used. The output strings are created from a sequence of characters defined in the hash function.
The uses of hash functions in cryptography are very diverse. Hash functions are an important part of digital signature schemes and message authentication codes. It is also widely used for other cryptographic applications, for example, storing password hashes or key derivation.
Features of hash functions
- One-way: Once a hash value is created, it should be impossible to convert it back to the original data.
- Conflict-free: For a hash function to be conflict-free, the hash value of two different data values ​​must not be the same. In other words, each input sequence must produce a unique output sequence.
- Fast: If a hash function takes too long to calculate hash values, it is of little use. Hash functions must therefore be very fast.
Popular Hash Functions
Message Digest (MD)
The MD family consists of hash functions MD2, MD4, MD5 and MD6. Adopted as Internet Standard RFC 1321. It is a 128-bit hash function. The most popular member of the family is MD5.
MD5 was the most popular and widely used hash function for many years. MD5 digests are widely used in the software world to provide assurance about the integrity of the transferred file. For example, file servers often provide a pre-computed MD5 hash for files, so a user can compare the hash of the downloaded file with the provided value. In 2004, conflicts were found in MD5. An analytics attack using the computer cluster was reported to be successful in just an hour. This collision attack resulted in MD5 being an unreliable algorithm and therefore its use is no longer recommended.
Secure Hash Function (SHA)
The SHA family consists of four SHA algorithms; SHA-0, SHA-1, SHA-2 and SHA-3. Although they are from the same family, they have structurally different algorithms.
The original version is SHA-0, a 160-bit hash function, and was published by the National Institute of Standards and Technology (NIST) in 1993. It had a few weaknesses and did not become very popular. Later in 1995, SHA-1 was designed to fix the alleged weaknesses of SHA-0.
SHA-1 is the most widely used of the existing SHA hash functions. It is used in many commonly used applications and protocols, including Secure Sockets Layer (SSL) security. In 2005, a method was found for SHA-1 to expose conflicts within the practical time frame, making the long-term usability of SHA-1 questionable.
The SHA-2 family has four SHA variants, SHA-224, SHA-256, SHA-384, and SHA-512, depending on the number of bits in the hash values. No successful attack on the SHA-2 hash function has yet been reported. Although SHA-2 is a powerful hash function and is significantly different, its basic design is still similar to that of SHA-1. Therefore, NIST has called for new hash function designs.
In October 2012, NIST selected the Keccak algorithm as the new SHA-3 standard. Keccak offers many advantages to its users, such as efficient performance and strong resistance to attacks.
RIPEMD
RIPEMD is the abbreviation for RACE Integrity Primitives Assessment Message Digest. This set of hash functions was designed by the open research community and is commonly known as a family of European hash functions. The family has 3 members. These; RIPEMD, RIPEMD-128 and RIPEMD-160. 256 and 320 bit versions of this algorithm are also available.
The original RIPEMD (128 bit) was based on the design principles used in MD4 and security issues were found. RIPEMD 128-bit version came as a quick fix to overcome vulnerabilities in the original RIPEMD.
RIPEMD-160 is an improved version and is the most used version in the family. The 256- and 320-bit versions reduce the likelihood of conflicts, but do not have higher security levels compared to RIPEMD-128 and RIPEMD-160, respectively.
####Whirlpool
Whirlpool, 512 bIt is a hash function. It is derived from a modified version of the Advanced Encryption Standard (AES). One of the designers was Vincent Rijmen, co-creator of AES. Three versions of Whirlpool have been released. These; They are WHIRLPOOL-0, WHIRLPOOL-T and WHIRLPOOL.
Key Distribution Protocol
Key da protocol is an encryption protocol in which some secret values are shared among several members of a group. The secret value can also be used, for example, as a secret session key for a secure communication channel between members of the group. Roughly speaking, key distribution protocol deals with creating a shared key between two or more parties. For this, key transport or key agreement methods can be used. A key transport protocol is a technique by which one party securely transfers a secret value to others. In a key agreement protocol, two (or more) parties derive the public key, with all parties contributing the key. Ideally, neither party can control what the final public key will be.

Key Agreement
In cryptography, a key agreement protocol is a protocol in which two or more parties can agree on a key in a way that both affects the outcome. If done properly, this prevents unintended third parties from imposing a choice on contracting parties. In practice, advanced protocols do not reveal to any eavesdropping party what key has been agreed upon.
Key Transport
In many key transport protocols, one party simply generates the key and sends that key to the other party; the other side has no influence on the key.
Using a key agreement protocol avoids some of the key distribution problems associated with such systems. Protocols where both parties influence the final derived key are the only way to implement perfect forward secrecy.

In this article, I talked about cryptography. In my next article, I will talk about cryptanalysis. You can find the list of the series on my profile.
Part 4
Hello, in this article of the cryptology basics series, I will talk about what blockchain is, how it works and where it is used.
What is Blockchain?
Blockchain(blockchain) is an ever-growing list of records blocks, linked and secured using cryptography.
Blockchain technology was invented by Satoshi Nakamoto in 2008. Since it has gained great importance in the last few years, many countries have started working to develop the technology and use it in various fields. Blockchain is highly appreciated by FinTech organizations. Practical applications of Blockchain Technology such as Digital Identities, Bitcoin and Ethereum have made it clear that this technology is here to stay. It is a combination of various technologies, including distributed data storage, encryption algorithms and consensus mechanism. Technology has the ability to revolutionize the working models of departments such as finance, banking and cybersecurity departments.
Some of the advantages of blockchain technology:
- No third party intervention.
- Data cannot be modified or deleted.
- Secure data notebook.
- All blocks in the blockchain are timestamped.
- Transparent transactions.
- Distributed to each node in the blockchain.
- There is no risk of duplication or fraud.
How Does Blockchain Work?
Briefly, the blockchain works like this: Each block typically contains transaction data, the hash of the previous block, and a timestamp. By design, a blockchain is resistant to subsequent modification of records. The ledger used is "an open, distributed ledger that can record transactions between two parties in an efficient, verifiable and persistent manner." For use as a distributed ledger, a blockchain is typically managed by a peer-to-peer network for inter-node communication and validating new blocks, collectively tied to a protocol. If the data in any block is wanted to be changed later, the block containing the data and all subsequent blocks will need to be changed. This requires being elected in the node selection for each block write and approval by the majority of the nodes in the network each time before the next node is written. In addition, since it is clear who modified each block, it is possible to detect possible abuse.
Blockchain works on three leading technologies:
1- Cryptography keys
Cryptography keys are of two types â€" Private key and Public key. Both parties in a network have these two keys, thus helping to create a secure digital identity. These keys help in the successful execution of transactions between these two people. This secure identity is the most important aspect of Blockchain technology, called a 'digital signature' when it comes to cryptocurrency.
2- A peer-to-peer network with a shared ledger
The digital signature is then combined with a peer-to-peer network; A large number of individuals acting as authorities and using the digital signature to reach the consensus of others on transactions, among all other matters.
3- A computing tool for sharing the records and transactions of the network
Once they all consent to an agreement, it is confirmed by a mathematical verification that results in a secure transaction between two parties on a shared network.
Thus, in Blockchain technology, users use cryptography keys to perform different digital transactions over a peer-to-peer network.
Where is Blockchain Used?
Blockchain technology can be integrated into multiple domains. The primary use of blockchains today is cryptocurrencies, most notably bitcoin.
Blockchain technology has great potential to transform business operating models in the long term. Blockchain distributed ledger technology is typically a "low cost" technology based on its potential to create new foundations for global economic and social systems.It is a more fundamental technology than a disruptive technology that attacks a traditional business model with a costly solution and quickly consumes incumbents. The use of blockchains promises to bring significant efficiency to global supply chains, financial transactions, ledgers of assets, and decentralized social networks.
Smart contracts
Blockchain-based smart contracts are contracts that can be executed or enforced in whole or in part without human interaction. One of the main purposes of a smart contract is automatic escrow. The IMF believes that blockchains can reduce moral damages and optimize the use of contracts in general. Its legal status is unclear due to lack of widespread use.
Decentralized networks
- The Backfeed project develops a distributed governance system for blockchain-based applications that enables collaborative creation and distribution of value across networks of simultaneously occurring peers.
- The Alexandria project is a blockchain-based Distributed Library.
- Tezos is a blockchain project that governs itself through the vote of token holders. Bitcoin implements the blockchain as a cryptocurrency and payment system. The Ethereum blockchain added a smart contract system on top of a blockchain. The Tezos blockchain will add an autonomy system â€" a decentralized code Development function on top of both the bitcoin and Ethereum blockchains.
Governments and national currencies
Jose Arrieta, Operations Manager for IT Contract Planning at the U.S. General Services Administration, explained at the ACT-IAC (American Technology Council and Industry Advisory Council) Forum in September 2017 that the organization is using blockchain distributed ledger technology through automation to streamline the FASt Lane process of IT Schedule 70 contracts.
The Commercial Clearance Advisory Committee, a subcommittee of U.S. Customs and Border Protection, is working to find practical ways blockchain can be applied to its missions.
Banks
Large parts of the financial industry are implementing distributed ledgers for use in banking, and according to a September 2016 IBM study, this is happening faster than expected. Banks are interested in this technology because it has the potential to speed up back-office settlement systems.
Other financial companies
Credit and debit payment company MasterCard has added three blockchain-based APIs for programmers to enhance both person-to-person (P2P) and business-to-business (B2B) payment systems.
CLS Group is using blockchain technology to increase the number of foreign exchange deals it can extend.
VISA payment systems, Mastercard, Unionpay and SWIFT have announced their plans and developments to use blockchain technology.
Blockchain Types
Currently, there are three types of blockchain networks:
public blockchains, private blockchains and consortium blockchains.
Public blockchains
A public blockchain has absolutely no access restrictions. Anyone with an Internet connection can make transactions and gain validity (that is, participate in the execution of a consensus protocol). Often, such networks offer economic incentives for people who secure them and use a Proof of Stake or Proof of Work algorithm.
Some of the largest, best-known public blockchains are Bitcoin and Ethereum.
Private blockchains
These types of blockchains can be considered a middle ground for companies interested in blockchain technology in general but not comfortable with a level of control offered by public networks. Typically, they try not to incorporate blockchain into accounting and record-keeping procedures without compromising their autonomy and exposing sensitive data to public internet risk.
Consortium blockchains
A consortium blockchain is often said to be semi-decentralized. He is also on leave; But instead of a single organization controlling it, each company can operate a node in such a network. Administrators of a consortium chain restrict users' read rights as they see fit, allowing only a limited number of trusted nodes to execute a consortium protocol.
In this article, I talked about blockchain. You can find the list of the series on my profile.
Part 5
Cryptology Fundamentals:#5 Applications
Hello, in this last article of the cryptology basics series, I will talk about how cryptographic protocols are implemented. I will use the Java programming language during the implementation phase.
MD5 Application
MD5 is a widely used hash function that can produce a fixed-size output (128 bits) for any input data. In Java, you can calculate the MD5 digest of a string or file using the MessageDigest class, which is part of the Java Security API.
Here is an example of how to calculate the MD5 hash of a string in Java:
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public class MD5Example {
public static void main(String[] args) {
String input = "Hello, world!";
String md5Hash = calculateMD5(input);
System.out.println("MD5 hash of '" + input + "' is: " + md5Hash);
}
public static String calculateMD5(String input) {
try {
MessageDigest md = MessageDigest.getInstance("MD5");
byte[] hash = md.digest(input.getBytes());
StringBuilder sb = new StringBuilder();
for (byte b : hash) {
sb.append(String.format("%02x", b));
}
return sb.toString();
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException("MD5 algorithm not available", e);
}
}
}
In this example, we first import the MessageDigest class and define a calculateMD5 method that takes a string input and returns the MD5 value as a string.
Inside the calculateMD5 method, we first create a new instance of the MessageDigest class by using the getInstance method and giving the "MD5" algorithm as a parameter. Next, we call the hash method on the MessageDigest object and pass the input string as a byte array to calculate the MD5 digest.
Finally, we convert the byte array to a string using a StringBuilder object and the String.format method to format each byte as a two-digit hexadecimal number. We then return the resulting string as an MD5 digest.
SHA-1 Implementation
SHA-1 (Secure HashAlgorithm 1) is a widely used hash function that can create a fixed-size output (160 bits) for any input data. In Java, you can calculate the SHA-1 digest of a string or file using the MessageDigest class, which is part of the Java Security API.
Here is an example of how to calculate the SHA-1 hash of a string in Java:
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public class SHA1Example {
public static void main(String[] args) {
String input = "Hello, world!";
String sha1Hash = calculateSHA1(input);
System.out.println("SHA-1 hash of '" + input + "' is: " + sha1Hash);
}
public static String calculateSHA1(String input) {
try {
MessageDigest md = MessageDigest.getInstance("SHA-1");
byte[] hash = md.digest(input.getBytes());
StringBuilder sb = new StringBuilder();
for (byte b : hash) {
sb.append(String.format("%02x", b));
}
return sb.toString();
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException("SHA-1 algorithm not available", e);
}
}
}
In this example, we first import the MessageDigest class and define a calculateSHA1 method that takes a string input and returns the SHA-1 digest as a string.
Inside the calculateSHA1 method, we first create a new instance of the MessageDigest class by using the getInstance method and giving the "SHA-1" algorithm as a parameter. Next, we call the hash method on the MessageDigest object and pass the input string as a byte array to calculate the SHA-1 hash value.
Finally, we convert the byte array to a string by using a StringBuilder object and the String.format method to format each byte as a two-digit hexadecimal number. We then return the resulting string as a SHA-1 digest.
DES Application
DES (Data Encryption Standard) is a symmetric key encryption system that can be used to encrypt and decrypt data.me algorithm. In Java, you can use the Cipher class from the Java Cryptography Architecture (JCA) to implement DES encryption and decryption.
Here is an example of how to encrypt and decrypt a string using DES in Java:
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
public class DESExample {
public static void main(String[] args) throws Exception {
String originalString = "Hello, world!";
String secretKey = "mysecretkey";
// Encrypt the original string
String encryptedString = encrypt(originalString, secretKey);
System.out.println("Encrypted string: " + encryptedString);
// Decrypt the encrypted string
String decryptedString = decrypt(encryptedString, secretKey);
System.out.println("Decrypted string: " + decryptedString);
}
public static String encrypt(String plainText, String secretKey) throws Exception {
Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
SecretKeySpec secretKeySpec = new SecretKeySpec(secretKey.getBytes(StandardCharsets.UTF_8), "DES");
cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);
byte[] encryptedBytes = cipher.doFinal(plainText.getBytes(StandardCharsets.UTF_8));
return Base64.getEncoder().encodeToString(encryptedBytes);
}
public static String decrypt(String encryptedText, String secretKey) throws Exception {
Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
SecretKeySpec secretKeySpec = new SecretKeySpec(secretKey.getBytes(StandardCharsets.UTF_8), "DES");
cipher.init(Cipher.DECRYPT_MODE, secretKeySpec);
byte[] decodedBytes = Base64.getDecoder().decode(encryptedText);
byte[] decryptedBytes = cipher.doFinal(decodedBytes);
return new String(decryptedBytes, StandardCharsets.UTF_8);
}
}
In this example, we first import the required classes and define the encrypt and decrypt methods, which take a plaintext string and a secret key string as input and return the corresponding encrypted or decrypted string.
Inside each method, we first create a Cipher object using the "DES/ECB/PKCS5Padding" conversion string, which specifies the DES encryption algorithm with Electronic Code Book (ECB) mode and PKCS5 padding.
We then create a SecretKeySpec object using the secret key string and the "DES" algorithm and initialize the cipher object with the secret key using the init method with the appropriate mode (Cipher.ENCRYPT_MODE or Cipher.DECRYPT_MODE).
For encryption, we convert the plaintext string into a byte array and call the doFinal method on the cipher object to encrypt the data. Then, we convert the resulting byte array to a base64-encoded string using the Base64 class and return the encrypted string.
For decryption, we decode the base64-encoded string back into a byte array using the Base64 class, call the doFinal method on the cipher object to decrypt the data, and convert the resulting byte array into a string using the appropriate character set (in this case, StandardCharsets.UTF_8). We then return the decrypted string.
AES Implementation
AES (Advanced Encryption Standard) is a symmetric key encryption algorithm that can be used to encrypt and decrypt data. In Java, you can use the Cipher class from the Java Cryptography Architecture (JCA) to implement AES encryption and decryption.
Here is an example of how to encrypt and decrypt a string using AES in Java:
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
public class AESExample {
public static void main(String[] args) throws Exception {
String originalString = "Hello, world!";
String secretKey = "mysecretkey";
// Encrypt the original string
String encryptedString = encrypt(originalString, secretKey);
System.out.println("Encrypted string: " + encryptedString);
// Decrypt the encrypted string
String decryptedString = decrypt(encryptedString, secretKey);
System.out.println("Decrypted string: " + decryptedString);
}
public static String encrypt(String plainText, String secretKey) throws Exception {
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
SecretKeySpec secretKeySpec = new SecretKeySpec(secretKey.getBytes(StandardCharsets.UTF_8), "AES");
cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);
byte[] encryptedBytes = cipher.doFinal(plainText.getBytes(StandardCharsets.UTF_8));
return Base64.getEncoder().encodeToString(encryptedBytes);
}
public static String decrypt(String encryptedText, String secretKey) throws Exception {
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
SecretKeySpec secretKeySpec = new SecretKeySpec(secretKey.getBytes(StandardCharsets.UTF_8), "AES");
cipher.init(Cipher.DECRYPT_MODE, secretKeySpec);
byte[] decodedBytes = Base64.getDecoder().decode(encryptedText);
byte[] decryptedBytes = cipher.doFinal(decodedBytes);
return new String(decryptedBytes, StandardCharsets.UTF_8);
}
}
In this example, we first import the required classes and define the encrypt and decrypt methods, which take a plaintext string and a secret key string as input and return the corresponding encrypted or decrypted string.
Inside each method, we first create a Cipher object using the "AES/ECB/PKCS5Padding" transform string, which specifies the AES encryption algorithm with Electronic Code Book (ECB) mode and PKCS5 padding.
We then create a SecretKeySpec object using the secret key string and the "AES" algorithm and initialize the cipher object with the secret key using the init method with the appropriate mode (Cipher.ENCRYPT_MODE or Cipher.DECRYPT_MODE).
For encryption, we convert the plaintext string into a byte string and call the doFinal method on the cipher object to encrypt the data. Then, we convert the resulting byte array to a base64-encoded string using the Base64 class and return the encrypted string.
For decryption, we decode the base64-encoded string back into a byte array using the Base64 class, call the doFinal method on the cipher object to decrypt the data, and convert the resulting byte array into a string using the appropriate character set (in this case, StandardCharsets.UTF_8). We then return the decrypted string.
RSA Implementation
RSA (Rivestâ€"Shamirâ€"Adleman) is a public key encryption algorithm that can be used to securely encrypt and decrypt data. In Java, you can use the KeyPairGenerator and Cipher classes from the Java Cryptography Architecture (JCA) to implement RSA encryption and decryption.
Here is an example of how to create an RSA key pair in Java, encrypt a string using the public key, and decrypt the encrypted string:
import javax.crypto.Cipher;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.util.Base64;
public class RSAExample {
public static void main(String[] args) throws Exception {
String originalString = "Hello, world!";
// Generate an RSA key pair
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
keyPairGenerator.initialize(2048);
KeyPair keyPair = keyPairGenerator.generateKeyPair();
// Get the public and private keys from the key pair
byte[] publicKeyBytes = keyPair.getPublic().getEncoded();
byte[] privateKeyBytes = keyPair.getPrivate().getEncoded();
// Encrypt the original string using the public key
byte[] encryptedBytes = encrypt(originalString.getBytes(), publicKeyBytes);
String encryptedString = Base64.getEncoder().encodeToString(encryptedBytes);
System.out.println("Encrypted string: " + encryptedString);
// Decrypt the encrypted string using the private key
byte[] decryptedBytes = decrypt(Base64.getDecoder().decode(encryptedString), privateKeyBytes);
String decryptedString = new String(decryptedBytes);
System.out.println("Decrypted string: " + decryptedString);
}
public static byte[] encrypt(byte[] plainBytes, byte[] publicKeyBytes) throws Exception {
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.ENCRYPT_MODE, KeyFactory.getInstance("RSA").generatePublic(new X509EncodedKeySpec(publicKeyBytes)));
return cipher.doFinal(plainBytes);
}
public static byte[] decrypt(byte[] encryptedBytes, byte[] privateKeyBytes) throws Exception {
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.DECRYPT_MODE, KeyFactory.getInstance("RSA").generatePrivate(new PKCS8EncodedKeySpec(privateKeyBytes)));
return cipher.doFinal(encryptedBytes);
}
}
In this example, we first import the required classes and define the encrypt and decrypt methods, which take a byte array of plaintext or encrypted data and a byte array of public or private key as input and return the corresponding encrypted or decrypted byte array. .
In the main method, we first create an RSA key pair using the KeyPairGenerator class with the "RSA" algorithm and a key size of 2048 bits. We then extract the public and private keys from the key pair as byte arrays using the getEncoded method.
For encryption, we call the encrypt method with the original string converted to a byte array and the public key byte array as input. We create a Cipher object using the "RSA" algorithm in the Encrypt method and initialize it with the public key using the appropriate mode (Cipher.ENCRYPT_MODE) using the init method. Next, we call the doFinal method on the cipher object to encrypt the data and return the resulting byte array.
For decryption, we call the decrypt method with the base64-decrypted encrypted string converted to a byte array and the private key byte array as input. Inside the Decrypt method, we create another Cipher object using the "RSA" algorithm and initialize it with the private key using the appropriate mode and init method.
ECDH Application
ECDH (Elliptic Curve Diffie-Hellman) is a key agreement protocol that allows two parties to establish a shared secret over an unsecured communication channel. In Java, you can use the KeyAgreement and KeyPairGenerator classes from the Java Cryptography Architecture (JCA) to implement ECDH key exchange using elliptic curve cryptography.
Here's an example of creating an ECDH key pair, performing a key exchange with another party, and deriving a shared key using Java:
import javax.crypto.KeyAgreement;
import javax.crypto.SecretKey;
import javax.crypto.spec.ECGenParameterSpec;
import java.security.*;
import java.security.spec.ECParameterSpec;
import java.security.spec.ECPublicKeySpec;
import java.security.spec.InvalidKeySpecException;
public class ECDHExample {
public static void main(String[] args) throws Exception {
// Generate an ECDH key pair
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("EC");
ECGenParameterSpec ecGenParameterSpec = new ECGenParameterSpec("secp256r1");
keyPairGenerator.initialize(ecGenParameterSpec);
KeyPair keyPair = keyPairGenerator.generateKeyPair();
PrivateKey privateKey = keyPair.getPrivate();
PublicKey publicKey = keyPair.getPublic();
// Simulate the other party by generating its own ECDH key pair
KeyPair otherKeyPair = keyPairGenerator.generateKeyPair();
PrivateKey otherPrivateKey = otherKeyPair.getPrivate();
PublicKey otherPublicKey = otherKeyPair.getPublic();
// Perform key exchange with the other party
KeyAgreement keyAgreement = KeyAgreement.getInstance("ECDH");
keyAgreement.init(privateKey);
keyAgreement.doPhase(otherPublicKey, true);
// Derive the shared secret
byte[] sharedSecret = keyAgreement.generateSecret();
// Simulate the other party deriving the shared secret using its private key
KeyFactory keyFactory = KeyFactory.getInstance("EC");
ECParameterSpec ecParameterSpec = ((ECPublicKeySpec) otherPublicKey.getKeySpec(ECPublicKeySpec.class)).getParams();
PublicKey simulatedOtherPublicKey = keyFactory.generatePublic(new ECPublicKeySpec(((java.security.spec.ECPoint) otherPublicKey).getW(), ecParameterSpec));
KeyAgreement simulatedKeyAgreement = KeyAgreement.getInstance("ECDH");
simulatedKeyAgreement.init(otherPrivateKey);simulatedKeyAgreement.doPhase(publicKey, true);
byte[] simulatedSharedSecret = simulatedKeyAgreement.generateSecret();
// Compare the two shared secrets (should be equal)
System.out.println("Shared secret: " + bytesToHex(sharedSecret));
System.out.println("Simulated shared secret: " + bytesToHex(simulatedSharedSecret));
System.out.println("Shared secrets match: " + bytesToHex(sharedSecret).equals(bytesToHex(simulatedSharedSecret)));
}
public static String bytesToHex(byte[] bytes) {
StringBuilder sb = new StringBuilder();
for (byte b : bytes) {
sb.append(String.format("%02X", b));
}
return sb.toString();
}
}
In this example, we first import the required classes and define a bytesToHex method to convert a byte array to a hexadecimal string.
Inside the main method, we first create an ECDH key pair using the KeyPairGenerator class with the "EC" algorithm and the "secp256r1" elliptic curve parameter property. We then extract the private and public keys from the key pair.
We simulate the counterparty by creating its own ECDH key pair using the same curve parameters.
ECDSA Application
ECDSA (Elliptic Curve Digital Signature Algorithm) is a digital signature algorithm based on elliptic curve cryptography. In Java, you can use the Signature and KeyPairGenerator classes from the Java Cryptography Architecture (JCA) to implement ECDSA.
Here's an example of how to create an ECDSA key pair using Java, sign a message with the private key, and verify the signature with the public key:
import java.security.*;
import java.security.spec.ECGenParameterSpec;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
public class ECDSAExample {
public static void main(String[] args) throws Exception {
// Generate an ECDSA key pair
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("EC");
ECGenParameterSpec ecGenParameterSpec = new ECGenParameterSpec("secp256r1");
keyPairGenerator.initialize(ecGenParameterSpec);
KeyPair keyPair = keyPairGenerator.generateKeyPair();
PrivateKey privateKey = keyPair.getPrivate();
PublicKey publicKey = keyPair.getPublic();
// Sign a message with the private key
byte[] message = "Hello, world!".getBytes();
Signature signature = Signature.getInstance("SHA256withECDSA");
signature.initSign(privateKey);
signature.update(message);
byte[] signatureBytes = signature.sign();
// Verify the signature with the public key
Signature verifier = Signature.getInstance("SHA256withECDSA");
verifier.initVerify(publicKey);
verifier.update(message);
boolean signatureValid = verifier.verify(signatureBytes);
System.out.println("Signature valid: " + signatureValid);
}
}
In this example, we first import the necessary classes.
Inside the main method, we generate an ECDSA key pair using the KeyPairGenerator class with the "EC" algorithm and the elliptic curve parameter property "secp256r1". We extract the private and public keys from the key pair.
We then create a message to sign and use the Signature class to sign the message with the private key. To use SHA-256 as the hash function, we specify the "SHA256withECDSA" algorithm.
Next, we create a validator object using the Signature class and initialize it with the public key. We update the validator with the same message and verify the signature using the verification method. We compare the result to true to determine whether the signature is valid.
Note that in a real-world scenario, you will typically transmit the signed message and the public key separately to the verifier to ensure that the signature has not been tampered with during transmission.
In this article, I made cryptology applications with Java. You can access the article series from my profile. Don't forget to like and follow.
Part 2
Cryptology Fundamentals:#3 Cryptanalysis
Hello, in this article of the cryptology basics series, I will talk about what cryptanalysis is, password cracking techniques and social engineering methods.
Cryptanalysis Overview
Cryptanalysis is the science of breaking and deciphering crypto systems. It is the branch of cryptology that investigates the decryption of encrypted texts. Cryptanalysis is used to find unknown keys.

Cryptanalysis; We can divide Application Attacks into three areas: classical cryptanalysis and social engineering. Now let's look at these areas and the methods used.
Application Attacks
Cryptanalysis methods that attempt to obtain the secret key through reverse engineering or password attacks are types of attacks.
Brute-Force Attacks
This type of password attack uses trial and error methods to guess the target user's password information. The attacker tries as many permutations as possible to correctly guess the user's password. Although it is a relatively old method that requires a lot of patience and time, a brute force attack is still one of the most used methods because it is automatic and straightforward.

There are several types of brute force attacks:
1. Simple brute force attacks: Uses data about a user to guess the most likely password. This technique is used for simple passwords, such as those containing a combination of pet name-year and birth.
2. Credential stuffing: Involves the use of previously compromised login combinations maliciously obtained from vulnerable websites. These types of attacks take advantage of target users' tendency to reuse username-password combinations across multiple services.
3. Reverse brute force attacks: It starts with a known password and then looks for usernames that match that password. Since threat actors often have access to multiple databases of leaked credentials, it is easy to identify common passwords within a given group of users.
Dictionary Attacks
This attack method uses a predefined list of words that are likely to be used as passwords by a particular target network.
The predefined list is created from a website user's behavioral patterns and passwords obtained from previous data breaches. Lists common password combinations by case;
- By changing
- By adding numeric suffixes and prefixes
- Using common expressions
is created. These lists are passed to tools that attempt to authenticate against a list of known usernames.
Here are the tools that can be used to create a password list.
Password Spraying Attacks
In this attack, the hacker attempts to authenticate using the same password across several accounts before switching to another password. Since most website users set simple passwords, password spraying is the most effective technique.
Attackers often use the password spraying attack on websites where administrators set a standard default password for new users and unregistered accounts.
Keylogging
When conducting a Keylogging attack, the attacker installs keyboard monitoring software on the user's computer to record the keys the user secretly types. A keylogger records all the information users type into login forms and then sends them to the malicious attacker.
Computer Forensics
From the memory, disk or processor of a system to which we have physical access; It involves obtaining the secret key using various forensic methods such as string analysis and signal measurement. In cases where I do not have physical access, such as a remote server, we do not need to worry about this attack.
Application Attacks Tools
- CrackStation
- John the Ripper
- Hashcat
- Medusa
- Hydra
- Brutus
- RainbowCrack
- L0phtCrack
- OphCrack
Classical Cryptanalysis
Classical cryptanalysis is the science of recovering the plaintext from its ciphertext or, alternatively, finding the key from its ciphertext. It uses mathematical analysis that takes advantage of the internal structure of the encryption method.
Encryption Decryption
An encryption process consists of 3 elements. These are: clear text, encrypted text and key. If we have any two of these elements, we can easily find the third. However, the main function of cryptanalysis is the ability to find others when only the ciphertext is available. It uses various mathematical methods for this.
These methods are:
- Known Plaintext Analysis (KPA): In this type of attack, some plaintext-ciphertext pairs are already known. The attacker maps them to find the encryption key. This attack is easier to use because a lot of information is already available.
- Chosen Plaintext Analysis (CPA): In this type of attack, the attacker selects random plaintexts and retrieves the corresponding ciphertexts and tries to find the encryption key. Like KPA, it is very simple to implement, but its success rate is quite low.
- Ciphertext Analysis Only (COA): In this type of attack, only some ciphertexts are known and the attacker tries to find the corresponding encryption key and plaintext. It is the most difficult to implement, but the most likely attack since only ciphertext is required.
- Adaptive Selected Plaintext Analysis (ACPA): This attack is similar to CPA. Here the attacker, after having the ciphertexts for some texts, requests the ciphertexts of additional plaintexts.
- Birthday attack: This attack exploits the possibility of two or more people in a group of people sharing the same birthday. In cryptography, this attack is used to find collisions in a hash function.
- Differential cryptanalysis: This type of attack involves comparing pairs of plaintexts and their corresponding ciphertexts to find patterns in the encryption algorithm. It can be effective against block ciphers with certain properties.
- Integral cryptanalysis: It is a method used on block cipher methods based on Replacement-Scrambling functions.
Social Engineering
No matter how strong the crypto system we have established, risks arising from human factors should not be ignored. Bribery, blackmail, deception or classic espionage can be used to obtain a secret key. For example, holding a gun to a person's head and forcing them to tell the password can be quite successful. Another less violent attack is social engineering techniques such as calling the people we want to attack and saying, "We're calling from your company's IT department. We need your password for important software updates." It is surprising that there are no small number of people who are naive enough to actually give their passwords in such cases.
The attacker is always looking for the weakest link in your crypto system. For this, we need to choose strong algorithms and ensure that social engineering and application attacks are impractical. Both application attacks and social engineering attacks can be quite powerful in practice.
Phishing Attacks
It involves a social engineering technique in which the attacker disguises himself as a trusted site by sending a malicious link to the victim. Once the victim assumes they are authenticating with a legitimate web server, they click on that link, providing the attacker with their account information. In this way, the attacker obtains the account information of the target user, and the victim is phished.
Aside from identity theft, phishing attacks enable an attacker to obtain a user's permissions, allowing them to compromise deeper components of the system before the attack is detected. In phishing attacks, attackers often use multiple methods to trick the user into clicking the malicious link:
- DNS cache poisoning: Attackers exploit the application's DNS server to redirect user requests to a malicious site with a similar-sounding domain name.It exploits the security vulnerabilities in its mind.
- URL hijacking/typo: The attacker creates a real-looking URL with subtle differences from the website they want to impersonate. The attack relies on users making typos, so they land on the malicious page.
- Tabbing: The attacker rewrites unattended browser tabs with malicious sites disguised as legitimate web pages.
- UI fix/iFrame overlay: Using transparent layers, the attacker places a link to the malicious page over a legitimate, clickable button.
- Clone phishing : In this attack, the attacker sends a copy of a legitimate email to malicious sites where the links in the original email are replaced with URLs.
In this article, I talked about cryptanalysis. In my next article, I will talk about cryptography. You can find the list of the series on my profile.
Part 3
Cryptology Fundamentals:#2 Cryptography
Hello, in this article of the cryptology basics series, I will talk about what cryptography is, encryption techniques and cryptographic protocols.
Cryptography Overview
Cryptography is the science of secret writing for the purpose of hiding the meaning of a message. Cryptography is a set of mathematical methods and is intended to provide conditions such as confidentiality, authenticity, authentication, and prevention of false rejection necessary for the security of important information. These methods aim to protect the information â€" and therefore the interests of the sender, receiver, carrier of the information, its subjects, and any other parties â€" from active attacks or passive perceptions that may be encountered during the transmission and storage of information.

Cryptography; We can divide it into 3 areas: symmetric encryption, asymmetric encryption and cryptographic protocols. Now let's look at these areas and the methods used.

Basic Classification Diagram for Cryptographic Algorithms
Symmetric Encryption
Symmetric Encryption** is an encryption technique where both parties use the same encryption and decryption method. There is only one common secret key to be used in this encryption method.
All cryptography from ancient times until 1976 was based solely on symmetric methods, and symmetric ciphers are still widely used. It is especially useful for encryption and integrity control of messages.

Symmetric Encryption
In the computer system; All data such as text, images, music are expressed as 1â€"0s, and each 1â€"0 is called a bit.
Symmetric encryption is divided into block ciphers and stream ciphers. Although stream cipher and block cipher are symmetric encryption techniques, there are some important differences. While block ciphers encrypt fixed-length blocks of bits, stream ciphers combine plaintext bits into a text encryption stream using the XOR operation.

Stream Encryption
In stream encryption, bits are encrypted individually. Each bit is encrypted by XORing the bit coming from the bit stream generator. If the encrypted text is XORed with the cipher stream, the plain text is found and decrypted. For this reason, in the stream encryption technique, there is no need for different algorithms for encryption and decryption operations, these operations are performed with the same algorithm.

XOR operation
The most important point in stream encryption algorithms is the bit stream generator. The bitstream generator creates a bitstream based on the key given to it. The complexity and randomness of this bitstream are of great importance to the reliability of the encryption. At this point, different stream encryption algorithms with different bit stream generators have been developed.
ChaCha20
ChaCha20 algorithm is a stream encryption algorithm. Supports 128 and 256 bits. It has similar features to its predecessor Salsa20. It has a primitive function consisting of 12 or 20 different rounds. It was standardized by the IETF in RFC 7539 and is among the most used algorithms today because it is much more efficient and faster than AES in software applications.
Google has a big part in making ChaCha20 so popular. Until a few years ago, Google used AES-GCM as the symmetric encryption algorithm for Chrome and Android. However, due to the use of ARM-based processors in mobile devices and the lack of AES configurations in these processors as in Intel-based processors, encryption was relatively slow. For this reason, Google was working on a more up-to-date, secure and faster encryption algorithm.

ChaCha20-Poly1305
The jumping off point for ChaCha20 was when the android version of Chrome started using ChaCha20 for encryption and Poly1305 for authentication. The main reason for this was that ChaCha20 achieved three times the performance of slightly older protocols such as AES.
ChaCha20, HTTPS connectionsIt is widely used for SSH connections and managing servers. Even the popular WireGuard VPN protocol uses only ChaCha20 for symmetric data encryption. It is very likely that we will soon see ChaCha20 in IPsec connections as well.
Block Cipher
In block ciphering, an entire block of plaintext bits is encrypted at a time. This requires a key bit block that is the same length as the text bit block. In practice, keys with a block length of 128 bits (16 bytes) or 64 bits (8 bytes) are used. The longer the key length, the more reliable the encryption process.
In block ciphering, encryption and decryption algorithms are different algorithms. The decryption algorithm does the exact opposite of what is done in the encryption algorithm.

Block Cipher
There are two key features that make block cipher algorithms reliable. These are the concepts of confusion and diffusion
**Confusion is an encryption process in which the relationship between the key and the ciphertext is hidden.
**Diffusion is an encryption process in which the effect of one plaintext symbol is spread across many ciphertext symbols in order to hide statistical properties of the plaintext.
Algorithms that perform only propagation or only confusion are not secure. However, strong passwords can be created by using a combination of such processes. Today's block cipher algorithms consist of loops that repeatedly apply these operations to the data.
There are two standardized algorithms widely used in the block cipher technique. These; advanced encryption standard (AES) and data encryption standard (DES) algorithms.
DES
Data Encryption Standard (DES) has been by far the most popular block cipher method for most of the last 30 years. Although DES is not considered secure today because its key length is very short, it is still used in old applications.
DES is an algorithm that encrypts 64-bit blocks with a 56-bit key. This algorithm completes the encryption process in 16 rounds, all performing the same operation. A different subkey is used in each round, and all subkeys are derived from the main key k.

If we look in more detail at the transactions made in each round, we encounter the Feistel structure of the DES algorithm (also known as the Feistel network). If this feistel structure is carefully designed, very strong passwords can be created. In addition to their cryptographic power, an advantage of Feistel networks is that encryption and decryption are almost the same process.

The two fundamental properties of passwords mentioned above, namely hashing and diffusion, are implemented within the f-function. Round is taken as the number of rounds and K1, K2,..KN are taken as subkeys for rounds 1,2,..,n respectively. Then, the Ciphertext blocks are divided into 2 equal parts, L and R, and processed within the function. Then, input R is output as L, input L is output as R, and this process is repeated n times.
The diagram shows both encryption and decryption. It is worth noting that the subkey order is reversed for decryption; This is the only difference between encryption and decryption.
Once the f-function is securely designed, the security of the Feistel cipher increases with the number of keys and block length. The more the number of keys, the more the number of rounds and the more confusion and diffusion we get. Likewise, the longer the block length, the longer the password spreads and the harder it is to crack.
####AES
Advanced Encryption Standard (AES) is the most widely used symmetric cipher today. Software that incorporates AES includes Internet security standard IPsec, TLS, Wi-Fi encryption standard IEEE 802.11i, secure shell network protocol SSH (Secure Shell), Internet telephony Skype, and numerous security products worldwide.
Unlike DES, the AES algorithm does not have a Feistel structure. Feistel networks do not encrypt an entire block per iteration, for example in DES 64/2 = 32 bits are encrypted in one round. AES, on the other hand, encrypts all 128 bits in one round. Therefore, the AES algorithm has a relatively small number of rounds.

AES algorithm
In the image above, the plaintext is x and the ciphertext is y.rak and number of rounds are shown as nr.
AES consists of layers. Each layer processes all 128 bits of the block. There are three different types of layers. These;
Key Addition(AddRoundKey) layer: In the key generator, the 128-bit subkey derived from the main key is XORed with state(x).
SubBytes layer:* Each byte in the state matrix is ​​updated according to a table and with a non-linear transformation.
Diffusion layer: Provides diffusion over text bits. It consists of two sublayers, both of which perform linear operations:
- **Row Shift (ShiftRows) layer, each row is shifted circularly a certain number of times.
- The Column Mixing (MixColumn) layer mixes the four-byte blocks in each column. Last round, the MixColumn transform is not used.
In the AES encryption algorithm, the reverse process is done to decrypt.
Asymmetric Encryption
Asymmetric Encryption is an encryption technique in which a user has a private key and also a public key. Asymmetric algorithms can be used for digital signatures, key generation, and classical data encryption.
It was introduced in 1976 as a completely different type of cipher by Whitfield Diffie, Martin Hellman and Ralph Merkle. Also known as public key encryption.

Asymmetric Encryption
Asymmetric cryptography, also known as public key cryptography, is a fairly new encryption technique. It was introduced in 1976 by Whitfield Diffie, Martin Hellman and Ralph Merkle. In asymmetric encryption, each user has a private key and a public key. The way these keys are used is as follows:
- Message + public key = Encrypted message
- Encrypted message + secret key = Decrypted message
- Message + secret key = Signed message
- Signed message + public key = Authentication
In asymmetric encryption, a message encrypted with a user's public key can only be decrypted with that user's private key. This method is used to send a message to that user. If a user has encrypted the message with his private key, we can decrypt this message with that user's public key. This method is also used in authentication, if the message can be decrypted with that user's public key, his identity is confirmed.
Before moving on to the actual public key encryption algorithms, let's take a look at the mathematical basis of these algorithms.
Public Key Algorithm Families
Integer-Factorization Schemes: Many public-key schemes rely on the fact that it is difficult to factor large integers. The most well-known representative of this family of algorithms is RSA.
Discrete Logarithm Schemes: Based on mathematics known as the discrete logarithm problem in finite fields. Examples of this are Diffie-Hellman key exchange, Elgamal encryption or Digital Signature Algorithm (DSA).
Elliptic Curve (EC) Schemes: A generalization of discrete logarithms are elliptic curve public key schemes. The most popular examples include Elliptic Curve Diffie-Hellman key exchange (ECDH) and Elliptic Curve Digital Signature Algorithm (ECDSA).
The first two families appeared in the mid-1970s. Elliptic curves were introduced in the mid-1980s. There are no known attacks against either scheme if parameters and key lengths are chosen carefully.
RSA
RSA is an encryption technique developed considering the algorithmic difficulty of factoring very large integers. There are many applications where RSA is used, but in practice it is most commonly used for digital signatures, digital certificates, and encryption of small pieces of data. Additionally, RSA is the most widely used asymmetric encryption scheme today.
It should be noted that RSA encryption is not intended to replace symmetric ciphers, as it is several times slower than symmetric ciphers such as AES. This is due to the many calculations involved in performing RSA (or any other public key algorithm). Therefore, the main use of the encryption feature is to securely exchange a key with a symmetric cipher (key transfer). In practice, RSA is often used in conjunction with a symmetric cipher such as AES, where the symmetric cipher does the actual bulk data encryption.
The underlying one-way function of RSA is the integer factorization problem:
 Multiplying two large prime numbers is computationally easy (you can actually do it with paper and pencil).niz), but it is very difficult to factor the resulting product. Euler's theorem and Euler's phi function play important roles in RSA. Now, let's look at how encryption, decryption, and key generation work with RSA.

RSA encryption algorithm
e: encryption exponent, d: decryption exponent, n: length
Modular computations play an important role in RSA encryption and decryption. In practice x, y, n and d are very long numbers (usually 1024 bits).
A distinctive feature of all asymmetric schemes is that there is a setup phase in which the public and private key are calculated. Depending on the public key scheme, key generation can be quite complex. Let's take a look at the steps involved in calculating the public and private key for an RSA encryption system:
- N = p.q
 Two different and large prime numbers are determined, which will form the very large integer that we will denote by N. These numbers are called p and q. - φ(N) = (p-1)(q-1)
 The totient value of number N is calculated. Totient is a function in number theory that indicates the number of numbers that are smaller than an integer and prime to that number. - 1 < e < φ(N) and GCF(e, φ(N)) = 1
 As can be understood from the mathematical expression above, an integer between 1 and the Totient value, which is prime between the Totient value and the Totient value, is selected and named e. Choosing a small number of e to be chosen here provides performance gains when performing operations such as mod and exponentiation, but in some cases it reduces security. - d.e ≡ 1 (mod φ(N)
 The number d that provides equivalence and will be used to create the secret key is found. The process to be done here is to find the inverse of the number e in mod φ(N).
We have obtained all the values necessary to create the public and private key. Provided that the numbers (p,q, φ(N)) used in calculating the number d constituting the private key remain secret, the pair (N,e) is the public key; The (N,d) pair constitutes the secret key.
As you can see, doing these operations can be very long and tiring. For this purpose, some practical methods are used in advanced systems. When designing the RSA scheme, if the e and d values are too large, it may cause slow encryption. On the other hand, if these values are too small, this brings security problems.
Protocols
Cryptographic Protocols are encryption methods created by applying and standardizing cryptographic algorithms. Symmetric and asymmetric algorithms are the building blocks of secure Internet communications. A protocol defines how to use these algorithms.
Digital signature
Digital signature is a legal authentication method used for authentication purposes in the electronic environment. It can be roughly defined as a signature made electronically. As with traditional handwritten signatures, only the person creating the digital message must be able to produce a valid signature. To achieve this with cryptographic primi-262 10 Digital Signatures we need to implement public key cryptography. The basic idea is that the person signing the message uses a private key and the receiving party uses the matching public key. The principle of the digital signature scheme is shown in the figure.

Digital Signature
The key feature of digital signatures is this: Since a valid signature can only be calculated with the signer's private key, a signed message can be unambiguously traced back to its origin. Only the signer has the authority to create a signature in his or her own name. Therefore, we can prove that the signing party actually created the message.
 Each of three popular families of public key algorithms, namely integer factorization, discrete logarithms, and elliptic curves, allow us to create digital signatures.
Summary Functions
Hash functions, also known as hash functions, are an important cryptographic protocol. It is extremely useful and appears in almost all information security applications. For a given message, the message digest or hash value can be viewed as a message fingerprint, that is, a unique representation of a message. Unlike other crypto algorithms, hash functions do not have a key.

Summary Function
Hash functions are mathematical functions that convert a numerical input value into another compressed numerical value.Zion. The input of the hash function is of arbitrary length, but the output is always fixed length. The values ​​returned by a hash function are called message digests or simply hash values. Regardless of the input, all output strings produced by a given hash function are the same length. The length is defined by the type of hashing technology used. The output strings are created from a sequence of characters defined in the hash function.
The uses of hash functions in cryptography are very diverse. Hash functions are an important part of digital signature schemes and message authentication codes. It is also widely used for other cryptographic applications, for example, storing password hashes or key derivation.
Features of hash functions
- One-way: Once a hash value is created, it should be impossible to convert it back to the original data.
- Conflict-free: For a hash function to be conflict-free, the hash value of two different data values ​​must not be the same. In other words, each input sequence must produce a unique output sequence.
- Fast: If a hash function takes too long to calculate hash values, it is of little use. Hash functions must therefore be very fast.
Popular Hash Functions
Message Digest (MD)
The MD family consists of hash functions MD2, MD4, MD5 and MD6. Adopted as Internet Standard RFC 1321. It is a 128-bit hash function. The most popular member of the family is MD5.
MD5 was the most popular and widely used hash function for many years. MD5 digests are widely used in the software world to provide assurance about the integrity of the transferred file. For example, file servers often provide a pre-computed MD5 hash for files, so a user can compare the hash of the downloaded file with the provided value. In 2004, conflicts were found in MD5. An analytics attack using the computer cluster was reported to be successful in just an hour. This collision attack resulted in MD5 being an unreliable algorithm and therefore its use is no longer recommended.
Secure Hash Function (SHA)
The SHA family consists of four SHA algorithms; SHA-0, SHA-1, SHA-2 and SHA-3. Although they are from the same family, they have structurally different algorithms.
The original version is SHA-0, a 160-bit hash function, and was published by the National Institute of Standards and Technology (NIST) in 1993. It had a few weaknesses and did not become very popular. Later in 1995, SHA-1 was designed to fix the alleged weaknesses of SHA-0.
SHA-1 is the most widely used of the existing SHA hash functions. It is used in many commonly used applications and protocols, including Secure Sockets Layer (SSL) security. In 2005, a method was found for SHA-1 to expose conflicts within the practical time frame, making the long-term usability of SHA-1 questionable.
The SHA-2 family has four SHA variants, SHA-224, SHA-256, SHA-384, and SHA-512, depending on the number of bits in the hash values. No successful attack on the SHA-2 hash function has yet been reported. Although SHA-2 is a powerful hash function and is significantly different, its basic design is still similar to that of SHA-1. Therefore, NIST has called for new hash function designs.
In October 2012, NIST selected the Keccak algorithm as the new SHA-3 standard. Keccak offers many advantages to its users, such as efficient performance and strong resistance to attacks.
RIPEMD
RIPEMD is the abbreviation for RACE Integrity Primitives Assessment Message Digest. This set of hash functions was designed by the open research community and is commonly known as a family of European hash functions. The family has 3 members. These; RIPEMD, RIPEMD-128 and RIPEMD-160. 256 and 320 bit versions of this algorithm are also available.
The original RIPEMD (128 bit) was based on the design principles used in MD4 and security issues were found. RIPEMD 128-bit version came as a quick fix to overcome vulnerabilities in the original RIPEMD.
RIPEMD-160 is an improved version and is the most used version in the family. The 256- and 320-bit versions reduce the likelihood of conflicts, but do not have higher security levels compared to RIPEMD-128 and RIPEMD-160, respectively.
####Whirlpool
Whirlpool, 512 bIt is a hash function. It is derived from a modified version of the Advanced Encryption Standard (AES). One of the designers was Vincent Rijmen, co-creator of AES. Three versions of Whirlpool have been released. These; They are WHIRLPOOL-0, WHIRLPOOL-T and WHIRLPOOL.
Key Distribution Protocol
Key da protocol is an encryption protocol in which some secret values are shared among several members of a group. The secret value can also be used, for example, as a secret session key for a secure communication channel between members of the group. Roughly speaking, key distribution protocol deals with creating a shared key between two or more parties. For this, key transport or key agreement methods can be used. A key transport protocol is a technique by which one party securely transfers a secret value to others. In a key agreement protocol, two (or more) parties derive the public key, with all parties contributing the key. Ideally, neither party can control what the final public key will be.

Key Agreement
In cryptography, a key agreement protocol is a protocol in which two or more parties can agree on a key in a way that both affects the outcome. If done properly, this prevents unintended third parties from imposing a choice on contracting parties. In practice, advanced protocols do not reveal to any eavesdropping party what key has been agreed upon.
Key Transport
In many key transport protocols, one party simply generates the key and sends that key to the other party; the other side has no influence on the key.
Using a key agreement protocol avoids some of the key distribution problems associated with such systems. Protocols where both parties influence the final derived key are the only way to implement perfect forward secrecy.

In this article, I talked about cryptography. In my next article, I will talk about cryptanalysis. You can find the list of the series on my profile.
Part 4
Hello, in this article of the cryptology basics series, I will talk about what blockchain is, how it works and where it is used.
What is Blockchain?
Blockchain(blockchain) is an ever-growing list of records blocks, linked and secured using cryptography.
Blockchain technology was invented by Satoshi Nakamoto in 2008. Since it has gained great importance in the last few years, many countries have started working to develop the technology and use it in various fields. Blockchain is highly appreciated by FinTech organizations. Practical applications of Blockchain Technology such as Digital Identities, Bitcoin and Ethereum have made it clear that this technology is here to stay. It is a combination of various technologies, including distributed data storage, encryption algorithms and consensus mechanism. Technology has the ability to revolutionize the working models of departments such as finance, banking and cybersecurity departments.
Some of the advantages of blockchain technology:
- No third party intervention.
- Data cannot be modified or deleted.
- Secure data notebook.
- All blocks in the blockchain are timestamped.
- Transparent transactions.
- Distributed to each node in the blockchain.
- There is no risk of duplication or fraud.
How Does Blockchain Work?
Briefly, the blockchain works like this: Each block typically contains transaction data, the hash of the previous block, and a timestamp. By design, a blockchain is resistant to subsequent modification of records. The ledger used is "an open, distributed ledger that can record transactions between two parties in an efficient, verifiable and persistent manner." For use as a distributed ledger, a blockchain is typically managed by a peer-to-peer network for inter-node communication and validating new blocks, collectively tied to a protocol. If the data in any block is wanted to be changed later, the block containing the data and all subsequent blocks will need to be changed. This requires being elected in the node selection for each block write and approval by the majority of the nodes in the network each time before the next node is written. In addition, since it is clear who modified each block, it is possible to detect possible abuse.
Blockchain works on three leading technologies:
1- Cryptography keys
Cryptography keys are of two types â€" Private key and Public key. Both parties in a network have these two keys, thus helping to create a secure digital identity. These keys help in the successful execution of transactions between these two people. This secure identity is the most important aspect of Blockchain technology, called a 'digital signature' when it comes to cryptocurrency.
2- A peer-to-peer network with a shared ledger
The digital signature is then combined with a peer-to-peer network; A large number of individuals acting as authorities and using the digital signature to reach the consensus of others on transactions, among all other matters.
3- A computing tool for sharing the records and transactions of the network
Once they all consent to an agreement, it is confirmed by a mathematical verification that results in a secure transaction between two parties on a shared network.
Thus, in Blockchain technology, users use cryptography keys to perform different digital transactions over a peer-to-peer network.
Where is Blockchain Used?
Blockchain technology can be integrated into multiple domains. The primary use of blockchains today is cryptocurrencies, most notably bitcoin.
Blockchain technology has great potential to transform business operating models in the long term. Blockchain distributed ledger technology is typically a "low cost" technology based on its potential to create new foundations for global economic and social systems.It is a more fundamental technology than a disruptive technology that attacks a traditional business model with a costly solution and quickly consumes incumbents. The use of blockchains promises to bring significant efficiency to global supply chains, financial transactions, ledgers of assets, and decentralized social networks.
Smart contracts
Blockchain-based smart contracts are contracts that can be executed or enforced in whole or in part without human interaction. One of the main purposes of a smart contract is automatic escrow. The IMF believes that blockchains can reduce moral damages and optimize the use of contracts in general. Its legal status is unclear due to lack of widespread use.
Decentralized networks
- The Backfeed project develops a distributed governance system for blockchain-based applications that enables collaborative creation and distribution of value across networks of simultaneously occurring peers.
- The Alexandria project is a blockchain-based Distributed Library.
- Tezos is a blockchain project that governs itself through the vote of token holders. Bitcoin implements the blockchain as a cryptocurrency and payment system. The Ethereum blockchain added a smart contract system on top of a blockchain. The Tezos blockchain will add an autonomy system â€" a decentralized code Development function on top of both the bitcoin and Ethereum blockchains.
Governments and national currencies
Jose Arrieta, Operations Manager for IT Contract Planning at the U.S. General Services Administration, explained at the ACT-IAC (American Technology Council and Industry Advisory Council) Forum in September 2017 that the organization is using blockchain distributed ledger technology through automation to streamline the FASt Lane process of IT Schedule 70 contracts.
The Commercial Clearance Advisory Committee, a subcommittee of U.S. Customs and Border Protection, is working to find practical ways blockchain can be applied to its missions.
Banks
Large parts of the financial industry are implementing distributed ledgers for use in banking, and according to a September 2016 IBM study, this is happening faster than expected. Banks are interested in this technology because it has the potential to speed up back-office settlement systems.
Other financial companies
Credit and debit payment company MasterCard has added three blockchain-based APIs for programmers to enhance both person-to-person (P2P) and business-to-business (B2B) payment systems.
CLS Group is using blockchain technology to increase the number of foreign exchange deals it can extend.
VISA payment systems, Mastercard, Unionpay and SWIFT have announced their plans and developments to use blockchain technology.
Blockchain Types
Currently, there are three types of blockchain networks:
public blockchains, private blockchains and consortium blockchains.
Public blockchains
A public blockchain has absolutely no access restrictions. Anyone with an Internet connection can make transactions and gain validity (that is, participate in the execution of a consensus protocol). Often, such networks offer economic incentives for people who secure them and use a Proof of Stake or Proof of Work algorithm.
Some of the largest, best-known public blockchains are Bitcoin and Ethereum.
Private blockchains
These types of blockchains can be considered a middle ground for companies interested in blockchain technology in general but not comfortable with a level of control offered by public networks. Typically, they try not to incorporate blockchain into accounting and record-keeping procedures without compromising their autonomy and exposing sensitive data to public internet risk.
Consortium blockchains
A consortium blockchain is often said to be semi-decentralized. He is also on leave; But instead of a single organization controlling it, each company can operate a node in such a network. Administrators of a consortium chain restrict users' read rights as they see fit, allowing only a limited number of trusted nodes to execute a consortium protocol.
In this article, I talked about blockchain. You can find the list of the series on my profile.
Part 5
Cryptology Fundamentals:#5 Applications
Hello, in this last article of the cryptology basics series, I will talk about how cryptographic protocols are implemented. I will use the Java programming language during the implementation phase.
MD5 Application
MD5 is a widely used hash function that can produce a fixed-size output (128 bits) for any input data. In Java, you can calculate the MD5 digest of a string or file using the MessageDigest class, which is part of the Java Security API.
Here is an example of how to calculate the MD5 hash of a string in Java:
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public class MD5Example {
public static void main(String[] args) {
String input = "Hello, world!";
String md5Hash = calculateMD5(input);
System.out.println("MD5 hash of '" + input + "' is: " + md5Hash);
}
public static String calculateMD5(String input) {
try {
MessageDigest md = MessageDigest.getInstance("MD5");
byte[] hash = md.digest(input.getBytes());
StringBuilder sb = new StringBuilder();
for (byte b : hash) {
sb.append(String.format("%02x", b));
}
return sb.toString();
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException("MD5 algorithm not available", e);
}
}
}
In this example, we first import the MessageDigest class and define a calculateMD5 method that takes a string input and returns the MD5 value as a string.
Inside the calculateMD5 method, we first create a new instance of the MessageDigest class by using the getInstance method and giving the "MD5" algorithm as a parameter. Next, we call the hash method on the MessageDigest object and pass the input string as a byte array to calculate the MD5 digest.
Finally, we convert the byte array to a string using a StringBuilder object and the String.format method to format each byte as a two-digit hexadecimal number. We then return the resulting string as an MD5 digest.
SHA-1 Implementation
SHA-1 (Secure HashAlgorithm 1) is a widely used hash function that can create a fixed-size output (160 bits) for any input data. In Java, you can calculate the SHA-1 digest of a string or file using the MessageDigest class, which is part of the Java Security API.
Here is an example of how to calculate the SHA-1 hash of a string in Java:
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public class SHA1Example {
public static void main(String[] args) {
String input = "Hello, world!";
String sha1Hash = calculateSHA1(input);
System.out.println("SHA-1 hash of '" + input + "' is: " + sha1Hash);
}
public static String calculateSHA1(String input) {
try {
MessageDigest md = MessageDigest.getInstance("SHA-1");
byte[] hash = md.digest(input.getBytes());
StringBuilder sb = new StringBuilder();
for (byte b : hash) {
sb.append(String.format("%02x", b));
}
return sb.toString();
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException("SHA-1 algorithm not available", e);
}
}
}
In this example, we first import the MessageDigest class and define a calculateSHA1 method that takes a string input and returns the SHA-1 digest as a string.
Inside the calculateSHA1 method, we first create a new instance of the MessageDigest class by using the getInstance method and giving the "SHA-1" algorithm as a parameter. Next, we call the hash method on the MessageDigest object and pass the input string as a byte array to calculate the SHA-1 hash value.
Finally, we convert the byte array to a string by using a StringBuilder object and the String.format method to format each byte as a two-digit hexadecimal number. We then return the resulting string as a SHA-1 digest.
DES Application
DES (Data Encryption Standard) is a symmetric key encryption system that can be used to encrypt and decrypt data.me algorithm. In Java, you can use the Cipher class from the Java Cryptography Architecture (JCA) to implement DES encryption and decryption.
Here is an example of how to encrypt and decrypt a string using DES in Java:
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
public class DESExample {
public static void main(String[] args) throws Exception {
String originalString = "Hello, world!";
String secretKey = "mysecretkey";
// Encrypt the original string
String encryptedString = encrypt(originalString, secretKey);
System.out.println("Encrypted string: " + encryptedString);
// Decrypt the encrypted string
String decryptedString = decrypt(encryptedString, secretKey);
System.out.println("Decrypted string: " + decryptedString);
}
public static String encrypt(String plainText, String secretKey) throws Exception {
Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
SecretKeySpec secretKeySpec = new SecretKeySpec(secretKey.getBytes(StandardCharsets.UTF_8), "DES");
cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);
byte[] encryptedBytes = cipher.doFinal(plainText.getBytes(StandardCharsets.UTF_8));
return Base64.getEncoder().encodeToString(encryptedBytes);
}
public static String decrypt(String encryptedText, String secretKey) throws Exception {
Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
SecretKeySpec secretKeySpec = new SecretKeySpec(secretKey.getBytes(StandardCharsets.UTF_8), "DES");
cipher.init(Cipher.DECRYPT_MODE, secretKeySpec);
byte[] decodedBytes = Base64.getDecoder().decode(encryptedText);
byte[] decryptedBytes = cipher.doFinal(decodedBytes);
return new String(decryptedBytes, StandardCharsets.UTF_8);
}
}
In this example, we first import the required classes and define the encrypt and decrypt methods, which take a plaintext string and a secret key string as input and return the corresponding encrypted or decrypted string.
Inside each method, we first create a Cipher object using the "DES/ECB/PKCS5Padding" conversion string, which specifies the DES encryption algorithm with Electronic Code Book (ECB) mode and PKCS5 padding.
We then create a SecretKeySpec object using the secret key string and the "DES" algorithm and initialize the cipher object with the secret key using the init method with the appropriate mode (Cipher.ENCRYPT_MODE or Cipher.DECRYPT_MODE).
For encryption, we convert the plaintext string into a byte array and call the doFinal method on the cipher object to encrypt the data. Then, we convert the resulting byte array to a base64-encoded string using the Base64 class and return the encrypted string.
For decryption, we decode the base64-encoded string back into a byte array using the Base64 class, call the doFinal method on the cipher object to decrypt the data, and convert the resulting byte array into a string using the appropriate character set (in this case, StandardCharsets.UTF_8). We then return the decrypted string.
AES Implementation
AES (Advanced Encryption Standard) is a symmetric key encryption algorithm that can be used to encrypt and decrypt data. In Java, you can use the Cipher class from the Java Cryptography Architecture (JCA) to implement AES encryption and decryption.
Here is an example of how to encrypt and decrypt a string using AES in Java:
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
public class AESExample {
public static void main(String[] args) throws Exception {
String originalString = "Hello, world!";
String secretKey = "mysecretkey";
// Encrypt the original string
String encryptedString = encrypt(originalString, secretKey);
System.out.println("Encrypted string: " + encryptedString);
// Decrypt the encrypted string
String decryptedString = decrypt(encryptedString, secretKey);
System.out.println("Decrypted string: " + decryptedString);
}
public static String encrypt(String plainText, String secretKey) throws Exception {
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
SecretKeySpec secretKeySpec = new SecretKeySpec(secretKey.getBytes(StandardCharsets.UTF_8), "AES");
cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);
byte[] encryptedBytes = cipher.doFinal(plainText.getBytes(StandardCharsets.UTF_8));
return Base64.getEncoder().encodeToString(encryptedBytes);
}
public static String decrypt(String encryptedText, String secretKey) throws Exception {
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
SecretKeySpec secretKeySpec = new SecretKeySpec(secretKey.getBytes(StandardCharsets.UTF_8), "AES");
cipher.init(Cipher.DECRYPT_MODE, secretKeySpec);
byte[] decodedBytes = Base64.getDecoder().decode(encryptedText);
byte[] decryptedBytes = cipher.doFinal(decodedBytes);
return new String(decryptedBytes, StandardCharsets.UTF_8);
}
}
In this example, we first import the required classes and define the encrypt and decrypt methods, which take a plaintext string and a secret key string as input and return the corresponding encrypted or decrypted string.
Inside each method, we first create a Cipher object using the "AES/ECB/PKCS5Padding" transform string, which specifies the AES encryption algorithm with Electronic Code Book (ECB) mode and PKCS5 padding.
We then create a SecretKeySpec object using the secret key string and the "AES" algorithm and initialize the cipher object with the secret key using the init method with the appropriate mode (Cipher.ENCRYPT_MODE or Cipher.DECRYPT_MODE).
For encryption, we convert the plaintext string into a byte string and call the doFinal method on the cipher object to encrypt the data. Then, we convert the resulting byte array to a base64-encoded string using the Base64 class and return the encrypted string.
For decryption, we decode the base64-encoded string back into a byte array using the Base64 class, call the doFinal method on the cipher object to decrypt the data, and convert the resulting byte array into a string using the appropriate character set (in this case, StandardCharsets.UTF_8). We then return the decrypted string.
RSA Implementation
RSA (Rivestâ€"Shamirâ€"Adleman) is a public key encryption algorithm that can be used to securely encrypt and decrypt data. In Java, you can use the KeyPairGenerator and Cipher classes from the Java Cryptography Architecture (JCA) to implement RSA encryption and decryption.
Here is an example of how to create an RSA key pair in Java, encrypt a string using the public key, and decrypt the encrypted string:
import javax.crypto.Cipher;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.util.Base64;
public class RSAExample {
public static void main(String[] args) throws Exception {
String originalString = "Hello, world!";
// Generate an RSA key pair
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
keyPairGenerator.initialize(2048);
KeyPair keyPair = keyPairGenerator.generateKeyPair();
// Get the public and private keys from the key pair
byte[] publicKeyBytes = keyPair.getPublic().getEncoded();
byte[] privateKeyBytes = keyPair.getPrivate().getEncoded();
// Encrypt the original string using the public key
byte[] encryptedBytes = encrypt(originalString.getBytes(), publicKeyBytes);
String encryptedString = Base64.getEncoder().encodeToString(encryptedBytes);
System.out.println("Encrypted string: " + encryptedString);
// Decrypt the encrypted string using the private key
byte[] decryptedBytes = decrypt(Base64.getDecoder().decode(encryptedString), privateKeyBytes);
String decryptedString = new String(decryptedBytes);
System.out.println("Decrypted string: " + decryptedString);
}
public static byte[] encrypt(byte[] plainBytes, byte[] publicKeyBytes) throws Exception {
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.ENCRYPT_MODE, KeyFactory.getInstance("RSA").generatePublic(new X509EncodedKeySpec(publicKeyBytes)));
return cipher.doFinal(plainBytes);
}
public static byte[] decrypt(byte[] encryptedBytes, byte[] privateKeyBytes) throws Exception {
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.DECRYPT_MODE, KeyFactory.getInstance("RSA").generatePrivate(new PKCS8EncodedKeySpec(privateKeyBytes)));
return cipher.doFinal(encryptedBytes);
}
}
In this example, we first import the required classes and define the encrypt and decrypt methods, which take a byte array of plaintext or encrypted data and a byte array of public or private key as input and return the corresponding encrypted or decrypted byte array. .
In the main method, we first create an RSA key pair using the KeyPairGenerator class with the "RSA" algorithm and a key size of 2048 bits. We then extract the public and private keys from the key pair as byte arrays using the getEncoded method.
For encryption, we call the encrypt method with the original string converted to a byte array and the public key byte array as input. We create a Cipher object using the "RSA" algorithm in the Encrypt method and initialize it with the public key using the appropriate mode (Cipher.ENCRYPT_MODE) using the init method. Next, we call the doFinal method on the cipher object to encrypt the data and return the resulting byte array.
For decryption, we call the decrypt method with the base64-decrypted encrypted string converted to a byte array and the private key byte array as input. Inside the Decrypt method, we create another Cipher object using the "RSA" algorithm and initialize it with the private key using the appropriate mode and init method.
ECDH Application
ECDH (Elliptic Curve Diffie-Hellman) is a key agreement protocol that allows two parties to establish a shared secret over an unsecured communication channel. In Java, you can use the KeyAgreement and KeyPairGenerator classes from the Java Cryptography Architecture (JCA) to implement ECDH key exchange using elliptic curve cryptography.
Here's an example of creating an ECDH key pair, performing a key exchange with another party, and deriving a shared key using Java:
import javax.crypto.KeyAgreement;
import javax.crypto.SecretKey;
import javax.crypto.spec.ECGenParameterSpec;
import java.security.*;
import java.security.spec.ECParameterSpec;
import java.security.spec.ECPublicKeySpec;
import java.security.spec.InvalidKeySpecException;
public class ECDHExample {
public static void main(String[] args) throws Exception {
// Generate an ECDH key pair
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("EC");
ECGenParameterSpec ecGenParameterSpec = new ECGenParameterSpec("secp256r1");
keyPairGenerator.initialize(ecGenParameterSpec);
KeyPair keyPair = keyPairGenerator.generateKeyPair();
PrivateKey privateKey = keyPair.getPrivate();
PublicKey publicKey = keyPair.getPublic();
// Simulate the other party by generating its own ECDH key pair
KeyPair otherKeyPair = keyPairGenerator.generateKeyPair();
PrivateKey otherPrivateKey = otherKeyPair.getPrivate();
PublicKey otherPublicKey = otherKeyPair.getPublic();
// Perform key exchange with the other party
KeyAgreement keyAgreement = KeyAgreement.getInstance("ECDH");
keyAgreement.init(privateKey);
keyAgreement.doPhase(otherPublicKey, true);
// Derive the shared secret
byte[] sharedSecret = keyAgreement.generateSecret();
// Simulate the other party deriving the shared secret using its private key
KeyFactory keyFactory = KeyFactory.getInstance("EC");
ECParameterSpec ecParameterSpec = ((ECPublicKeySpec) otherPublicKey.getKeySpec(ECPublicKeySpec.class)).getParams();
PublicKey simulatedOtherPublicKey = keyFactory.generatePublic(new ECPublicKeySpec(((java.security.spec.ECPoint) otherPublicKey).getW(), ecParameterSpec));
KeyAgreement simulatedKeyAgreement = KeyAgreement.getInstance("ECDH");
simulatedKeyAgreement.init(otherPrivateKey);simulatedKeyAgreement.doPhase(publicKey, true);
byte[] simulatedSharedSecret = simulatedKeyAgreement.generateSecret();
// Compare the two shared secrets (should be equal)
System.out.println("Shared secret: " + bytesToHex(sharedSecret));
System.out.println("Simulated shared secret: " + bytesToHex(simulatedSharedSecret));
System.out.println("Shared secrets match: " + bytesToHex(sharedSecret).equals(bytesToHex(simulatedSharedSecret)));
}
public static String bytesToHex(byte[] bytes) {
StringBuilder sb = new StringBuilder();
for (byte b : bytes) {
sb.append(String.format("%02X", b));
}
return sb.toString();
}
}
In this example, we first import the required classes and define a bytesToHex method to convert a byte array to a hexadecimal string.
Inside the main method, we first create an ECDH key pair using the KeyPairGenerator class with the "EC" algorithm and the "secp256r1" elliptic curve parameter property. We then extract the private and public keys from the key pair.
We simulate the counterparty by creating its own ECDH key pair using the same curve parameters.
ECDSA Application
ECDSA (Elliptic Curve Digital Signature Algorithm) is a digital signature algorithm based on elliptic curve cryptography. In Java, you can use the Signature and KeyPairGenerator classes from the Java Cryptography Architecture (JCA) to implement ECDSA.
Here's an example of how to create an ECDSA key pair using Java, sign a message with the private key, and verify the signature with the public key:
import java.security.*;
import java.security.spec.ECGenParameterSpec;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
public class ECDSAExample {
public static void main(String[] args) throws Exception {
// Generate an ECDSA key pair
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("EC");
ECGenParameterSpec ecGenParameterSpec = new ECGenParameterSpec("secp256r1");
keyPairGenerator.initialize(ecGenParameterSpec);
KeyPair keyPair = keyPairGenerator.generateKeyPair();
PrivateKey privateKey = keyPair.getPrivate();
PublicKey publicKey = keyPair.getPublic();
// Sign a message with the private key
byte[] message = "Hello, world!".getBytes();
Signature signature = Signature.getInstance("SHA256withECDSA");
signature.initSign(privateKey);
signature.update(message);
byte[] signatureBytes = signature.sign();
// Verify the signature with the public key
Signature verifier = Signature.getInstance("SHA256withECDSA");
verifier.initVerify(publicKey);
verifier.update(message);
boolean signatureValid = verifier.verify(signatureBytes);
System.out.println("Signature valid: " + signatureValid);
}
}
In this example, we first import the necessary classes.
Inside the main method, we generate an ECDSA key pair using the KeyPairGenerator class with the "EC" algorithm and the elliptic curve parameter property "secp256r1". We extract the private and public keys from the key pair.
We then create a message to sign and use the Signature class to sign the message with the private key. To use SHA-256 as the hash function, we specify the "SHA256withECDSA" algorithm.
Next, we create a validator object using the Signature class and initialize it with the public key. We update the validator with the same message and verify the signature using the verification method. We compare the result to true to determine whether the signature is valid.
Note that in a real-world scenario, you will typically transmit the signed message and the public key separately to the verifier to ensure that the signature has not been tampered with during transmission.
In this article, I made cryptology applications with Java. You can access the article series from my profile. Don't forget to like and follow.