php 3des加密解密和 java 3des互通
时间: 2023-08-04 07:38:44 浏览: 129
PHP 3DES 加密解密
PHP和Java都有支持3DES加密和解密的库,可以通过这些库来实现互通。以下是一个简单的PHP和Java之间3DES加密和解密的例子:
PHP代码:
```php
$key = "123456789012345678901234"; // 24位密钥
$data = "Hello, world!"; // 待加密的数据
// 加密
$encrypted = openssl_encrypt($data, "DES-EDE3", $key, OPENSSL_RAW_DATA);
$encrypted = base64_encode($encrypted); // 转成base64字符串
// 解密
$encrypted = base64_decode($encrypted); // 将base64字符串转成二进制数据
$decrypted = openssl_decrypt($encrypted, "DES-EDE3", $key, OPENSSL_RAW_DATA);
echo $decrypted; // 输出:Hello, world!
```
Java代码:
```java
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESedeKeySpec;
import java.util.Base64;
public class Main {
public static void main(String[] args) throws Exception {
String key = "123456789012345678901234"; // 24位密钥
String data = "Hello, world!"; // 待加密的数据
// 加密
byte[] encrypted = encrypt(data.getBytes("UTF-8"), key.getBytes("UTF-8"));
String encryptedStr = Base64.getEncoder().encodeToString(encrypted); // 转成base64字符串
System.out.println(encryptedStr);
// 解密
byte[] encryptedBytes = Base64.getDecoder().decode(encryptedStr); // 将base64字符串转成二进制数据
byte[] decrypted = decrypt(encryptedBytes, key.getBytes("UTF-8"));
System.out.println(new String(decrypted, "UTF-8")); // 输出:Hello, world!
}
public static byte[] encrypt(byte[] data, byte[] key) throws Exception {
DESedeKeySpec spec = new DESedeKeySpec(key);
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DESede");
SecretKey secretKey = keyFactory.generateSecret(spec);
Cipher cipher = Cipher.getInstance("DESede/ECB/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, secretKey);
return cipher.doFinal(data);
}
public static byte[] decrypt(byte[] data, byte[] key) throws Exception {
DESedeKeySpec spec = new DESedeKeySpec(key);
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DESede");
SecretKey secretKey = keyFactory.generateSecret(spec);
Cipher cipher = Cipher.getInstance("DESede/ECB/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, secretKey);
return cipher.doFinal(data);
}
}
```
这两段代码都使用了3DES算法进行加密和解密,PHP使用了OpenSSL库,Java使用了JCE库。在加密时,PHP和Java都使用了相同的密钥和加密模式(ECB),因此可以互相解密。
阅读全文