用java实现,1、编写Diffie-Hellman程序,协商出用于收、发双方的加、解密密钥K; 2、模拟发送端A,用协商出的密钥K,通过对称加密算法(具体算法不限)将文本文件加密;模拟接收端B,用协商出的密钥K,对接收到的密文解密
时间: 2024-06-09 08:05:40 浏览: 71
以下是用Java实现Diffie-Hellman密钥交换协议,并使用对称加密算法进行文件加解密的示例代码:
DiffieHellman.java
```java
import java.math.BigInteger;
import java.security.SecureRandom;
public class DiffieHellman {
private BigInteger prime;
private BigInteger generator;
private BigInteger privateKey;
private BigInteger publicKey;
public DiffieHellman(BigInteger prime, BigInteger generator) {
this.prime = prime;
this.generator = generator;
this.privateKey = generatePrivateKey(prime);
this.publicKey = generator.modPow(privateKey, prime);
}
public BigInteger getPublicKey() {
return publicKey;
}
public BigInteger getSharedSecret(BigInteger otherPublicKey) {
return otherPublicKey.modPow(privateKey, prime);
}
private BigInteger generatePrivateKey(BigInteger limit) {
SecureRandom random = new SecureRandom();
BigInteger privateKey;
do {
privateKey = new BigInteger(limit.bitLength(), random);
} while (privateKey.compareTo(BigInteger.ONE) <= 0 || privateKey.compareTo(limit.subtract(BigInteger.ONE)) >= 0);
return privateKey;
}
}
```
FileEncryption.java
```java
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.io.*;
import java.math.BigInteger;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.security.Key;
import java.security.MessageDigest;
import java.security.SecureRandom;
import java.util.Arrays;
public class FileEncryption {
private static final String ALGORITHM = "AES";
private static final int KEY_SIZE = 128;
public static void main(String[] args) throws Exception {
// 1. Diffie-Hellman key exchange
BigInteger prime = new BigInteger("FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E088A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9A63A3620FFFFFFFFFFFFFFFF", 16);
BigInteger generator = BigInteger.TWO;
DiffieHellman alice = new DiffieHellman(prime, generator);
DiffieHellman bob = new DiffieHellman(prime, generator);
// simulate Alice and Bob exchanging public keys
BigInteger alicePublicKey = alice.getPublicKey();
BigInteger bobPublicKey = bob.getPublicKey();
BigInteger aliceSharedSecret = alice.getSharedSecret(bobPublicKey);
BigInteger bobSharedSecret = bob.getSharedSecret(alicePublicKey);
System.out.println("Alice's public key: " + alicePublicKey);
System.out.println("Bob's public key: " + bobPublicKey);
System.out.println("Alice's shared secret: " + aliceSharedSecret);
System.out.println("Bob's shared secret: " + bobSharedSecret);
// 2. file encryption
String inputFileName = "input.txt";
String outputFileName = "output.txt";
byte[] key = generateKey(aliceSharedSecret.toByteArray());
System.out.println("Encryption key: " + Arrays.toString(key));
encryptFile(inputFileName, outputFileName, key);
System.out.println("File encrypted.");
// 3. file decryption
String decryptedFileName = "decrypted.txt";
byte[] decryptedKey = generateKey(bobSharedSecret.toByteArray());
System.out.println("Decryption key: " + Arrays.toString(decryptedKey));
decryptFile(outputFileName, decryptedFileName, decryptedKey);
System.out.println("File decrypted.");
}
private static byte[] generateKey(byte[] sharedSecret) throws Exception {
MessageDigest sha = MessageDigest.getInstance("SHA-256");
byte[] key = sha.digest(sharedSecret);
return Arrays.copyOf(key, KEY_SIZE / 8);
}
private static void encryptFile(String inputFileName, String outputFileName, byte[] key) throws Exception {
Path inputFile = Paths.get(inputFileName);
Path outputFile = Paths.get(outputFileName);
try (InputStream inputStream = Files.newInputStream(inputFile);
OutputStream outputStream = new BufferedOutputStream(Files.newOutputStream(outputFile))) {
Key secretKey = new SecretKeySpec(key, ALGORITHM);
Cipher cipher = Cipher.getInstance(ALGORITHM);
cipher.init(Cipher.ENCRYPT_MODE, secretKey, new SecureRandom());
byte[] buffer = new byte[4096];
int bytesRead;
while ((bytesRead = inputStream.read(buffer)) != -1) {
byte[] encryptedBytes = cipher.update(buffer, 0, bytesRead);
outputStream.write(encryptedBytes);
}
byte[] encryptedBytes = cipher.doFinal();
outputStream.write(encryptedBytes);
}
}
private static void decryptFile(String inputFileName, String outputFileName, byte[] key) throws Exception {
Path inputFile = Paths.get(inputFileName);
Path outputFile = Paths.get(outputFileName);
try (InputStream inputStream = Files.newInputStream(inputFile);
OutputStream outputStream = new BufferedOutputStream(Files.newOutputStream(outputFile))) {
Key secretKey = new SecretKeySpec(key, ALGORITHM);
Cipher cipher = Cipher.getInstance(ALGORITHM);
cipher.init(Cipher.DECRYPT_MODE, secretKey, new SecureRandom());
byte[] buffer = new byte[4096];
int bytesRead;
while ((bytesRead = inputStream.read(buffer)) != -1) {
byte[] decryptedBytes = cipher.update(buffer, 0, bytesRead);
outputStream.write(decryptedBytes);
}
byte[] decryptedBytes = cipher.doFinal();
outputStream.write(decryptedBytes);
}
}
}
```
在运行以上代码时,需要确保文件`input.txt`存在,且文件内容不为空。运行程序后,会输出Alice和Bob交换公钥、共享密钥,以及加密和解密的过程。在运行完成后,会生成密文文件`output.txt`和解密后的明文文件`decrypted.txt`。
阅读全文