栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

如何在Java中使用3DES加密/解密?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

如何在Java中使用3DES加密/解密?

除了base 64编码位(你提到的是测试)外,你的代码还不错,输出可能没有意义的原因是你显示的是原始字节数组(对字节数组执行toString()返回其内部Java引用,不是的字符串表示的内容)。这是一个清理过的版本,并输出“ kyle boon”作为解码后的字符串:

import java.security.MessageDigest;import java.util.Arrays;import javax.crypto.Cipher;import javax.crypto.SecretKey;import javax.crypto.spec.IvParameterSpec;import javax.crypto.spec.SecretKeySpec;public class TripleDESTest {    public static void main(String[] args) throws Exception {        String text = "kyle boon";        byte[] predtext = new TripleDESTest().encrypt(text);        String depredtext = new TripleDESTest().decrypt(predtext);        System.out.println(predtext); // this is a byte array, you'll just see a reference to an array        System.out.println(depredtext); // This correctly shows "kyle boon"    }    public byte[] encrypt(String message) throws Exception {        final MessageDigest md = MessageDigest.getInstance("md5");        final byte[] digestOfPassword = md.digest("HG58YZ3CR9"     .getBytes("utf-8"));        final byte[] keyBytes = Arrays.copyOf(digestOfPassword, 24);        for (int j = 0, k = 16; j < 8;) { keyBytes[k++] = keyBytes[j++];        }        final SecretKey key = new SecretKeySpec(keyBytes, "DESede");        final IvParameterSpec iv = new IvParameterSpec(new byte[8]);        final Cipher cipher = Cipher.getInstance("DESede/CBC/PKCS5Padding");        cipher.init(Cipher.ENCRYPT_MODE, key, iv);        final byte[] plainTextBytes = message.getBytes("utf-8");        final byte[] cipherText = cipher.doFinal(plainTextBytes);        // final String enpredCipherText = new sun.misc.base64Enprer()        // .enpre(cipherText);        return cipherText;    }    public String decrypt(byte[] message) throws Exception {        final MessageDigest md = MessageDigest.getInstance("md5");        final byte[] digestOfPassword = md.digest("HG58YZ3CR9"     .getBytes("utf-8"));        final byte[] keyBytes = Arrays.copyOf(digestOfPassword, 24);        for (int j = 0, k = 16; j < 8;) { keyBytes[k++] = keyBytes[j++];        }        final SecretKey key = new SecretKeySpec(keyBytes, "DESede");        final IvParameterSpec iv = new IvParameterSpec(new byte[8]);        final Cipher decipher = Cipher.getInstance("DESede/CBC/PKCS5Padding");        decipher.init(Cipher.DECRYPT_MODE, key, iv);        // final byte[] encData = new        // sun.misc.base64Deprer().depreBuffer(message);        final byte[] plainText = decipher.doFinal(message);        return new String(plainText, "UTF-8");    }}


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/400349.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号