PHP vs Java:加密功能的代码行数大比拼!

起因:接到需求,将一个 java 接口中的 AES 加密功能转为 PHP 代码实现。

Java 代码

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.security.Key;
import java.util.Base64;

public class EncryptionExample {
    public static String encrypt(String data, String key) throws Exception {
        // 将密钥转换为字节
        byte[] keyBytes = key.getBytes();
        // 创建一个AES密钥
        SecretKeySpec secretKeySpec = new SecretKeySpec(keyBytes, "AES");
        
        // 使用AES/ECB/PKCS5Padding模式实例化Cipher对象
        Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
        // 初始化为加密模式
        cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);
        
        // 执行加密操作
        byte[] encryptedBytes = cipher.doFinal(data.getBytes());
        
        // 将加密后的字节转换为大写的十六进制字符串
        String encryptedHex = bytesToHex(encryptedBytes).toUpperCase();
        
        return encryptedHex;
    }
    
    // 辅助方法:将字节转换为十六进制字符串
    private static String bytesToHex(byte[] bytes) {
        StringBuilder hexString = new StringBuilder();
        for (byte b : bytes) {
            String hex = Integer.toHexString(0xff & b);
            if (hex.length() == 1) hexString.append('0');
            hexString.append(hex);
        }
        return hexString.toString();
    }

    public static void main(String[] args) {
        try {
            String originalData = "Your data here"; // 需要加密的数据
            String aesKey = "YourAESKeyHere"; // AES密钥,确保是256位(32字节)
            
            // 确保密钥长度正确,可能需要根据实际情况调整密钥生成或处理逻辑
            if (aesKey.getBytes().length != 32) {
                throw new IllegalArgumentException("Key is not 32 bytes (256 bits)");
            }
            
            String encryptedData = encrypt(originalData, aesKey);
            System.out.println("Encrypted (Hex): " + encryptedData);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

一行 PHP 代码实现

strtoupper(bin2hex(openssl_encrypt('Your data here', 'AES-256-ECB', 'YourAESKeyHere', OPENSSL_RAW_DATA)));

结论

PHP 完胜!果然是世界上最好的语言! 古人诚不欺我!
所以,你是选择快餐还是精致料理呢

2 个赞

幸亏你 throws Exception 了

幸亏你 throws Exception 了.

哈哈哈 :joy:

代码不长? 老板怎么看得到工作量?工资怎么能高?

2 个赞

:smile:吾皇好速度,是每篇帖子都要先 review 吗?

2 个赞

为了升级,水一篇处女作 :sweat_smile:

2 个赞