Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
467 views
in Technique[技术] by (71.8m points)

帮忙用PHP实现如下Java的功能

package com.company;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.Arrays;
import javax.crypto.Cipher;
import javax.crypto.spec.DESKeySpec;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

public class AES256Util {

    private static final byte[] RAW = {50, -115, -81, -50, -32, 55, -120, 112, 4, -98, -78, -8, 5, 56, -46, -19};

    // 加密
    public static String encrypt(String s) throws Exception {

        byte[] raw = Arrays.copyOf(RAW, 16);
        SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        IvParameterSpec iv = new IvParameterSpec(raw);
        cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv);
        byte[] encrypted = cipher.doFinal(s.getBytes("UTF-8"));
        return URLEncoder.encode(new String(encrypted,"ISO-8859-1"), "ISO-8859-1");
    }

    // 解密
    public static String decrypt(String s) throws Exception {
        byte[] raw = Arrays.copyOf(RAW, 16);
        SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        IvParameterSpec iv = new IvParameterSpec(raw);
        cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv);
        byte[] encrypted = URLDecoder.decode(s, "ISO-8859-1").getBytes("ISO-8859-1");
        byte[] original = cipher.doFinal(encrypted);
        String originalString = new String(original, "UTF-8");
        return originalString;
    }

    public static void main(String args[]) throws Exception {
        String msg = AES256Util.encrypt("我只是个测试!");
        System.out.println(msg);
        System.out.println(AES256Util.decrypt(msg));
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

你给你一个结果,比如加密 我只是个测试! 密文 是什么? 多加密几个。

提供,明文 和 密文,然后用php实现的时候 才知道 明文 加密后 密文 对不对呀。


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...