


Algorithmes de chiffrement et de déchiffrement courants implémentés en Java
Java est un langage de programmation très populaire et largement utilisé dans divers domaines. Dans les applications pratiques, le cryptage et le déchiffrement des données sont des exigences très courantes. Java fournit de nombreux algorithmes de chiffrement et de déchiffrement. Cet article présentera brièvement plusieurs algorithmes courants.
1. Algorithme de cryptage symétrique
L'algorithme de cryptage symétrique, également appelé algorithme de cryptage à clé privée, utilise la même clé pour le cryptage et le déchiffrement. Les algorithmes de chiffrement symétriques courants incluent DES, 3DES, AES, etc.
- Algorithme DES
DES (Data Encryption Standard) est un algorithme de cryptage symétrique classique avec une longueur de clé de 56 bits. Lorsque vous utilisez l'algorithme DES, vous devez d'abord générer une clé, puis utiliser la clé pour chiffrer le texte en clair afin d'obtenir le texte chiffré, puis utiliser la clé pour déchiffrer le texte chiffré afin d'obtenir le texte en clair ; En Java, vous pouvez utiliser la fonction de cryptage et de déchiffrement DES fournie par JCE (Java Cryptography Extension). L'exemple de code est le suivant :
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); } }
- Algorithme 3DES
L'algorithme 3DES (Triple DES) est un algorithme de cryptage amélioré sur la base de l'algorithme DES, avec une longueur de clé de 168 bits. Le processus de cryptage et de déchiffrement de l'algorithme 3DES est similaire à l'algorithme DES et peut être implémenté à l'aide de la bibliothèque JCE fournie par Java. L'exemple de code est le suivant :
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); } }
- Algorithme AES
L'algorithme AES (Advanced Encryption Standard) est une norme de cryptage avancée et l'un des algorithmes de cryptage symétriques les plus populaires actuellement. La longueur de clé de l'algorithme AES est généralement de 128 bits, 192 bits ou 256 bits. En Java, vous pouvez également utiliser la fonction de chiffrement et de déchiffrement AES fournie par la bibliothèque JCE. L'exemple de code est le suivant :
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); } }
2. Algorithme de cryptage asymétrique
L'algorithme de cryptage asymétrique est également appelé algorithme de cryptage à clé publique, qui utilise différentes clés pour le cryptage et le déchiffrement. Les algorithmes de chiffrement asymétriques courants incluent l'algorithme RSA.
- Algorithme RSA
L'algorithme RSA est un algorithme de chiffrement asymétrique et un algorithme de chiffrement de théorie des nombres basé sur de grands entiers. La caractéristique de l’algorithme RSA est que la clé publique peut être rendue publique et que la clé est privée, elle est donc hautement sécurisée. En Java, vous pouvez également utiliser les fonctions de chiffrement et de déchiffrement RSA fournies par la bibliothèque JCE. L'exemple de code est le suivant :
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); } }
Ci-dessus sont plusieurs algorithmes de cryptage et de déchiffrement courants implémentés en Java. Dans les applications réelles, vous devez choisir l'algorithme de cryptage et de décryptage qui vous convient en fonction de la situation réelle, puis l'ajuster et l'optimiser en fonction des besoins spécifiques.
Ce qui précède est le contenu détaillé de. pour plus d'informations, suivez d'autres articles connexes sur le site Web de PHP en chinois!

Outils d'IA chauds

Undresser.AI Undress
Application basée sur l'IA pour créer des photos de nu réalistes

AI Clothes Remover
Outil d'IA en ligne pour supprimer les vêtements des photos.

Undress AI Tool
Images de déshabillage gratuites

Clothoff.io
Dissolvant de vêtements AI

AI Hentai Generator
Générez AI Hentai gratuitement.

Article chaud

Outils chauds

Bloc-notes++7.3.1
Éditeur de code facile à utiliser et gratuit

SublimeText3 version chinoise
Version chinoise, très simple à utiliser

Envoyer Studio 13.0.1
Puissant environnement de développement intégré PHP

Dreamweaver CS6
Outils de développement Web visuel

SublimeText3 version Mac
Logiciel d'édition de code au niveau de Dieu (SublimeText3)

Le chargement de classe de Java implique le chargement, la liaison et l'initialisation des classes à l'aide d'un système hiérarchique avec Bootstrap, Extension et Application Classloaders. Le modèle de délégation parent garantit que les classes de base sont chargées en premier, affectant la classe de classe personnalisée LOA

L'article examine la mise en œuvre de la mise en cache à plusieurs niveaux en Java à l'aide de la caféine et du cache de goyave pour améliorer les performances de l'application. Il couvre les avantages de configuration, d'intégration et de performance, ainsi que la gestion de la politique de configuration et d'expulsion le meilleur PRA

L'article discute de l'utilisation de JPA pour la cartographie relationnelle des objets avec des fonctionnalités avancées comme la mise en cache et le chargement paresseux. Il couvre la configuration, la cartographie des entités et les meilleures pratiques pour optimiser les performances tout en mettant en évidence les pièges potentiels. [159 caractères]

L'article discute de l'utilisation de Maven et Gradle pour la gestion de projet Java, la construction de l'automatisation et la résolution de dépendance, en comparant leurs approches et leurs stratégies d'optimisation.
