DESede/ECB/PKCS5Padding 3des 加密 返回十六进制 Java和PHP通用

1,197次阅读
没有评论

共计 1013 个字符,预计需要花费 3 分钟才能阅读完成。

请注意 : key 必须 24位,PHP7.1或者以上用,openssl_encrypt 中的 method :DES-EDE3 ,对应Java中的DESede/ECB

Java用法

public static String byte2hex(byte[] b) {
        String hs="";
        String stmp="";

        for (int n=0;n<b.length;n++) {
            stmp=(java.lang.Integer.toHexString(b[n] & 0XFF));
            if (stmp.length()==1) hs=hs+"0"+stmp;
            else hs=hs+stmp;
            if (n<b.length-1)  hs=hs;
        }
        return hs.toUpperCase();
    }
    public static void main(String[] args) throws NoSuchPaddingException, NoSuchAlgorithmException, UnsupportedEncodingException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException {
        String txt="66666";
        String key="123456781234567812345678"; // 必须24位
        //加密
        String keyStr = key;
        byte key_byte[] = keyStr.getBytes();// 3DES 24 bytes key
        SecretKey k = new SecretKeySpec(key_byte, "DESede");
        javax.crypto.Cipher cipher = javax.crypto.Cipher.getInstance("DESede");
        cipher.init(javax.crypto.Cipher.ENCRYPT_MODE, k);
        byte[] b = cipher.doFinal(txt.getBytes("utf-8"));
        String enc_txt = byte2hex(b);
        System.out.println(enc_txt);
    }

PHP用法

$miwen = openssl_encrypt('66666', 'DES-EDE3', '123456781234567812345678',OPENSSL_RAW_DATA);
var_dump(bin2hex($miwen));

正文完
 0
Eric chan
版权声明:本站原创文章,由 Eric chan 于2019-10-06发表,共计1013字。
转载说明:除特殊说明外本站文章皆由CC-4.0协议发布,转载请注明出处。