
Recently, I worked on a project that involved selecting some encryption algorithms, and I would like to summarize them here to deepen our understanding of encryption.
The most commonly used encryption algorithms can be summarized as one-way encryption and two-way encryption. They are quite simple and not difficult to understand. However, I believe it is essential to have a clear understanding of their principles so that we can work more effectively in our development. After all, for our research and development, data security is paramount, and encryption algorithms play a crucial role in maintaining the data security of software. Let’s take a look at the applications of these algorithms, how they are used, and how the code is implemented. By the end, you will have a deeper understanding of these little ciphers.
Introduction
Today, I will present the history and evolution of encryption algorithms.
As early as ancient Greece, humans invented substitution ciphers. In 1881, the world’s first telephone secrecy patent appeared. During World War II, the German military used the “Enigma” cipher machine, and cryptography played a very important role in the war.
In 1997, the U.S. National Institute of Standards and Technology implemented the “Data Encryption Standard (DES)” and civilian forces began to fully engage in the research and application of cryptography, using encryption algorithms such as DES, RSA, SHA
. With the increasing demand for encryption strength, new algorithms such as AES, ECC
have recently emerged.
Now that the history is covered, let’s get into the main content and first look at the benefits of using encryption algorithms.
Using cryptography can achieve the following goals:
Confidentiality: Prevents user identities or data from being read.
Data Integrity: Prevents data from being altered.
Authentication: Ensures that data originates from a specific party.
One-way encryption, in simple terms, generates ciphertext through a hash calculation of the data, and the ciphertext cannot be reversed to restore the original data. Algorithms include: MD5, SHA, HMAC, etc.
One-Way Encryption
MD5
MD5
— message-digest algorithm 5, widely used in encryption and decryption technology, is commonly used for file verification. Regardless of the file size, MD5 can generate a unique MD5
value. For example, the current ISO verification uses MD5, where the MD5 value is generated after processing the ISO with MD5. Generally, friends downloading linux-ISO
have seen the MD5 string next to the download link, which is used to verify file consistency.
Encryption tool class is as follows:
/**
* MD5 encryption
*
* @param data
* @return
* @throws Exception
*/
public static byte[] encryptMD5(byte[] data) throws Exception {
MessageDigest md5 = MessageDigest.getInstance(KEY_MD5);
md5.update(data);
return md5.digest();
}
SHA
SHA
(Secure Hash Algorithm, Secure Hash Algorithm) is an important tool in cryptographic applications such as digital signatures and is widely used in e-commerce and other information security fields. Although SHA and MD5 have both been compromised through collision attacks, SHA is still recognized as a secure encryption algorithm and is more secure than MD5.
Encryption tool class is as follows:
/**
* SHA encryption
*
* @param data
* @return
* @throws Exception
*/
public static byte[] encryptSHA(byte[] data) throws Exception {
MessageDigest sha = MessageDigest.getInstance(KEY_SHA);
sha.update(data);
return sha.digest();
}
HMAC
HMAC
(Hash Message Authentication Code, Hash Message Authentication Code) is an authentication protocol based on a key hash algorithm. The principle of message authentication is to generate a fixed-length value as an authentication identifier using a public function and a key, which is used to verify the integrity of the message. A key is used to generate a fixed-size small data block, known as MAC
, which is added to the message before transmission. The receiver uses the shared key with the sender for authentication.
Encryption tool class is as follows:
/**
* Initialize HMAC key
*
* @return
* @throws Exception
*/
public static String initMacKey() throws Exception {
KeyGenerator keyGenerator = KeyGenerator.getInstance(KEY_MAC);
SecretKey secretKey = keyGenerator.generateKey();
return encryptBASE64(secretKey.getEncoded());
}
/**
* HMAC encryption
*
* @param data
* @param key
* @return
* @throws Exception
*/
public static byte[] encryptHMAC(byte[] data, String key) throws Exception {
SecretKey secretKey = new SecretKeySpec(decryptBASE64(key), KEY_MAC);
Mac mac = Mac.getInstance(secretKey.getAlgorithm());
mac.init(secretKey);
return mac.doFinal(data);
}
Two-way encryption, also known as reversible encryption, generates ciphertext that can be decrypted back to plaintext when needed. Two-way encryption is divided into symmetric and asymmetric encryption.
Symmetric Encryption Algorithms
Symmetric encryption algorithms are among the earliest encryption algorithms and are technically mature. In symmetric encryption algorithms, the data sender processes the plaintext (original data) along with the encryption key through a special encryption algorithm, transforming it into complex encrypted ciphertext for transmission. In symmetric encryption algorithms, only one key is used, and both the sender and receiver use this key for encryption and decryption, which requires the decryption party to know the encryption key in advance. The characteristics of symmetric encryption algorithms include public algorithms, small computational load, fast encryption speed, and high encryption efficiency. However, the drawback is that both parties use the same key, which does not guarantee security. Symmetric encryption algorithms are more challenging to use in distributed network systems primarily due to key management difficulties and high usage costs.
Data encryption process: In symmetric encryption algorithms, the data sender processes the plaintext (original data) along with the encryption key through a special encryption process to generate complex encrypted ciphertext for transmission.
Data decryption process: The data receiver, upon receiving the ciphertext, must use the encryption key and the same algorithm’s inverse algorithm to decrypt the ciphertext to restore it to readable plaintext.
Common algorithms include: DES, 3DES, AES, TDEA, Blowfish, RC2, RC4, RC5, IDEA, Skipjack, etc. Below, we will mainly introduce the commonly used DES, 3DES, AES
encryption algorithms.

DES Encryption Algorithm
The DES encryption algorithm is a block cipher that encrypts data in 64
bit blocks, with a key length of 56
bits, using the same algorithm for encryption and decryption. The DES encryption algorithm keeps the key secret while the algorithm, including both encryption and decryption, is public. Thus, only those who possess the same key as the sender can interpret the ciphertext encrypted by the DES algorithm. Therefore, breaking the DES encryption algorithm essentially involves searching for the key code. For a key length of 56 bits, if a brute force method is used for searching, the number of operations required is 2^56
.
With the continuous development of computer system capabilities, the security of DES is much weaker than when it first appeared; however, from a practical standpoint, it can still be considered sufficient. Nevertheless, DES is now only used for authentication in legacy systems, and newer encryption standards are preferred.
Encryption tool class is as follows:
/**
* Encryption
*
* @param datasource Data to be encrypted
* @param key
* @return byte array
*/
public static byte[] enCrypto(byte[] datasource, String key) throws InvalidKeyException, NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException, BadPaddingException, IllegalBlockSizeException {
SecureRandom random = new SecureRandom();
DESKeySpec desKey = new DESKeySpec(key.getBytes());
// Create a key factory and convert DESKeySpec to
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
SecretKey securekey = keyFactory.generateSecret(desKey);
// Cipher object actually performs the encryption operation
Cipher cipher = Cipher.getInstance("DES");
// Initialize the Cipher object with the key
cipher.init(Cipher.ENCRYPT_MODE, securekey, random);
// Now, get the data and encrypt
// Perform the encryption operation
return cipher.doFinal(datasource);
}
3DES Encryption Algorithm
3DES is a triple data encryption algorithm block cipher. It applies the DES encryption algorithm three times to each data block. Due to the enhanced computational capabilities of computers, the original DES key length has become vulnerable to brute force attacks; 3DES was designed to provide a relatively simple method to avoid similar attacks by increasing the DES
key length rather than designing a completely new block cipher algorithm.
3DES serves as a transitional encryption algorithm from DES to AES, and its specific implementation is as follows: let Ek()
and Dk()
represent the encryption and decryption processes of the DES algorithm, K
represent the key used by the DES algorithm, M
represent the plaintext, and C
represent the ciphertext. The encryption process is: C=Ek3(Dk2(Ek1(M)))
Encryption tool class is as follows:
/**
* Method description: 3DES encryption
*
* @param plainText Plaintext
* @param secretKey Key
* @param iv Initialization vector
* @return String Ciphertext
* @throws Exception
*/
public static String encode(String plainText, String secretKey, String iv)
throws Exception {
Key deskey = null;
DESedeKeySpec spec = new DESedeKeySpec(secretKey.getBytes());
SecretKeyFactory keyfactory = SecretKeyFactory.getInstance("desede");
deskey = keyfactory.generateSecret(spec);
Cipher cipher = Cipher.getInstance("desede/CBC/PKCS5Padding");
IvParameterSpec ips = new IvParameterSpec(iv.getBytes());
cipher.init(Cipher.ENCRYPT_MODE, deskey, ips);
byte[] encryptData = cipher.doFinal(plainText.getBytes(encoding));
return Base64.encode(encryptData);
}
AES Encryption Algorithm
The AES encryption algorithm is the Advanced Encryption Standard in cryptography, which uses a symmetric block cipher system with a minimum key length of 128
, 192
, or 256
, and a block length of 128
bits. The algorithm should be easy to implement in various hardware and software. This encryption algorithm is the block encryption standard adopted by the U.S. federal government, which replaces the original DES
and has been widely analyzed and used worldwide.
The AES encryption algorithm is designed to support 128/192/256
bit data block sizes (i.e., block lengths); it supports 128/192/256
bit key lengths, corresponding to 34×10^38, 62×10^57, 1.1×10^77
keys in decimal.
Encryption tool class is as follows:
/**
* AES encryption
* @param data String to be encrypted
* @param key Encryption key
* @param iv Initialization vector in the encryption algorithm
* @return Encrypted string
*/
public static String encrypt(String data, String key, String iv) {
try {
Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
int blockSize = cipher.getBlockSize();
byte[] dataBytes = data.getBytes();
int plaintextLength = dataBytes.length;
if (plaintextLength % blockSize != 0) {
plaintextLength = plaintextLength + (blockSize - (plaintextLength % blockSize));
}
byte[] plaintext = new byte[plaintextLength];
System.arraycopy(dataBytes, 0, plaintext, 0, dataBytes.length);
SecretKeySpec keyspec = new SecretKeySpec(key.getBytes(), Constant.STRING_AES);
IvParameterSpec ivspec = new IvParameterSpec(iv.getBytes(Constant.STRING_UTF_8));
cipher.init(Cipher.ENCRYPT_MODE, keyspec, ivspec);
byte[] encrypted = cipher.doFinal(plaintext);
String encrypt = Base64.getEncoder().encodeToString(encrypted); //BASE64 encryption
encrypt = encrypt.replaceAll(new String(Constant.STRING_CARRIAGE_RETURN), Constant.STRING_BLANK);
encrypt = encrypt.replaceAll(new String(Constant.STRING_LINE_FEED), Constant.STRING_BLANK);
return encrypt;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
Comparison of Symmetric Encryption Algorithms

Asymmetric Encryption Algorithms
Asymmetric encryption algorithms use two completely different but perfectly matching keys—a public key and a private key. When using asymmetric encryption algorithms to encrypt files, only the matching pair of public and private keys can complete the encryption and decryption process of the plaintext. In asymmetric encryption algorithms, the receiving party must send their randomly generated public key to the sending party before communication while keeping the private key. Due to the presence of two keys, asymmetric algorithms are particularly suitable for data encryption in distributed systems. Widely used asymmetric encryption algorithms include RSA
and DSA
proposed by the U.S. National Institute of Standards and Technology. Encryption technologies based on asymmetric algorithms are widely applied.
Workflow:
1. Party B generates a pair of keys (public and private) and makes the public key public to others.
2. Party A, having obtained the public key, uses it to encrypt confidential information before sending it to Party B.
3. Party B then uses their private key to decrypt the encrypted information. Party B can only use their private key to decrypt information encrypted with the corresponding public key.
During transmission, even if an attacker intercepts the transmitted ciphertext and obtains Party B’s public key, they cannot decrypt the ciphertext because only Party B’s private key can decrypt it.
Similarly, if Party B wants to reply with encrypted information to Party A, they need Party A to first publish their public key for Party B to use for encryption, while Party A keeps their private key for decryption.

RSA Encryption Algorithm
The RSA encryption algorithm is currently the most influential public key encryption algorithm and is widely regarded as one of the best public key schemes. RSA is the first algorithm that can be used for both encryption and digital signatures, and it can resist all known cryptographic attacks to date. It has been recommended by ISO
as the public key data encryption standard.
Encryption tool class is as follows:
/**
* RSA public key encryption
*
* @param str String to encrypt
* @param publicKey Public key
* @return Ciphertext
* @throws Exception Exception information during the encryption process
*/
public static String encrypt( String str, String publicKey ) throws Exception{
// Base64 encoded public key
byte[] decoded = Base64.decodeBase64(publicKey);
RSAPublicKey pubKey = (RSAPublicKey) KeyFactory.getInstance("RSA").generatePublic(new X509EncodedKeySpec(decoded));
// RSA encryption
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.ENCRYPT_MODE, pubKey);
String outStr = Base64.encodeBase64String(cipher.doFinal(str.getBytes("UTF-8")));
return outStr;
}
DSA Encryption Algorithm
DSA is based on the discrete logarithm problem in finite fields, and its security is comparable to that of RSA. An important feature of DSA is that two prime numbers are public, so when using someone else’s p and q, even without knowing the private key, you can verify whether they were randomly generated or tampered with. RSA cannot do this. DSA is only an algorithm and, unlike RSA, cannot be used for encryption and decryption or key exchange; it is only used for signatures and is much faster than RSA.
Encryption process is as follows:

ECC Encryption Algorithm
The Elliptic Curve Cryptography (ECC) is a public key encryption system initially proposed by Koblitz
and Miller
in 1985. Its mathematical foundation is based on the difficulty of computing discrete logarithms on rational points on elliptic curves. Public key cryptosystems are generally divided into three categories based on the problems they rely on: large integer factorization, discrete logarithm problems, and elliptic curves. Sometimes, elliptic curve cryptography is classified under discrete logarithm problems. The elliptic curve cryptosystem is currently known to provide the highest encryption strength per bit among public key systems. The best algorithm for solving the discrete logarithm problem on elliptic curves is the Pollard rho
method, which has a time complexity that is completely exponential.
Encryption tool class is as follows:
/**
* Encryption
* @param data
* @param publicKey
* @return
* @throws Exception
*/
public static byte[] encrypt(byte[] data, String publicKey)
throws Exception {
byte[] keyBytes = BASE64Decoder.decodeBuffer(publicKey);
X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes);
KeyFactory keyFactory = KeyFactory.getInstance(ECCEnum.ALGORITHM.value());
ECPublicKey pubKey = (ECPublicKey) keyFactory
.generatePublic(x509KeySpec);
Cipher cipher = new NullCipher();
cipher.init(Cipher.ENCRYPT_MODE, pubKey);
return cipher.doFinal(data);
}
Comparison of Asymmetric Encryption Algorithms

Conclusion
Comparison of Symmetric and Asymmetric Encryption

Practical Applications:
Asymmetric encryption algorithms manage the keys of symmetric algorithms, while symmetric encryption algorithms encrypt data, thus improving encryption speed while ensuring decryption security.
It is recommended to use 1024
bits for RSA, 160
bits for ECC, and 128
bits for AES.
Other Comparisons:
In terms of management: Public key cryptography algorithms require fewer resources to achieve their goals, and in key distribution, the two differ by an exponential level (one is n, the other is n^2). Therefore, public key cryptography algorithms are not suitable for wide area networks, and more importantly, they do not support digital signatures.
In terms of security: Since public key cryptography algorithms are based on unsolved mathematical problems, they are nearly impossible to break. For private key cryptography algorithms, although AES is theoretically unbreakable, from the perspective of computer development, public key algorithms have superiority.
About Me
Below is my personal QR code image, and I hope to advance together with everyone and improve together.
I have established a technical group, and if you want to learn more about IT industry technologies and the problems encountered in life, feel free to add me as a friend and note: Join Group to exchange ideas. I look forward to your joining.
Recommended Reading
Wow, you actually hid a Trojan in your resume!
Latest programming language rankings as of December 2020
These 25 images will help you thoroughly understand 25 complex mathematical formulas!