java程序怎么加密

时间:2025-01-25 03:19:07 单机游戏

在Java中加密程序可以通过多种方式实现,包括对称加密和非对称加密。以下是一些常用的加密方法和相关步骤:

对称加密

AES:高级加密标准,支持128、192和256位密钥长度。

DES:数据加密标准,使用56位密钥,安全性较低,已被AES取代。

示例代码(AES加密):

```java

import javax.crypto.Cipher;

import javax.crypto.KeyGenerator;

import javax.crypto.SecretKey;

import java.util.Base64;

public class AESExample {

public static void main(String[] args) throws Exception {

// 生成AES密钥

KeyGenerator keyGen = KeyGenerator.getInstance("AES");

keyGen.init(128); // 使用128位密钥

SecretKey secretKey = keyGen.generateKey();

// 待加密的数据

String originalText = "Hello, 这是需要加密的数据!";

// 加密

Cipher cipher = Cipher.getInstance("AES");

cipher.init(Cipher.ENCRYPT_MODE, secretKey);

byte[] encryptedBytes = cipher.doFinal(originalText.getBytes());

String encryptedText = Base64.getEncoder().encodeToString(encryptedBytes);

System.out.println("加密后: " + encryptedText);

}

}

```

非对称加密

RSA:使用公钥加密,私钥解密。

示例代码(RSA加密):

```java

import javax.crypto.Cipher;

import java.security.KeyPair;

import java.security.KeyPairGenerator;

import java.security.PrivateKey;

import java.security.PublicKey;

import java.util.Base64;

public class RSAExample {

public static void main(String[] args) throws Exception {

// 生成RSA密钥对

KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("RSA");

keyPairGen.initialize(2048);

KeyPair keyPair = keyPairGen.generateKeyPair();

PublicKey publicKey = keyPair.getPublic();

PrivateKey privateKey = keyPair.getPrivate();

// 待加密的数据

String originalText = "Hello, 这是需要加密的数据!";

// 加密

Cipher cipher = Cipher.getInstance("RSA");

cipher.init(Cipher.ENCRYPT_MODE, publicKey);

byte[] encryptedBytes = cipher.doFinal(originalText.getBytes());

String encryptedText = Base64.getEncoder().encodeToString(encryptedBytes);

System.out.println("加密后: " + encryptedText);

// 解密

cipher.init(Cipher.DECRYPT_MODE, privateKey);

byte[] decryptedBytes = cipher.doFinal(Base64.getDecoder().decode(encryptedText));

String decryptedText = new String(decryptedBytes);

System.out.println("解密后: " + decryptedText);

}

}

```

其他加密方法

XOR异或加密:简单高效,适用于简单项目。

MD5消息摘要:将任意长度的数据转换成固定长度的哈希值,常用于数据完整性验证。

示例代码(XOR异或加密):

```java

public class SimpleClassEncryptor {

private static final byte KEY = (byte) 0xFF;

public static byte[] encrypt(byte[] classData) {

byte[] result = new byte[classData.length];

for (int i = 0; i < classData.length; i++) {

result[i] = (byte) (classData[i] ^ KEY);

}

return result;

}

public static byte[] decrypt(byte[] encryptedData) {

return encrypt(encryptedData); // 异或运算的特性,加密解密用同一个方法

}

}

```

示例代码(MD5加密):