Java로 구현된 일반적인 암호화 및 암호 해독 알고리즘
Java는 매우 인기 있는 프로그래밍 언어이며 다양한 분야에서 널리 사용됩니다. 실제 응용 프로그램에서 데이터 암호화 및 암호 해독은 매우 일반적인 요구 사항입니다. Java는 다양한 암호화 및 암호 해독 알고리즘을 제공합니다. 이 기사에서는 몇 가지 일반적인 알고리즘을 간략하게 소개합니다.
1. 대칭 암호화 알고리즘
개인 키 암호화 알고리즘이라고도 하는 대칭 암호화 알고리즘은 암호화 및 복호화에 동일한 키를 사용합니다. 일반적인 대칭 암호화 알고리즘에는 DES, 3DES, AES 등이 포함됩니다.
- DES 알고리즘
DES(데이터 암호화 표준)는 키 길이가 56비트인 고전적인 대칭 암호화 알고리즘입니다. DES 알고리즘을 사용하는 경우 먼저 키를 생성한 다음 키를 사용하여 일반 텍스트를 암호화하여 암호문을 얻은 다음 키를 사용하여 암호문을 해독하여 일반 텍스트를 얻습니다. Java에서는 JCE(Java Cryptography Extension)에서 제공하는 DES 암호화 및 복호화 기능을 사용할 수 있습니다. 샘플 코드는 다음과 같습니다.
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); } }
- 3DES 알고리즘
3DES(Triple DES) 알고리즘은 DES 알고리즘을 기반으로 강화된 암호화 알고리즘으로, 키 길이는 168비트입니다. 3DES 알고리즘의 암호화 및 복호화 프로세스는 DES 알고리즘과 유사하며 Java에서 제공하는 JCE 라이브러리를 사용하여 구현할 수 있습니다. 샘플 코드는 다음과 같습니다.
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); } }
- AES 알고리즘
AES(Advanced Encryption Standard) 알고리즘은 고급 암호화 표준이며 현재 가장 널리 사용되는 대칭 암호화 알고리즘 중 하나입니다. AES 알고리즘의 키 길이는 일반적으로 128비트, 192비트 또는 256비트입니다. Java에서는 JCE 라이브러리에서 제공하는 AES 암호화 및 복호화 기능을 사용할 수도 있습니다. 샘플 코드는 다음과 같습니다.
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. 비대칭 암호화 알고리즘
비대칭 암호화 알고리즘은 공개키 암호화 알고리즘이라고도 하며, 암호화와 복호화에 서로 다른 키를 사용합니다. 일반적인 비대칭 암호화 알고리즘에는 RSA 알고리즘이 포함됩니다.
- RSA 알고리즘
RSA 알고리즘은 비대칭 암호화 알고리즘이자 큰 정수를 기반으로 하는 정수론 암호화 알고리즘입니다. RSA 알고리즘의 특징은 공개키는 공개하고 키는 비공개로 하여 보안성이 높다는 점이다. Java에서는 JCE 라이브러리에서 제공하는 RSA 암호화 및 복호화 기능을 사용할 수도 있습니다. 샘플 코드는 다음과 같습니다.
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); } }
위는 Java로 구현된 몇 가지 일반적인 암호화 및 복호화 알고리즘입니다. 실제 애플리케이션에서는 실제 상황에 따라 자신에게 적합한 암호화 및 복호화 알고리즘을 선택하고 특정 요구에 따라 조정 및 최적화해야 합니다.
위 내용은 Java로 구현된 일반적인 암호화 및 암호 해독 알고리즘의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

핫 AI 도구

Undresser.AI Undress
사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover
사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool
무료로 이미지를 벗다

Clothoff.io
AI 옷 제거제

AI Hentai Generator
AI Hentai를 무료로 생성하십시오.

인기 기사

뜨거운 도구

메모장++7.3.1
사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전
중국어 버전, 사용하기 매우 쉽습니다.

스튜디오 13.0.1 보내기
강력한 PHP 통합 개발 환경

드림위버 CS6
시각적 웹 개발 도구

SublimeText3 Mac 버전
신 수준의 코드 편집 소프트웨어(SublimeText3)

뜨거운 주제











Java의 클래스 로딩에는 부트 스트랩, 확장 및 응용 프로그램 클래스 로더가있는 계층 적 시스템을 사용하여 클래스로드, 링크 및 초기화 클래스가 포함됩니다. 학부모 위임 모델은 핵심 클래스가 먼저로드되어 사용자 정의 클래스 LOA에 영향을 미치도록합니다.

이 기사는 카페인 및 구아바 캐시를 사용하여 자바에서 다단계 캐싱을 구현하여 응용 프로그램 성능을 향상시키는 것에 대해 설명합니다. 구성 및 퇴거 정책 관리 Best Pra와 함께 설정, 통합 및 성능 이점을 다룹니다.

이 기사는 캐싱 및 게으른 하중과 같은 고급 기능을 사용하여 객체 관계 매핑에 JPA를 사용하는 것에 대해 설명합니다. 잠재적 인 함정을 강조하면서 성능을 최적화하기위한 설정, 엔티티 매핑 및 모범 사례를 다룹니다. [159 문자]

이 기사에서는 Java 프로젝트 관리, 구축 자동화 및 종속성 해상도에 Maven 및 Gradle을 사용하여 접근 방식과 최적화 전략을 비교합니다.

이 기사에서는 Maven 및 Gradle과 같은 도구를 사용하여 적절한 버전 및 종속성 관리로 사용자 정의 Java 라이브러리 (JAR Files)를 작성하고 사용하는 것에 대해 설명합니다.
