如何使用JAVA实现对字符串的DES加密和解密
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了如何使用JAVA实现对字符串的DES加密和解密相关的知识,希望对你有一定的参考价值。
java加密字符串可以使用des加密算法,实例如下:package test;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.security.*;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
/**
* 加密解密
*
* @author shy.qiu
* @since http://blog.csdn.net/qiushyfm
*/
public class CryptTest
/**
* 进行MD5加密
*
* @param info
* 要加密的信息
* @return String 加密后的字符串
*/
public String encryptToMD5(String info)
byte[] digesta = null;
try
// 得到一个md5的消息摘要
MessageDigest alga = MessageDigest.getInstance("MD5");
// 添加要进行计算摘要的信息
alga.update(info.getBytes());
// 得到该摘要
digesta = alga.digest();
catch (NoSuchAlgorithmException e)
e.printStackTrace();
// 将摘要转为字符串
String rs = byte2hex(digesta);
return rs;
/**
* 进行SHA加密
*
* @param info
* 要加密的信息
* @return String 加密后的字符串
*/
public String encryptToSHA(String info)
byte[] digesta = null;
try
// 得到一个SHA-1的消息摘要
MessageDigest alga = MessageDigest.getInstance("SHA-1");
// 添加要进行计算摘要的信息
alga.update(info.getBytes());
// 得到该摘要
digesta = alga.digest();
catch (NoSuchAlgorithmException e)
e.printStackTrace();
// 将摘要转为字符串
String rs = byte2hex(digesta);
return rs;
// //////////////////////////////////////////////////////////////////////////
/**
* 创建密匙
*
* @param algorithm
* 加密算法,可用 DES,DESede,Blowfish
* @return SecretKey 秘密(对称)密钥
*/
public SecretKey createSecretKey(String algorithm)
// 声明KeyGenerator对象
KeyGenerator keygen;
// 声明 密钥对象
SecretKey deskey = null;
try
// 返回生成指定算法的秘密密钥的 KeyGenerator 对象
keygen = KeyGenerator.getInstance(algorithm);
// 生成一个密钥
deskey = keygen.generateKey();
catch (NoSuchAlgorithmException e)
e.printStackTrace();
// 返回密匙
return deskey;
/**
* 根据密匙进行DES加密
*
* @param key
* 密匙
* @param info
* 要加密的信息
* @return String 加密后的信息
*/
public String encryptToDES(SecretKey key, String info)
// 定义 加密算法,可用 DES,DESede,Blowfish
String Algorithm = "DES";
// 加密随机数生成器 (RNG),(可以不写)
SecureRandom sr = new SecureRandom();
// 定义要生成的密文
byte[] cipherByte = null;
try
// 得到加密/解密器
Cipher c1 = Cipher.getInstance(Algorithm);
// 用指定的密钥和模式初始化Cipher对象
// 参数:(ENCRYPT_MODE, DECRYPT_MODE, WRAP_MODE,UNWRAP_MODE)
c1.init(Cipher.ENCRYPT_MODE, key, sr);
// 对要加密的内容进行编码处理,
cipherByte = c1.doFinal(info.getBytes());
catch (Exception e)
e.printStackTrace();
// 返回密文的十六进制形式
return byte2hex(cipherByte);
/**
* 根据密匙进行DES解密
*
* @param key
* 密匙
* @param sInfo
* 要解密的密文
* @return String 返回解密后信息
*/
public String decryptByDES(SecretKey key, String sInfo)
// 定义 加密算法,
String Algorithm = "DES";
// 加密随机数生成器 (RNG)
SecureRandom sr = new SecureRandom();
byte[] cipherByte = null;
try
// 得到加密/解密器
Cipher c1 = Cipher.getInstance(Algorithm);
// 用指定的密钥和模式初始化Cipher对象
c1.init(Cipher.DECRYPT_MODE, key, sr);
// 对要解密的内容进行编码处理
cipherByte = c1.doFinal(hex2byte(sInfo));
catch (Exception e)
e.printStackTrace();
// return byte2hex(cipherByte);
return new String(cipherByte);
// /////////////////////////////////////////////////////////////////////////////
/**
* 创建密匙组,并将公匙,私匙放入到指定文件中
*
* 默认放入mykeys.bat文件中
*/
public void createPairKey()
try
// 根据特定的算法一个密钥对生成器
KeyPairGenerator keygen = KeyPairGenerator.getInstance("DSA");
// 加密随机数生成器 (RNG)
SecureRandom random = new SecureRandom();
// 重新设置此随机对象的种子
random.setSeed(1000);
// 使用给定的随机源(和默认的参数集合)初始化确定密钥大小的密钥对生成器
keygen.initialize(512, random);// keygen.initialize(512);
// 生成密钥组
KeyPair keys = keygen.generateKeyPair();
// 得到公匙
PublicKey pubkey = keys.getPublic();
// 得到私匙
PrivateKey prikey = keys.getPrivate();
// 将公匙私匙写入到文件当中
doObjToFile("mykeys.bat", new Object[] prikey, pubkey );
catch (NoSuchAlgorithmException e)
e.printStackTrace();
/**
* 利用私匙对信息进行签名 把签名后的信息放入到指定的文件中
*
* @param info
* 要签名的信息
* @param signfile
* 存入的文件
*/
public void signToInfo(String info, String signfile)
// 从文件当中读取私匙
PrivateKey myprikey = (PrivateKey) getObjFromFile("mykeys.bat", 1);
// 从文件中读取公匙
PublicKey mypubkey = (PublicKey) getObjFromFile("mykeys.bat", 2);
try
// Signature 对象可用来生成和验证数字签名
Signature signet = Signature.getInstance("DSA");
// 初始化签署签名的私钥
signet.initSign(myprikey);
// 更新要由字节签名或验证的数据
signet.update(info.getBytes());
// 签署或验证所有更新字节的签名,返回签名
byte[] signed = signet.sign();
// 将数字签名,公匙,信息放入文件中
doObjToFile(signfile, new Object[] signed, mypubkey, info );
catch (Exception e)
e.printStackTrace();
/**
* 读取数字签名文件 根据公匙,签名,信息验证信息的合法性
*
* @return true 验证成功 false 验证失败
*/
public boolean validateSign(String signfile)
// 读取公匙
PublicKey mypubkey = (PublicKey) getObjFromFile(signfile, 2);
// 读取签名
byte[] signed = (byte[]) getObjFromFile(signfile, 1);
// 读取信息
String info = (String) getObjFromFile(signfile, 3);
try
// 初始一个Signature对象,并用公钥和签名进行验证
Signature signetcheck = Signature.getInstance("DSA");
// 初始化验证签名的公钥
signetcheck.initVerify(mypubkey);
// 使用指定的 byte 数组更新要签名或验证的数据
signetcheck.update(info.getBytes());
System.out.println(info);
// 验证传入的签名
return signetcheck.verify(signed);
catch (Exception e)
e.printStackTrace();
return false;
/**
* 将二进制转化为16进制字符串
*
* @param b
* 二进制字节数组
* @return String
*/
public 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;
return hs.toUpperCase();
/**
* 十六进制字符串转化为2进制
*
* @param hex
* @return
*/
public byte[] hex2byte(String hex)
byte[] ret = new byte[8];
byte[] tmp = hex.getBytes();
for (int i = 0; i < 8; i++)
ret[i] = uniteBytes(tmp[i * 2], tmp[i * 2 + 1]);
return ret;
/**
* 将两个ASCII字符合成一个字节; 如:"EF"--> 0xEF
*
* @param src0
* byte
* @param src1
* byte
* @return byte
*/
public static byte uniteBytes(byte src0, byte src1)
byte _b0 = Byte.decode("0x" + new String(new byte[] src0 ))
.byteValue();
_b0 = (byte) (_b0 << 4);
byte _b1 = Byte.decode("0x" + new String(new byte[] src1 ))
.byteValue();
byte ret = (byte) (_b0 ^ _b1);
return ret;
/**
* 将指定的对象写入指定的文件
*
* @param file
* 指定写入的文件
* @param objs
* 要写入的对象
*/
public void doObjToFile(String file, Object[] objs)
ObjectOutputStream oos = null;
try
FileOutputStream fos = new FileOutputStream(file);
oos = new ObjectOutputStream(fos);
for (int i = 0; i < objs.length; i++)
oos.writeObject(objs[i]);
catch (Exception e)
e.printStackTrace();
finally
try
oos.close();
catch (IOException e)
e.printStackTrace();
/**
* 返回在文件中指定位置的对象
*
* @param file
* 指定的文件
* @param i
* 从1开始
* @return
*/
public Object getObjFromFile(String file, int i)
ObjectInputStream ois = null;
Object obj = null;
try
FileInputStream fis = new FileInputStream(file);
ois = new ObjectInputStream(fis);
for (int j = 0; j < i; j++)
obj = ois.readObject();
catch (Exception e)
e.printStackTrace();
finally
try
ois.close();
catch (IOException e)
e.printStackTrace();
return obj;
/**
* 测试
*
* @param args
*/
public static void main(String[] args)
CryptTest jiami = new CryptTest();
// 执行MD5加密"Hello world!"
System.out.println("Hello经过MD5:" + jiami.encryptToMD5("Hello"));
// 生成一个DES算法的密匙
SecretKey key = jiami.createSecretKey("DES");
// 用密匙加密信息"Hello world!"
String str1 = jiami.encryptToDES(key, "Hello");
System.out.println("使用des加密信息Hello为:" + str1);
// 使用这个密匙解密
String str2 = jiami.decryptByDES(key, str1);
System.out.println("解密后为:" + str2);
// 创建公匙和私匙
jiami.createPairKey();
// 对Hello world!使用私匙进行签名
jiami.signToInfo("Hello", "mysign.bat");
// 利用公匙对签名进行验证。
if (jiami.validateSign("mysign.bat"))
System.out.println("Success!");
else
System.out.println("Fail!");
参考技术A
代码如下,请参照:
import java.security.SecureRandom;import javax.crypto.spec.DESKeySpec;
import javax.crypto.SecretKeyFactory;
import javax.crypto.SecretKey;
import javax.crypto.Cipher;
/**
DES加密介绍
DES是一种对称加密算法,所谓对称加密算法即:加密和解密使用相同密钥的算法。DES加密算法出自IBM的研究,
后来被美国政府正式采用,之后开始广泛流传,但是近些年使用越来越少,因为DES使用56位密钥,以现代计算能力,
24小时内即可被破解。虽然如此,在某些简单应用中,我们还是可以使用DES加密算法,本文简单讲解DES的JAVA实现
。
注意:DES加密和解密过程中,密钥长度都必须是8的倍数
*/
public class DES
public DES()
//测试
public static void main(String args[])
//待加密内容
String str = "测试内容";
//密码,长度要是8的倍数
String password = "9588028820109132570743325311898426347857298773549468758875018579537757772163084478873699447306034466200616411960574122434059469100235892702736860872901247123456";
byte[] result = DES.encrypt(str.getBytes(),password);
System.out.println("加密后:"+new String(result));
//直接将如上内容解密
try
byte[] decryResult = DES.decrypt(result, password);
System.out.println("解密后:"+new String(decryResult));
catch (Exception e1)
e1.printStackTrace();
/**
* 加密
* @param datasource byte[]
* @param password String
* @return byte[]
*/
public static byte[] encrypt(byte[] datasource, String password)
try
SecureRandom random = new SecureRandom();
DESKeySpec desKey = new DESKeySpec(password.getBytes());
//创建一个密匙工厂,然后用它把DESKeySpec转换成
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
SecretKey securekey = keyFactory.generateSecret(desKey);
//Cipher对象实际完成加密操作
Cipher cipher = Cipher.getInstance("DES");
//用密匙初始化Cipher对象
cipher.init(Cipher.ENCRYPT_MODE, securekey, random);
//现在,获取数据并加密
//正式执行加密操作
return cipher.doFinal(datasource);
catch(Throwable e)
e.printStackTrace();
return null;
/**
* 解密
* @param src byte[]
* @param password String
* @return byte[]
* @throws Exception
*/
public static byte[] decrypt(byte[] src, String password) throws Exception
// DES算法要求有一个可信任的随机数源
SecureRandom random = new SecureRandom();
// 创建一个DESKeySpec对象
DESKeySpec desKey = new DESKeySpec(password.getBytes());
// 创建一个密匙工厂
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
// 将DESKeySpec对象转换成SecretKey对象
SecretKey securekey = keyFactory.generateSecret(desKey);
// Cipher对象实际完成解密操作
Cipher cipher = Cipher.getInstance("DES");
// 用密匙初始化Cipher对象
cipher.init(Cipher.DECRYPT_MODE, securekey, random);
// 真正开始解密操作
return cipher.doFinal(src);
如何在 Java 中使用 3DES 加密/解密?
【中文标题】如何在 Java 中使用 3DES 加密/解密?【英文标题】:How do I use 3DES encryption/decryption in Java? 【发布时间】:2010-09-06 10:06:06 【问题描述】:我编写的每个使用 3DES 在 Java 中对字符串进行编码的方法都无法解密回原始字符串。有没有人有一个简单的代码 sn-p 可以将字符串编码然后解码回原始字符串?
我知道我在这段代码的某个地方犯了一个非常愚蠢的错误。到目前为止,这是我一直在使用的:
** 注意,我没有从 encrypt 方法返回 BASE64 文本,也没有在解密方法中进行 base64 未编码,因为我试图查看我是否在拼图的 BASE64 部分中犯了错误.
public class TripleDESTest
public static void main(String[] args)
String text = "kyle boon";
byte[] codedtext = new TripleDESTest().encrypt(text);
String decodedtext = new TripleDESTest().decrypt(codedtext);
System.out.println(codedtext);
System.out.println(decodedtext);
public byte[] encrypt(String message)
try
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 encodedCipherText = new sun.misc.BASE64Encoder().encode(cipherText);
return cipherText;
catch (java.security.InvalidAlgorithmParameterException e) System.out.println("Invalid Algorithm");
catch (javax.crypto.NoSuchPaddingException e) System.out.println("No Such Padding");
catch (java.security.NoSuchAlgorithmException e) System.out.println("No Such Algorithm");
catch (java.security.InvalidKeyException e) System.out.println("Invalid Key");
catch (BadPaddingException e) System.out.println("Invalid Key");
catch (IllegalBlockSizeException e) System.out.println("Invalid Key");
catch (UnsupportedEncodingException e) System.out.println("Invalid Key");
return null;
public String decrypt(byte[] message)
try
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.BASE64Decoder().decodeBuffer(message);
final byte[] plainText = decipher.doFinal(message);
return plainText.toString();
catch (java.security.InvalidAlgorithmParameterException e) System.out.println("Invalid Algorithm");
catch (javax.crypto.NoSuchPaddingException e) System.out.println("No Such Padding");
catch (java.security.NoSuchAlgorithmException e) System.out.println("No Such Algorithm");
catch (java.security.InvalidKeyException e) System.out.println("Invalid Key");
catch (BadPaddingException e) System.out.println("Invalid Key");
catch (IllegalBlockSizeException e) System.out.println("Invalid Key");
catch (UnsupportedEncodingException e) System.out.println("Invalid Key");
catch (IOException e)
// TODO Auto-generated catch block
e.printStackTrace();
return null;
【问题讨论】:
【参考方案1】:您的代码很好,除了 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[] codedtext = new TripleDESTest().encrypt(text);
String decodedtext = new TripleDESTest().decrypt(codedtext);
System.out.println(codedtext); // this is a byte array, you'll just see a reference to an array
System.out.println(decodedtext); // 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 encodedCipherText = new sun.misc.BASE64Encoder()
// .encode(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.BASE64Decoder().decodeBuffer(message);
final byte[] plainText = decipher.doFinal(message);
return new String(plainText, "UTF-8");
【讨论】:
非常感谢。但实际上,这种方法只使用两个密钥来加密消息:“HG58YZ3CR9”和“IvParameterSpec iv = new IvParameterSpec(new byte[8]);” .但是triple des最强大的选项可以使用三个不同的密钥来加密消息。那么怎么做呢?我在 Cipher 中找到了一个方法,它使用“SecureRandom”作为另一个参数。那么这是正确的方法吗?非常感谢 3DES 使用 3 个 8 字节的密钥(在本例中存储为 24 个字节)。第一个和第三个键相同是很常见的(即,通过采用双倍长度、16 字节的键,您可以将第一个组件重新用作第三个组件)。要使用三倍长度的密钥,只需跳过上面的位,其中第一个组件(字节 0 - 7)被复制到第三个(字节 16 - 23)的空间中。 @AdrianHope-Bailie 该建议是错误的,因为 MD5 仅输出 16 个字节,因此其余部分将用零填充。只是零永远不会是一个好键。 这段代码确实做了很多正确的事情,包括使用有效的填充和模式、字符编码等。但是它应该使用 PBKDF2 将密码转换为密钥,或者使用真正的随机密钥。在密文上添加 HMAC 计算也可以增加显着的安全性。 这段代码的问题在于它使用了静态零字节 IV。最好为每次加密生成一个随机 IV 并将其存储在密文的前面。它不一定是秘密的,但它必须是不可预测的。【参考方案2】:这是一个使用 javax.crypto 库和 apache commons 编解码器库进行 Base64 编码和解码的解决方案:
import java.security.spec.KeySpec;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESedeKeySpec;
import org.apache.commons.codec.binary.Base64;
public class TrippleDes
private static final String UNICODE_FORMAT = "UTF8";
public static final String DESEDE_ENCRYPTION_SCHEME = "DESede";
private KeySpec ks;
private SecretKeyFactory skf;
private Cipher cipher;
byte[] arrayBytes;
private String myEncryptionKey;
private String myEncryptionScheme;
SecretKey key;
public TrippleDes() throws Exception
myEncryptionKey = "ThisIsSpartaThisIsSparta";
myEncryptionScheme = DESEDE_ENCRYPTION_SCHEME;
arrayBytes = myEncryptionKey.getBytes(UNICODE_FORMAT);
ks = new DESedeKeySpec(arrayBytes);
skf = SecretKeyFactory.getInstance(myEncryptionScheme);
cipher = Cipher.getInstance(myEncryptionScheme);
key = skf.generateSecret(ks);
public String encrypt(String unencryptedString)
String encryptedString = null;
try
cipher.init(Cipher.ENCRYPT_MODE, key);
byte[] plainText = unencryptedString.getBytes(UNICODE_FORMAT);
byte[] encryptedText = cipher.doFinal(plainText);
encryptedString = new String(Base64.encodeBase64(encryptedText));
catch (Exception e)
e.printStackTrace();
return encryptedString;
public String decrypt(String encryptedString)
String decryptedText=null;
try
cipher.init(Cipher.DECRYPT_MODE, key);
byte[] encryptedText = Base64.decodeBase64(encryptedString);
byte[] plainText = cipher.doFinal(encryptedText);
decryptedText= new String(plainText);
catch (Exception e)
e.printStackTrace();
return decryptedText;
public static void main(String args []) throws Exception
TrippleDes td= new TrippleDes();
String target="imparator";
String encrypted=td.encrypt(target);
String decrypted=td.decrypt(encrypted);
System.out.println("String To Encrypt: "+ target);
System.out.println("Encrypted String:" + encrypted);
System.out.println("Decrypted String:" + decrypted);
运行上述程序,输出如下:
String To Encrypt: imparator
Encrypted String:FdBNaYWfjpWN9eYghMpbRA==
Decrypted String:imparator
【讨论】:
这个答案解决了问题,但是代码引入了所有的编码,模式等错误,在问题的代码中要小心避免。 感谢您的回答。一个问题,如果key小于24字节怎么办,如何正确解决?key = skf.generateSecret(ks);
在这里我们正在生成要加密的密钥,对吧?那么myEncryptionKey
到底是什么?
当我用我的字符串替换上面的加密字符串并用我的密钥替换密钥时,这似乎对我不起作用。我得到输入长度不是 8 异常的因素【参考方案3】:
我自己很难弄清楚,这篇文章帮助我找到了适合我的案例的正确答案。当使用 ISO-8583 的金融消息时,3DES 要求非常具体,所以对于我的特殊情况,“DESede/CBC/PKCS5Padding”组合并没有解决问题。在将我的结果与为金融界设计的一些 3DES 计算器进行比较测试后,我发现“DESede/ECB/Nopadding”值更适合特定任务。
这是我的 TripleDes 类的演示实现(使用 Bouncy Castle 提供程序)
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.Security;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
/**
*
* @author Jose Luis Montes de Oca
*/
public class TripleDesCipher
private static String TRIPLE_DES_TRANSFORMATION = "DESede/ECB/Nopadding";
private static String ALGORITHM = "DESede";
private static String BOUNCY_CASTLE_PROVIDER = "BC";
private Cipher encrypter;
private Cipher decrypter;
public TripleDesCipher(byte[] key) throws NoSuchAlgorithmException, NoSuchProviderException, NoSuchPaddingException,
InvalidKeyException
Security.addProvider(new BouncyCastleProvider());
SecretKey keySpec = new SecretKeySpec(key, ALGORITHM);
encrypter = Cipher.getInstance(TRIPLE_DES_TRANSFORMATION, BOUNCY_CASTLE_PROVIDER);
encrypter.init(Cipher.ENCRYPT_MODE, keySpec);
decrypter = Cipher.getInstance(TRIPLE_DES_TRANSFORMATION, BOUNCY_CASTLE_PROVIDER);
decrypter.init(Cipher.DECRYPT_MODE, keySpec);
public byte[] encode(byte[] input) throws IllegalBlockSizeException, BadPaddingException
return encrypter.doFinal(input);
public byte[] decode(byte[] input) throws IllegalBlockSizeException, BadPaddingException
return decrypter.doFinal(input);
【讨论】:
只提供任何 3DES 代码似乎不是我的答案。此外,在我看来,明确使用 ECB 和 NoPadding 以及在不需要的地方使用 BC 会使这个答案不合格。 非常感谢@jlmontesdeoca。你的回答节省了我的时间。我也被 PKCS7Padding 困住了。【参考方案4】:这是一个非常简单的静态加密/解密类,该类偏向于 Jose Luis Montes de Oca 的 Bouncy Castle 无填充示例。这个使用“DESede/ECB/PKCS7Padding”,所以我不必手动填充。
package com.zenimax.encryption;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.Security;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
/**
*
* @author Matthew H. Wagner
*/
public class TripleDesBouncyCastle
private static String TRIPLE_DES_TRANSFORMATION = "DESede/ECB/PKCS7Padding";
private static String ALGORITHM = "DESede";
private static String BOUNCY_CASTLE_PROVIDER = "BC";
private static void init()
Security.addProvider(new BouncyCastleProvider());
public static byte[] encode(byte[] input, byte[] key)
throws IllegalBlockSizeException, BadPaddingException,
NoSuchAlgorithmException, NoSuchProviderException,
NoSuchPaddingException, InvalidKeyException
init();
SecretKey keySpec = new SecretKeySpec(key, ALGORITHM);
Cipher encrypter = Cipher.getInstance(TRIPLE_DES_TRANSFORMATION,
BOUNCY_CASTLE_PROVIDER);
encrypter.init(Cipher.ENCRYPT_MODE, keySpec);
return encrypter.doFinal(input);
public static byte[] decode(byte[] input, byte[] key)
throws IllegalBlockSizeException, BadPaddingException,
NoSuchAlgorithmException, NoSuchProviderException,
NoSuchPaddingException, InvalidKeyException
init();
SecretKey keySpec = new SecretKeySpec(key, ALGORITHM);
Cipher decrypter = Cipher.getInstance(TRIPLE_DES_TRANSFORMATION,
BOUNCY_CASTLE_PROVIDER);
decrypter.init(Cipher.DECRYPT_MODE, keySpec);
return decrypter.doFinal(input);
【讨论】:
但它仍然使用ECB,这是一个更大的错误。【参考方案5】:private static final String UNICODE_FORMAT = "UTF8";
private static final String DESEDE_ENCRYPTION_SCHEME = "DESede";
private KeySpec ks;
private SecretKeyFactory skf;
private Cipher cipher;
byte[] arrayBytes;
private String encryptionSecretKey = "ThisIsSpartaThisIsSparta";
SecretKey key;
public TripleDesEncryptDecrypt() throws Exception
convertStringToSecretKey(encryptionSecretKey);
public TripleDesEncryptDecrypt(String encryptionSecretKey) throws Exception
convertStringToSecretKey(encryptionSecretKey);
public SecretKey convertStringToSecretKey (String encryptionSecretKey) throws Exception
arrayBytes = encryptionSecretKey.getBytes(UNICODE_FORMAT);
ks = new DESedeKeySpec(arrayBytes);
skf = SecretKeyFactory.getInstance(DESEDE_ENCRYPTION_SCHEME);
cipher = Cipher.getInstance(DESEDE_ENCRYPTION_SCHEME);
key = skf.generateSecret(ks);
return key;
/**
* Encrypt without specifying secret key
*
* @param unencryptedString
* @return String
*/
public String encrypt(String unencryptedString)
String encryptedString = null;
try
cipher.init(Cipher.ENCRYPT_MODE, key);
byte[] plainText = unencryptedString.getBytes(UNICODE_FORMAT);
byte[] encryptedText = cipher.doFinal(plainText);
encryptedString = new String(Base64.encodeBase64(encryptedText));
catch (Exception e)
e.printStackTrace();
return encryptedString;
/**
* Encrypt with specified secret key
*
* @param unencryptedString
* @return String
*/
public String encrypt(String encryptionSecretKey, String unencryptedString)
String encryptedString = null;
try
key = convertStringToSecretKey(encryptionSecretKey);
cipher.init(Cipher.ENCRYPT_MODE, key);
byte[] plainText = unencryptedString.getBytes(UNICODE_FORMAT);
byte[] encryptedText = cipher.doFinal(plainText);
encryptedString = new String(Base64.encodeBase64(encryptedText));
catch (Exception e)
e.printStackTrace();
return encryptedString;
/**
* Decrypt without specifying secret key
* @param encryptedString
* @return
*/
public String decrypt(String encryptedString)
String decryptedText=null;
try
cipher.init(Cipher.DECRYPT_MODE, key);
byte[] encryptedText = Base64.decodeBase64(encryptedString);
byte[] plainText = cipher.doFinal(encryptedText);
decryptedText= new String(plainText);
catch (Exception e)
e.printStackTrace();
return decryptedText;
/**
* Decrypt with specified secret key
* @param encryptedString
* @return
*/
public String decrypt(String encryptionSecretKey, String encryptedString)
String decryptedText=null;
try
key = convertStringToSecretKey(encryptionSecretKey);
cipher.init(Cipher.DECRYPT_MODE, key);
byte[] encryptedText = Base64.decodeBase64(encryptedString);
byte[] plainText = cipher.doFinal(encryptedText);
decryptedText= new String(plainText);
catch (Exception e)
e.printStackTrace();
return decryptedText;
【讨论】:
增强@oniero 的代码,这可以帮助您使用更好的密钥,并且您启动一次课程并能够解密和加密。没有添加main方法,可以添加main方法或者复制oniero的main方法 您的答案可以通过额外的支持信息得到改进。请edit 添加更多详细信息,例如引用或文档,以便其他人可以确认您的答案是正确的。你可以找到更多关于如何写好答案的信息in the help center。【参考方案6】:import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.Key;
import javax.crypto.Cipher;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESedeKeySpec;
import javax.crypto.spec.IvParameterSpec;
import java.util.Base64;
import java.util.Base64.Encoder;
/**
*
* @author shivshankar pal
*
* this code is working properly. doing proper encription and decription
note:- it will work only with jdk8
*
*
*/
public class TDes
private static byte[] key = 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x02, 0x02,
0x02, 0x02, 0x02, 0x02, 0x02, 0x02 ;
private static byte[] keyiv = 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00 ;
public static String encode(String args)
System.out.println("plain data==> " + args);
byte[] encoding;
try
encoding = Base64.getEncoder().encode(args.getBytes("UTF-8"));
System.out.println("Base64.encodeBase64==>" + new String(encoding));
byte[] str5 = des3EncodeCBC(key, keyiv, encoding);
System.out.println("des3EncodeCBC==> " + new String(str5));
byte[] encoding1 = Base64.getEncoder().encode(str5);
System.out.println("Base64.encodeBase64==> " + new String(encoding1));
return new String(encoding1);
catch (UnsupportedEncodingException e)
// TODO Auto-generated catch block
e.printStackTrace();
return null;
public static String decode(String args)
try
System.out.println("encrypted data==>" + new String(args.getBytes("UTF-8")));
byte[] decode = Base64.getDecoder().decode(args.getBytes("UTF-8"));
System.out.println("Base64.decodeBase64(main encription)==>" + new String(decode));
byte[] str6 = des3DecodeCBC(key, keyiv, decode);
System.out.println("des3DecodeCBC==>" + new String(str6));
String data=new String(str6);
byte[] decode1 = Base64.getDecoder().decode(data.trim().getBytes("UTF-8"));
System.out.println("plaintext==> " + new String(decode1));
return new String(decode1);
catch (UnsupportedEncodingException e)
// TODO Auto-generated catch block
e.printStackTrace();
return "u mistaken in try block";
private static byte[] des3EncodeCBC(byte[] key, byte[] keyiv, byte[] data)
try
Key deskey = null;
DESedeKeySpec spec = new DESedeKeySpec(key);
SecretKeyFactory keyfactory = SecretKeyFactory.getInstance("desede");
deskey = keyfactory.generateSecret(spec);
Cipher cipher = Cipher.getInstance("desede/ CBC/PKCS5Padding");
IvParameterSpec ips = new IvParameterSpec(keyiv);
cipher.init(Cipher.ENCRYPT_MODE, deskey, ips);
byte[] bout = cipher.doFinal(data);
return bout;
catch (Exception e)
System.out.println("methods qualified name" + e);
return null;
private static byte[] des3DecodeCBC(byte[] key, byte[] keyiv, byte[] data)
try
Key deskey = null;
DESedeKeySpec spec = new DESedeKeySpec(key);
SecretKeyFactory keyfactory = SecretKeyFactory.getInstance("desede");
deskey = keyfactory.generateSecret(spec);
Cipher cipher = Cipher.getInstance("desede/ CBC/NoPadding");//PKCS5Padding NoPadding
IvParameterSpec ips = new IvParameterSpec(keyiv);
cipher.init(Cipher.DECRYPT_MODE, deskey, ips);
byte[] bout = cipher.doFinal(data);
return bout;
catch (Exception e)
System.out.println("methods qualified name" + e);
return null;
【讨论】:
以上是关于如何使用JAVA实现对字符串的DES加密和解密的主要内容,如果未能解决你的问题,请参考以下文章
如何在netbeans java中使用充气城堡(DES)加密和解密文件?