Home> Java> javaTutorial> body text

Common encryption and decryption algorithms implemented in Java

PHPz
Release: 2023-06-18 09:22:53
Original
1447 people have browsed it

Java is a very popular programming language that is widely used in various fields. In practical applications, data encryption and decryption are very common requirements. Java provides many encryption and decryption algorithms. This article will briefly introduce several common algorithms.

1. Symmetric encryption algorithm

Symmetric encryption algorithm, also called private key encryption algorithm, uses the same key for encryption and decryption. Common symmetric encryption algorithms include DES, 3DES, AES, etc.

  1. DES algorithm

DES (Data Encryption Standard) is a classic symmetric encryption algorithm with a key length of 56 bits. When using the DES algorithm, you need to generate a key first, then use the key to encrypt the plaintext to obtain the ciphertext; then use the key to decrypt the ciphertext to obtain the plaintext. In Java, you can use the DES encryption and decryption function provided by JCE (Java Cryptography Extension). The sample code is as follows:

import javax.crypto.Cipher; import javax.crypto.KeyGenerator; import javax.crypto.SecretKey; import javax.crypto.spec.SecretKeySpec; import java.security.NoSuchAlgorithmException; public class DESUtil { private static final String ALGORITHM = "DES"; public static String encrypt(String content, String key) throws Exception { SecretKeySpec skeySpec = new SecretKeySpec(key.getBytes(), ALGORITHM); Cipher cipher = Cipher.getInstance(ALGORITHM); byte[] byteContent = content.getBytes(); cipher.init(Cipher.ENCRYPT_MODE, skeySpec); byte[] result = cipher.doFinal(byteContent); return parseByte2HexStr(result); } public static String decrypt(String content, String key) throws Exception { byte[] decryptFrom = parseHexStr2Byte(content); SecretKeySpec skeySpec = new SecretKeySpec(key.getBytes(), ALGORITHM); Cipher cipher = Cipher.getInstance(ALGORITHM); cipher.init(Cipher.DECRYPT_MODE, skeySpec); byte[] result = cipher.doFinal(decryptFrom); return new String(result); } private static String parseByte2HexStr(byte[] buf) { StringBuilder sb = new StringBuilder(); for (byte b : buf) { String hex = Integer.toHexString(b & 0xFF); if (hex.length() == 1) { hex = '0' + hex; } sb.append(hex.toUpperCase()); } return sb.toString(); } private static byte[] parseHexStr2Byte(String hexStr) { if (hexStr.length() < 1) { return null; } byte[] result = new byte[hexStr.length() / 2]; for (int i = 0; i < hexStr.length() / 2; i++) { int high = Integer.parseInt(hexStr.substring(i * 2, i * 2 + 1), 16); int low = Integer.parseInt(hexStr.substring(i * 2 + 1, i * 2 + 2), 16); result[i] = (byte) (high * 16 + low); } return result; } public static void main(String[] args) throws Exception { String content = "Hello World!"; String key = "12345678"; String encrypt = encrypt(content, key); System.out.println("加密后:" + encrypt); String decrypt = decrypt(encrypt, key); System.out.println("解密后:" + decrypt); } }
Copy after login
  1. 3DES algorithm

3DES (Triple DES) algorithm is an encryption algorithm enhanced on the basis of the DES algorithm. The key length is 168 Bit. The encryption and decryption process of the 3DES algorithm is similar to the DES algorithm and can be implemented using the JCE library provided by Java. The sample code is as follows:

import javax.crypto.Cipher; import javax.crypto.KeyGenerator; import javax.crypto.SecretKey; import javax.crypto.spec.SecretKeySpec; import java.security.NoSuchAlgorithmException; public class TripleDESUtil { private static final String ALGORITHM = "DESede"; private static byte[] initKey() throws NoSuchAlgorithmException { KeyGenerator kg = KeyGenerator.getInstance(ALGORITHM); kg.init(168); // 3DES的密钥长度为168位 SecretKey secretKey = kg.generateKey(); return secretKey.getEncoded(); } public static String encrypt(String content, byte[] key) throws Exception { SecretKeySpec skeySpec = new SecretKeySpec(key, ALGORITHM); Cipher cipher = Cipher.getInstance(ALGORITHM); byte[] byteContent = content.getBytes(); cipher.init(Cipher.ENCRYPT_MODE, skeySpec); byte[] result = cipher.doFinal(byteContent); return parseByte2HexStr(result); } public static String decrypt(String content, byte[] key) throws Exception { byte[] decryptFrom = parseHexStr2Byte(content); SecretKeySpec skeySpec = new SecretKeySpec(key, ALGORITHM); Cipher cipher = Cipher.getInstance(ALGORITHM); cipher.init(Cipher.DECRYPT_MODE, skeySpec); byte[] result = cipher.doFinal(decryptFrom); return new String(result); } private static String parseByte2HexStr(byte[] buf) { StringBuilder sb = new StringBuilder(); for (byte b : buf) { String hex = Integer.toHexString(b & 0xFF); if (hex.length() == 1) { hex = '0' + hex; } sb.append(hex.toUpperCase()); } return sb.toString(); } private static byte[] parseHexStr2Byte(String hexStr) { if (hexStr.length() < 1) { return null; } byte[] result = new byte[hexStr.length() / 2]; for (int i = 0; i < hexStr.length() / 2; i++) { int high = Integer.parseInt(hexStr.substring(i * 2, i * 2 + 1), 16); int low = Integer.parseInt(hexStr.substring(i * 2 + 1, i * 2 + 2), 16); result[i] = (byte) (high * 16 + low); } return result; } public static void main(String[] args) throws Exception { String content = "Hello World!"; byte[] key = initKey(); String encrypt = encrypt(content, key); System.out.println("加密后:" + encrypt); String decrypt = decrypt(encrypt, key); System.out.println("解密后:" + decrypt); } }
Copy after login
  1. AES algorithm

The AES (Advanced Encryption Standard) algorithm is an advanced encryption standard and one of the most popular symmetric encryption algorithms currently. The key length of the AES algorithm is generally 128 bits, 192 bits or 256 bits. In Java, you can also use the AES encryption and decryption function provided by the JCE library. The sample code is as follows:

import javax.crypto.Cipher; import javax.crypto.KeyGenerator; import javax.crypto.SecretKey; import javax.crypto.spec.SecretKeySpec; import java.security.NoSuchAlgorithmException; public class AESUtil { private static final String ALGORITHM = "AES"; private static byte[] initKey() throws NoSuchAlgorithmException { KeyGenerator kg = KeyGenerator.getInstance(ALGORITHM); kg.init(128); // AES的密钥长度为128位、192位、256位 SecretKey secretKey = kg.generateKey(); return secretKey.getEncoded(); } public static String encrypt(String content, byte[] key) throws Exception { SecretKeySpec skeySpec = new SecretKeySpec(key, ALGORITHM); Cipher cipher = Cipher.getInstance(ALGORITHM); byte[] byteContent = content.getBytes(); cipher.init(Cipher.ENCRYPT_MODE, skeySpec); byte[] result = cipher.doFinal(byteContent); return parseByte2HexStr(result); } public static String decrypt(String content, byte[] key) throws Exception { byte[] decryptFrom = parseHexStr2Byte(content); SecretKeySpec skeySpec = new SecretKeySpec(key, ALGORITHM); Cipher cipher = Cipher.getInstance(ALGORITHM); cipher.init(Cipher.DECRYPT_MODE, skeySpec); byte[] result = cipher.doFinal(decryptFrom); return new String(result); } private static String parseByte2HexStr(byte[] buf) { StringBuilder sb = new StringBuilder(); for (byte b : buf) { String hex = Integer.toHexString(b & 0xFF); if (hex.length() == 1) { hex = '0' + hex; } sb.append(hex.toUpperCase()); } return sb.toString(); } private static byte[] parseHexStr2Byte(String hexStr) { if (hexStr.length() < 1) { return null; } byte[] result = new byte[hexStr.length() / 2]; for (int i = 0; i < hexStr.length() / 2; i++) { int high = Integer.parseInt(hexStr.substring(i * 2, i * 2 + 1), 16); int low = Integer.parseInt(hexStr.substring(i * 2 + 1, i * 2 + 2), 16); result[i] = (byte) (high * 16 + low); } return result; } public static void main(String[] args) throws Exception { String content = "Hello World!"; byte[] key = initKey(); String encrypt = encrypt(content, key); System.out.println("加密后:" + encrypt); String decrypt = decrypt(encrypt, key); System.out.println("解密后:" + decrypt); } }
Copy after login

2. Asymmetric encryption algorithm

The asymmetric encryption algorithm is also called the public key encryption algorithm, which uses different keys for encryption and decryption. Common asymmetric encryption algorithms include the RSA algorithm.

  1. RSA algorithm

RSA algorithm is an asymmetric encryption algorithm and a number theory encryption algorithm based on large integers. The characteristic of the RSA algorithm is that the public key can be made public and the key is private, so it is highly secure. In Java, you can also use the RSA encryption and decryption functions provided by the JCE library. The sample code is as follows:

import javax.crypto.Cipher; import java.security.KeyPair; import java.security.KeyPairGenerator; import java.security.NoSuchAlgorithmException; import java.security.PrivateKey; import java.security.PublicKey; public class RSAUtil { private static final String ALGORITHM = "RSA"; private static KeyPair getKeyPair(int keySize) throws NoSuchAlgorithmException { KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(ALGORITHM); keyPairGenerator.initialize(keySize); return keyPairGenerator.generateKeyPair(); } public static String encrypt(String content, PublicKey publicKey) throws Exception { Cipher cipher = Cipher.getInstance(ALGORITHM); cipher.init(Cipher.ENCRYPT_MODE, publicKey); byte[] byteContent = content.getBytes(); byte[] result = cipher.doFinal(byteContent); return parseByte2HexStr(result); } public static String decrypt(String content, PrivateKey privateKey) throws Exception { byte[] decryptFrom = parseHexStr2Byte(content); Cipher cipher = Cipher.getInstance(ALGORITHM); cipher.init(Cipher.DECRYPT_MODE, privateKey); byte[] result = cipher.doFinal(decryptFrom); return new String(result); } private static String parseByte2HexStr(byte[] buf) { StringBuilder sb = new StringBuilder(); for (byte b : buf) { String hex = Integer.toHexString(b & 0xFF); if (hex.length() == 1) { hex = '0' + hex; } sb.append(hex.toUpperCase()); } return sb.toString(); } private static byte[] parseHexStr2Byte(String hexStr) { if (hexStr.length() < 1) { return null; } byte[] result = new byte[hexStr.length() / 2]; for (int i = 0; i < hexStr.length() / 2; i++) { int high = Integer.parseInt(hexStr.substring(i * 2, i * 2 + 1), 16); int low = Integer.parseInt(hexStr.substring(i * 2 + 1, i * 2 + 2), 16); result[i] = (byte) (high * 16 + low); } return result; } public static void main(String[] args) throws Exception { String content = "Hello World!"; KeyPair keyPair = getKeyPair(1024); PublicKey publicKey = keyPair.getPublic(); PrivateKey privateKey = keyPair.getPrivate(); String encrypt = encrypt(content, publicKey); System.out.println("加密后:" + encrypt); String decrypt = decrypt(encrypt, privateKey); System.out.println("解密后:" + decrypt); } }
Copy after login

The above are several common encryption and decryption algorithms implemented in Java. In actual applications, it is necessary to choose the encryption and decryption algorithm that suits you according to the actual situation, and adjust and optimize it according to specific needs.

The above is the detailed content of Common encryption and decryption algorithms implemented in Java. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!