java and php aes相互加密解密。

1:RSA加密算法:

1-1:Java RSA公约加密代码

    public static byte[] encryptByPublicKey(byte[] data, String publicKey) throws Exception {
        byte[] keyBytes = Base64.decodeBase64(publicKey);
        X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        Key publicK = keyFactory.generatePublic(x509KeySpec);
        // 对数据加密
        Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
        cipher.init(Cipher.ENCRYPT_MODE, publicK);
        int inputLen = data.length;
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        int offSet = 0;
        byte[] cache;
        int i = 0;
        // 对数据分段加密
        while (inputLen - offSet > 0) {
            if (inputLen - offSet > MAX_ENCRYPT_BLOCK) {
                cache = cipher.doFinal(data, offSet, MAX_ENCRYPT_BLOCK);
            } else {
                cache = cipher.doFinal(data, offSet, inputLen - offSet);
            }
            out.write(cache, 0, cache.length);
            i++;
            offSet = i * MAX_ENCRYPT_BLOCK;
        }
        byte[] encryptedData = out.toByteArray();
        out.close();
        return encryptedData;

    }

1-2:等价PHP代码公约加密代码

//用公钥加密后数据,网上传输
$encrypted = "";
//PHP代码进行RSA的加密解密(用公钥加密)
openssl_public_encrypt($encKeyStr,$encrypted, $pingtaiPublicKey);
//密钥密文 换成Hex字符串
$encKey = strtoupper(bin2hex($encrypted));

2:sha256加密算法

2-1:Java代码

MessageDigest md = MessageDigest.getInstance("SHA-256");
md.update(bt);
strDes = bytes2Hex(md.digest()); // to HexString

2-2:等价PHP代码

$macStr = hash('sha256', $macStr, true);

$macStr = bin2hex($macStr);

3:AES加密解密

3-1:Java代码

    public static byte[] encrypt(String content, String password) {
            SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
            secureRandom.setSeed(password.getBytes("utf-8"));
            KeyGenerator kgen = KeyGenerator.getInstance("AES");
            kgen.init(128, secureRandom);
            SecretKey secretKey = kgen.generateKey();
            byte[] enCodeFormat = secretKey.getEncoded();
            SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES");
            Cipher cipher = Cipher.getInstance("AES");// 创建密码器
            byte[] byteContent = content.getBytes("GBK");
            cipher.init(Cipher.ENCRYPT_MODE, key);// 初始化
            byte[] result = cipher.doFinal(byteContent);
            return result; // 加密
    }


    /**
     * 解密
     *
     * @param content  待解密内容
     * @param password 解密密钥
     * @return
     */
    public static byte[] decrypt(byte[] content, String password) {
    SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
    secureRandom.setSeed(password.getBytes("utf-8"));


    KeyGenerator kgen = KeyGenerator.getInstance("AES");
    kgen.init(128, secureRandom);
    SecretKey secretKey = kgen.generateKey();
    byte[] enCodeFormat = secretKey.getEncoded();
    SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES");
    Cipher cipher = Cipher.getInstance("AES");// 创建密码器
    cipher.init(Cipher.DECRYPT_MODE, key);// 初始化
    byte[] result = cipher.doFinal(content);
    return result; // 加密
    }

3-2:PHP代码

if (!function_exists('hex2bin')) {
    function hex2bin($str) {
        $sbin = "";
        $len = strlen($str);
        for ($i = 0; $i < $len; $i += 2) {
            $sbin .= pack("H*", substr($str, $i, 2));
        }


        return $sbin;
    }
}


class AESUtil {


    private $_cipher = MCRYPT_RIJNDAEL_128;
    private $_mode = MCRYPT_MODE_ECB;


    private function _pkcs5Pad($text, $blockSize) {
        $pad = $blockSize - (strlen($text) % $blockSize);
        return $text . str_repeat(chr($pad), $pad);
    }


    private function _pkcs5Unpad($text) {
        $end = substr($text, -1);
        $last = ord($end);
        $len = strlen($text) - $last;
        if (substr($text, $len) == str_repeat($end, $last)) {
            return substr($text, 0, $len);
        }
        return false;
    }


    public function encrypt($encrypt, $password) {
    // 对应Java SecureRandom.getInstance("SHA1PRNG")
    $key = substr(openssl_digest(openssl_digest($password, 'sha1', true), 'sha1', true), 0, 16);
        $blockSize = mcrypt_get_block_size($this->_cipher, $this->_mode);
        $paddedData = $this->_pkcs5Pad($encrypt, $blockSize);
        $ivSize = mcrypt_get_iv_size($this->_cipher, $this->_mode);
        $iv = mcrypt_create_iv($ivSize, MCRYPT_RAND);
        $encrypted = mcrypt_encrypt($this->_cipher, $key, $paddedData, $this->_mode, $iv);
        return bin2hex($encrypted);
    }


    public function decrypt($decrypt, $password) {
    $key = substr(openssl_digest(openssl_digest($password, 'sha1', true), 'sha1', true), 0, 16);
        $decoded = hex2bin($decrypt);
        $blockSize = mcrypt_get_iv_size($this->_cipher, $this->_mode);
        $iv = mcrypt_create_iv($blockSize, MCRYPT_RAND);
        $decrypted = mcrypt_decrypt($this->_cipher, $key, $decoded, $this->_mode, $iv);
        return $this->_pkcs5Unpad($decrypted);
    }
}

4:私钥加密

4-1:Java代码

    /**
     * <p>
     * 私钥加密
     * </p>
     *
     * @param data       源数据
     * @param privateKey 私钥(BASE64编码)
     * @return
     * @throws Exception
     */
    public static byte[] encryptByPrivateKey(byte[] data, String privateKey)
            throws Exception {
        byte[] keyBytes = Base64.decodeBase64(privateKey);
        PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        Key privateK = keyFactory.generatePrivate(pkcs8KeySpec);
        Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
        cipher.init(Cipher.ENCRYPT_MODE, privateK);
        int inputLen = data.length;
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        int offSet = 0;
        byte[] cache;
        int i = 0;
        // 对数据分段加密
        while (inputLen - offSet > 0) {
            if (inputLen - offSet > MAX_ENCRYPT_BLOCK) {
                cache = cipher.doFinal(data, offSet, MAX_ENCRYPT_BLOCK);
            } else {
                cache = cipher.doFinal(data, offSet, inputLen - offSet);
            }
            out.write(cache, 0, cache.length);
            i++;
            offSet = i * MAX_ENCRYPT_BLOCK;
        }
        byte[] encryptedData = out.toByteArray();
        out.close();
        return encryptedData;
    }

4-2:PHP代码私钥加密 

$maced="";
openssl_private_encrypt($macStr, $maced, $merPrivateKey); //私钥加密  
$mac = strtoupper(bin2hex($maced));

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Java AES256加密解密是一种常用的对称加密算法,它使用256位的密钥对数据进行加密解密。下面是Java中使用AES256进行加密解密的基本步骤: 1. 导入相关的类库: ```java import javax.crypto.Cipher; import javax.crypto.spec.SecretKeySpec; import java.nio.charset.StandardCharsets; import java.util.Base64; ``` 2. 定义加密解密方法: ```java public class AESUtil { private static final String ALGORITHM = "AES"; private static final TRANSFORMATION = "AES/ECB/PKCS5Padding"; public static String encrypt(String data, String key) throws Exception { SecretKeySpec secretKey = new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8), ALGORITHM); Cipher cipher = Cipher.getInstance(TRANSFORMATION); cipher.init(Cipher.ENCRYPT_MODE, secretKey); byte[] encryptedBytes = cipher.doFinal(data.getBytes(StandardCharsets.UTF_8)); return Base64.getEncoder().encodeToString(encryptedBytes); } public static String decrypt(String encryptedData, String key) throws Exception { SecretKeySpec secretKey = new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8), ALGORITHM); Cipher cipher = Cipher.getInstance(TRANSFORMATION); cipher.init(Cipher.DECRYPT_MODE, secretKey); byte[] decryptedBytes = cipher.doFinal(Base64.getDecoder().decode(encryptedData)); return new String(decryptedBytes, StandardCharsets.UTF_8); } } ``` 3. 使用加密解密方法: ```java public class Main { public static void main(String[] args) { try { String data = "Hello, World!"; String key = "0123456789abcdef0123456789abcdef"; // 256位密钥 String encryptedData = AESUtil.encrypt(data, key); System.out.println("加密后的数据:" + encryptedData); String decryptedData = AESUtil.decrypt(encryptedData, key); System.out.println("解密后的数据:" + decryptedData); } catch (Exception e) { e.printStackTrace(); } } } ``` 以上代码演示了如何使用Java进行AES256加密解密。需要注意的是,密钥的长度必须是256位(32字节),并且在实际应用中应该使用安全的方式来保存和传输密钥。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值