JAVA中的加解密,抛这样的javax.crypto.BadPaddingException异常啥原因,怎么解决?
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了JAVA中的加解密,抛这样的javax.crypto.BadPaddingException异常啥原因,怎么解决?相关的知识,希望对你有一定的参考价值。
public class DESTest
//KeyGenerator提供对称密钥生成器的功能
private KeyGenerator keyGenerator;
//SecretKey负责对称密钥的保存
private SecretKey desKey;
//完成加密和解密工作
private Cipher c;
//保存加密结果
private byte[] cipherResultByte;
public DESTest()
Security.addProvider(new com.sun.crypto.provider.SunJCE());
try
//实例化支持DES算法的密钥生成器(算法名称命名需按规定,否则抛异常)
keyGenerator=KeyGenerator.getInstance("DES");
//生成密钥
desKey=keyGenerator.generateKey();
//生成Cipher对象,指定其支持DES算法
c=Cipher.getInstance("DES");
catch (NoSuchAlgorithmException e)
e.printStackTrace();
catch (NoSuchPaddingException e)
e.printStackTrace();
//对str加密
public byte[] createEncryptor(String str)
try
//根据密钥,对Cipher进行初使化,DECRYPT_MODE加密模式
c.init(Cipher.DECRYPT_MODE, desKey);
byte[] input=str.getBytes();
//加密,将结果保存
cipherResultByte=c.doFinal(input);
catch (InvalidKeyException e)
e.printStackTrace();
catch (IllegalBlockSizeException e)
e.printStackTrace();
catch (BadPaddingException e)
e.printStackTrace();
return cipherResultByte;
//对buff解密
public byte[] createDecryptor(byte[] buff)
try
//根据密钥,对Cipher进行初使化,ENCRYPT_MODE加密模式
c.init(Cipher.ENCRYPT_MODE, desKey);
//得到明文,存入cipherResultByte
cipherResultByte=c.doFinal(buff);
catch (InvalidKeyException e)
e.printStackTrace();
catch (IllegalBlockSizeException e)
e.printStackTrace();
catch (BadPaddingException e)
e.printStackTrace();
return cipherResultByte;
public static void main(String[] args)
DESTest desTest=new DESTest();
String str="12341234";
// byte[] enc=desTest.createEncryptor(str);
byte[] enc="123".getBytes();
byte[] dec=desTest.createDecryptor(enc);
System.out.println("明文是:"+str);
// System.out.println("加密后,密文是:"+new String(enc));
System.out.println("解密后,明文是:"+new String(dec));
加密的时候抛javax.crypto.BadPaddingException这样的异常,求帮助.....
MD5+DES在C#.NET与Java/Android中的加解密使用
一、背景
后台(C#.NET)使用一个MD5+DES的加解密算法,查了下,很多网友都使用了这个算法。在Android里,也需要这个算法,如何把这个加解密算法切换成Java版,成了难题。毕竟好久没涉及到这一块了,只知道:
MD5(Message-Digest Algorithm 5,信息-摘要算法5):是一种信息摘要算法、哈希算法,不可逆;
DES(Data Encryption Standard,数据加密标准):是一种对称加密算法,加解密需要同一个密钥;
AES(Advanced Encryption Standard,高级加密标准), 也是一种对称加密算法,是DES的升级版。
目前来说,DES比较脆弱,所以推荐用AES。
核心算法都是一样的,各种语言都封装好了,就是如何使用的问题。为了弄懂C#中的代码,竟然把11G多的VS2017也给安装了(在线编译工具无法编译通过,最后在VS中改了才可以,推荐:http://ideone.com/)。经过一番折腾,终于切换成功。
二、C#源码
从网上把解密的算法也一起复制过来研究
#region ========加密========
/// <summary>
/// 加密
/// </summary>
/// <param name="Text"></param>
/// <returns></returns>
public static string Encrypt(string Text)
{
return Encrypt(Text, "Ralap");
}
/// <summary>
/// 加密数据
/// </summary>
/// <param name="Text"></param>
/// <param name="sKey"></param>
/// <returns></returns>
public static string Encrypt(string Text, string sKey)
{
DESCryptoServiceProvider des = new DESCryptoServiceProvider();
byte[] inputByteArray;
inputByteArray = Encoding.Default.GetBytes(Text);
des.Key = ASCIIEncoding.ASCII.GetBytes(System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(sKey, "md5").Substring(0, 8));
des.IV = ASCIIEncoding.ASCII.GetBytes(System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(sKey, "md5").Substring(0, 8));
System.IO.MemoryStream ms = new System.IO.MemoryStream();
CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write);
cs.Write(inputByteArray, 0, inputByteArray.Length);
cs.FlushFinalBlock();
StringBuilder ret = new StringBuilder();
foreach (byte b in ms.ToArray())
{
ret.AppendFormat("{0:X2}", b);
}
return ret.ToString();
}
#endregion
#region ========解密========
/// <summary>
/// 解密
/// </summary>
/// <param name="Text"></param>
/// <returns></returns>
public static string Decrypt(string Text)
{
return Decrypt(Text, "Ralap");
}
/// <summary>
/// 解密数据
/// </summary>
/// <param name="Text"></param>
/// <param name="sKey"></param>
/// <returns></returns>
public static string Decrypt(string Text, string sKey)
{
DESCryptoServiceProvider des = new DESCryptoServiceProvider();
int len;
len = Text.Length / 2;
byte[] inputByteArray = new byte[len];
int x, i;
for (x = 0; x < len; x++)
{
i = Convert.ToInt32(Text.Substring(x * 2, 2), 16);
inputByteArray[x] = (byte)i;
}
des.Key = ASCIIEncoding.ASCII.GetBytes(System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(sKey, "md5").Substring(0, 8));
des.IV = ASCIIEncoding.ASCII.GetBytes(System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(sKey, "md5").Substring(0, 8));
System.IO.MemoryStream ms = new System.IO.MemoryStream();
CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Write);
cs.Write(inputByteArray, 0, inputByteArray.Length);
cs.FlushFinalBlock();
return Encoding.Default.GetString(ms.ToArray());
}
#endregion
三、C#源码分析及替换MD5加密类
把这段代码复制过来,并不能使用,因为System.Web.Security报错。不会整,就想着换掉个方式,最后使用MD5CryptoServiceProvider类来替换,成功复原结果。如下:
using System;
using System.Text;
using System.Security.Cryptography;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
string key = "Ralap";
Console.WriteLine("==========加密=========");
string secret = Encrypt("Android, 你好!", key);
Console.WriteLine("result of Encrypt=" + secret);
Console.WriteLine("==========解密=========");
string data = Decrypt(secret, key);
Console.WriteLine("result of Decrypt=" + data);
Console.ReadKey();
}
#region ========加密========
public static string Encrypt(string Text, string sKey)
{
DESCryptoServiceProvider des = new DESCryptoServiceProvider();
byte[] inputByteArray;
inputByteArray = Encoding.UTF8.GetBytes(Text);
string md5 = Md5Hash(sKey).Substring(0, 8);
Console.WriteLine("md5=" + md5);
des.Key = ASCIIEncoding.ASCII.GetBytes(md5);
des.IV = ASCIIEncoding.ASCII.GetBytes(md5);
Console.WriteLine("Key=" + Bytes2Hex(des.Key));
System.IO.MemoryStream ms = new System.IO.MemoryStream();
CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write);
cs.Write(inputByteArray, 0, inputByteArray.Length);
cs.FlushFinalBlock();
return Bytes2Hex(ms.ToArray());
}
public static string Decrypt(string Text, string sKey)
{
DESCryptoServiceProvider des = new DESCryptoServiceProvider();
int len;
len = Text.Length / 2;
byte[] inputByteArray = new byte[len];
int x, i;
for (x = 0; x < len; x++)
{
i = Convert.ToInt32(Text.Substring(x * 2, 2), 16);
inputByteArray[x] = (byte)i;
}
string md5 = Md5Hash(sKey).Substring(0, 8);
des.Key = ASCIIEncoding.ASCII.GetBytes(md5);
des.IV = ASCIIEncoding.ASCII.GetBytes(md5);
Console.WriteLine("Key=" + Bytes2Hex(des.Key));
System.IO.MemoryStream ms = new System.IO.MemoryStream();
CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Write);
cs.Write(inputByteArray, 0, inputByteArray.Length);
cs.FlushFinalBlock();
return Encoding.UTF8.GetString(ms.ToArray());
}
private static string Md5Hash(string input)
{
MD5CryptoServiceProvider md5Hasher = new MD5CryptoServiceProvider();
byte[] data = md5Hasher.ComputeHash(Encoding.Default.GetBytes(input));
return Bytes2Hex(data);
}
private static string Bytes2Hex(byte[] bytes) {
StringBuilder sBuilder = new StringBuilder();
for (int i = 0; i < bytes.Length; i++)
{
sBuilder.Append(bytes[i].ToString("X2"));
}
return sBuilder.ToString();
}
#endregion
}
}
运行结果如下:
注意:
网上的Md5Hash()结果并没有转换成大写,所以掉坑了。
因为这里使用到了中文,所以并没有使用Default默认编码,而使用UTF-8编码:Encoding.UTF8.GetBytes()和Encoding.UTF8.GetString()
. 另外,Md5Hash()的另一种写法:
public static string Md5Hash(string input)
{
MD5 md5Hash = MD5.Create();
byte[] data = md5Hash.ComputeHash(Encoding.UTF8.GetBytes(input));
return Bytes2Hex(data);
}
四、Java版
对着C#,先获取key的MD5前8位,使用它作为key和iv,进行DES加解密。有坑的地方就是要全部转换成大写字母。其它没什么好说的,直接上代码和运行结果就一目了然:
package com.example;
import java.security.MessageDigest;
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
/**
* File Name : EncryptClass
* Description :
* Author : Ralap
* Create Date : 2017/3/19
* Version : v1
*/
public class EncryptClass {
public static void main(String[] args) {
println("=========Java版=========");
String key = "Ralap";
println("=========加密=========");
String secret = encrypt("Android, 你好!", key);
println("result of encrypt=%s", secret);
println("========解密==========");
String data = decrypt(secret, key);
println("result of decrypt=%s", data);
}
/**
* 加密
*
* @param data 要加密的数据
* @param key 密钥
*/
private static String encrypt(String data, String key) {
try {
// 获取key的MD5值
byte[] md5Bytes = MessageDigest.getInstance("MD5").digest(key.getBytes());
// md5值转换成十六进制(大写)
String md5 = bytes2Hex(md5Bytes).toUpperCase();
println("keyMD5=%s", md5);
// 并获取前8位作为真实的key
String pwd = md5.substring(0, 8);
println("pwd=%s", pwd);
// 使用DES 加密,key和iv都使用pwd
// 根据pwd,生成DES加密后的密钥,SecretKeySpec对象
SecretKeySpec secretKey = new SecretKeySpec(pwd.getBytes(), "DES");
// 根据pwd,创建一个初始化向量IvParameterSpec对象
IvParameterSpec iv = new IvParameterSpec(pwd.getBytes());
// 创建密码器,参数:算法/模式/填充
Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
// 用key和iv初始化密码器,参1:opmode,操作模式-加密、解密等。
cipher.init(Cipher.ENCRYPT_MODE, secretKey, iv);
// 执行(加密)并返回结果(字节数组)
byte[] resultBytes = cipher.doFinal(data.getBytes(""UTF-8""));
// 转换成十六进制(大写)
return bytes2Hex(resultBytes).toUpperCase();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* 解密
*
* @param data 要解密的数据
* @param key 密钥
*/
private static String decrypt(String data, String key) {
try {
// 把加密的十六进制字符串数据转换成字节数组
int len = data.length() >> 1;
byte[] dataBytes = new byte[len];
for (int i=0; i<len; i++) {
int index = i << 1;
dataBytes[i] = (byte)Integer.parseInt(data.substring(index, index + 2), 16);
}
// 获取key的MD5值
byte[] md5Bytes = MessageDigest.getInstance("MD5").digest(key.getBytes());
String pwd = bytes2Hex(md5Bytes).toUpperCase().substring(0, 8);
// 创建key和iv
SecretKeySpec secretKey = new SecretKeySpec(pwd.getBytes(), "DES");
IvParameterSpec iv = new IvParameterSpec(pwd.getBytes());
// DES 解密
Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, secretKey, iv);
byte[] resultBytes = cipher.doFinal(dataBytes);
return new String(resultBytes, "UTF-8");
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* 字节数组转换成十六进制字符串
*/
private static String bytes2Hex(byte[] bytes) {
if (bytes == null) {
return null;
}
StringBuilder resultSB = new StringBuilder();
for (byte b : bytes) {
String hex = Integer.toHexString(b & 0xFF);
if (hex.length() < 2) {
resultSB.append("0");
}
resultSB.append(hex);
}
return resultSB.toString();
}
private static void println(String format, Object... args) {
System.out.println(String.format(format, args));
}
}
运行结果:
说明:
1、创建密钥的一行代码:
SecretKeySpec secretKey = new SecretKeySpec(pwd.getBytes(), "DES");
也可以用这三行来创建:
DESKeySpec keySpec = new DESKeySpec(pwd.getBytes());
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
Key secretKey = keyFactory.generateSecret(keySpec);
2、服务器与客户端编码格式一定要一致,特别是原始数据含中文的情况
以上是关于JAVA中的加解密,抛这样的javax.crypto.BadPaddingException异常啥原因,怎么解决?的主要内容,如果未能解决你的问题,请参考以下文章