当前位置:首页 » 编程语言 » javacipher

javacipher

发布时间: 2023-01-27 12:08:04

1. 求助java关于音频加密的问题

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import javax.crypto.Cipher;

public class RSAEncrypt {

static KeyPairGenerator keyPairGen;

static KeyPair keyPair;

static RSAPrivateKey privateKey;

static RSAPublicKey publicKey;

static{
try {
keyPairGen = KeyPairGenerator.getInstance("RSA");
keyPairGen.initialize(512);
keyPair = keyPairGen.generateKeyPair();
// Generate keys
privateKey = (RSAPrivateKey) keyPair.getPrivate();
publicKey = (RSAPublicKey) keyPair.getPublic();
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

public static void main(String[] args) {
RSAEncrypt encrypt = new RSAEncrypt();
File file = new File(
"C:\\Documents and Settings\\Administrator.DCB5E0D91E0D436\\桌面\\sdf.txt");
File newFile = new File(
"C:\\Documents and Settings\\Administrator.DCB5E0D91E0D436\\桌面\\sdf1.txt");
encrypt.encryptFile(encrypt, file, newFile);
File file1 = new File(
"C:\\Documents and Settings\\Administrator.DCB5E0D91E0D436\\桌面\\sdf1.txt");
File newFile1 = new File(
"C:\\Documents and Settings\\Administrator.DCB5E0D91E0D436\\桌面\\sdf2.txt");
encrypt.decryptFile(encrypt, file1, newFile1);
}

public void encryptFile(RSAEncrypt encrypt, File file, File newFile) {
try {
InputStream is = new FileInputStream(file);
OutputStream os = new FileOutputStream(newFile);

byte[] bytes = new byte[53];
while (is.read(bytes) > 0) {
byte[] e = encrypt.encrypt(RSAEncrypt.publicKey, bytes);
bytes = new byte[53];
os.write(e, 0, e.length);
}
os.close();
is.close();
System.out.println("write success");
} catch (Exception e) {
e.printStackTrace();
}
}

public void decryptFile(RSAEncrypt encrypt, File file, File newFile) {
try {
InputStream is = new FileInputStream(file);
OutputStream os = new FileOutputStream(newFile);
byte[] bytes1 = new byte[64];
while (is.read(bytes1) > 0) {
byte[] de = encrypt.decrypt(RSAEncrypt.privateKey, bytes1);
bytes1 = new byte[64];
os.write(de, 0, de.length);
}
os.close();
is.close();
System.out.println("write success");

} catch (Exception e) {
e.printStackTrace();
}
}

/** */
/**
* * Encrypt String. *
*
* @return byte[]
*/
protected byte[] encrypt(RSAPublicKey publicKey, byte[] obj) {
if (publicKey != null) {
try {
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
return cipher.doFinal(obj);
} catch (Exception e) {
e.printStackTrace();
}
}
return null;
}

/** */
/**
* * Basic decrypt method *
*
* @return byte[]
*/
protected byte[] decrypt(RSAPrivateKey privateKey, byte[] obj) {
if (privateKey != null) {
try {
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.DECRYPT_MODE, privateKey);
return cipher.doFinal(obj);
} catch (Exception e) {
e.printStackTrace();
}
}
return null;
}
}

加解密需要依靠以下四个属性,你可以把它存文件,存数据库都无所谓:
static KeyPairGenerator keyPairGen;

static KeyPair keyPair;

static RSAPrivateKey privateKey;

static RSAPublicKey publicKey;

以上只是示例,怎么存放根据自己情况

2. java 中的Cipher类RSA方式能不能用私钥加密公钥解密,完整解释下

KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
keyGen.initialize(1024);
KeyPair key = keyGen.generateKeyPair();

Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
//把第二个参数改为 key.getPrivate()
cipher.init(Cipher.ENCRYPT_MODE, key.getPublic());
byte[] cipherText = cipher.doFinal("Message".getBytes("UTF8"));
System.out.println(new String(cipherText, "UTF8"));
//把第二个参数改为key.getPublic()
cipher.init(Cipher.DECRYPT_MODE, key.getPrivate());
byte[] newPlainText = cipher.doFinal(cipherText);
System.out.println(new String(newPlainText, "UTF8"));

正常的用公钥加密私钥解密就是这个过程,如果按私钥加密公钥解密,只要按备注改2个参数就可以。

但是我要提醒楼主,你要公钥解密,公钥是公开的,相当于任何人都查到公钥可以解密。
你是想做签名是吧。

3. 如何用JAVA实现字符串简单加密解密

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!");
}
}
}

4. java中如何实现对文件和字符串加密. 解密

DES 密钥生成,加解密方法,,你可以看一下

//DES 密钥生成工具
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.spec.InvalidKeySpecException;

import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;

public class GenKey {

private static final String DES = "DES";
public static final String SKEY_NAME = "key.des";

public static void genKey1(String path) {

// 密钥
SecretKey skey = null;
// 密钥随机数生成
SecureRandom sr = new SecureRandom();
//生成密钥文件
File file = genFile(path);

try {
// 获取密钥生成实例
KeyGenerator gen = KeyGenerator.getInstance(DES);
// 初始化密钥生成器
gen.init(sr);
// 生成密钥
skey = gen.generateKey();
// System.out.println(skey);

ObjectOutputStream oos = new ObjectOutputStream(
new FileOutputStream(file));
oos.writeObject(skey);
oos.close();

} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}

/**
* @param file : 生成密钥的路径
* SecretKeyFactory 方式生成des密钥
* */
public static void genKey2(String path) {
// 密钥随机数生成
SecureRandom sr = new SecureRandom();
// byte[] bytes = {11,12,44,99,76,45,1,8};
byte[] bytes = sr.generateSeed(20);
// 密钥
SecretKey skey = null;
//生成密钥文件路径
File file = genFile(path);

try {
//创建deskeyspec对象
DESKeySpec desKeySpec = new DESKeySpec(bytes,9);
//实例化des密钥工厂
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(DES);
//生成密钥对象
skey = keyFactory.generateSecret(desKeySpec);
//写出密钥对象
ObjectOutputStream oos = new ObjectOutputStream(
new FileOutputStream(file));
oos.writeObject(skey);
oos.close();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (InvalidKeyException e) {
e.printStackTrace();
} catch (InvalidKeySpecException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}

}

private static File genFile(String path) {
String temp = null;
File newFile = null;
if (path.endsWith("/") || path.endsWith("\\")) {
temp = path;
} else {
temp = path + "/";
}

File pathFile = new File(temp);
if (!pathFile.exists())
pathFile.mkdirs();

newFile = new File(temp+SKEY_NAME);

return newFile;
}
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
genKey2("E:/a/aa/");
}

}

//DES加解密方法

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;

import javax.crypto.Cipher;
import javax.crypto.CipherInputStream;
import javax.crypto.SecretKey;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
*制卡文件加/解密 加密方式DES
*/
public class SecUtil {

public static final Log log = LogFactory.getLog(SecUtil.class);

/**
* 解密
*
* @param keyPath
* 密钥路径
* @param source
* 解密前文件
* @param dest
* 解密后文件
*/
public static void decrypt(String keyPath, String source, String dest) {
SecretKey key = null;
try {
ObjectInputStream keyFile = new ObjectInputStream(
// 读取加密密钥
new FileInputStream(keyPath));
key = (SecretKey) keyFile.readObject();
keyFile.close();
} catch (FileNotFoundException ey1) {
log.info("Error when read keyFile");
throw new RuntimeException(ey1);
} catch (Exception ey2) {
log.info("error when read the keyFile");
throw new RuntimeException(ey2);
}
// 用key产生Cipher
Cipher cipher = null;
try {
// 设置算法,应该与加密时的设置一样
cipher = Cipher.getInstance("DES");
// 设置解密模式
cipher.init(Cipher.DECRYPT_MODE, key);
} catch (Exception ey3) {
log.info("Error when create the cipher");
throw new RuntimeException(ey3);
}
// 取得要解密的文件并解密
File file = new File(source);
String filename = file.getName();
try {
// 输出流,请注意文件名称的获取
BufferedOutputStream out = new BufferedOutputStream(
new FileOutputStream(dest));
// 输入流
CipherInputStream in = new CipherInputStream(
new BufferedInputStream(new FileInputStream(file)), cipher);
int thebyte = 0;
while ((thebyte = in.read()) != -1) {
out.write(thebyte);
}
in.close();
out.close();
} catch (Exception ey5) {
log.info("Error when encrypt the file");
throw new RuntimeException(ey5);
}
}

/**
* 加密
* @param keyPath 密钥路径
* @param source 加密前文件
* @param dest 加密后文件
*/
public static void encrypt(String keyPath, String source, String dest) {
SecretKey key = null;
try {
ObjectInputStream keyFile = new ObjectInputStream(
// 读取加密密钥
new FileInputStream(keyPath));
key = (SecretKey) keyFile.readObject();
keyFile.close();
} catch (FileNotFoundException ey1) {
log.info("Error when read keyFile");
throw new RuntimeException(ey1);
} catch (Exception ey2) {
log.info("error when read the keyFile");
throw new RuntimeException(ey2);
}
// 用key产生Cipher
Cipher cipher = null;
try {
// 设置算法,应该与加密时的设置一样
cipher = Cipher.getInstance("DES");
// 设置解密模式
cipher.init(Cipher.ENCRYPT_MODE, key);
} catch (Exception ey3) {
log.info("Error when create the cipher");
throw new RuntimeException(ey3);
}
// 取得要解密的文件并解密
File file = new File(source);
String filename = file.getName();
try {
// 输出流,请注意文件名称的获取
BufferedOutputStream out = new BufferedOutputStream(
new FileOutputStream(dest));
// 输入流
CipherInputStream in = new CipherInputStream(
new BufferedInputStream(new FileInputStream(file)), cipher);
int thebyte = 0;
while ((thebyte = in.read()) != -1) {
out.write(thebyte);
}
in.close();
out.close();
} catch (Exception ey5) {
log.info("Error when encrypt the file");
throw new RuntimeException(ey5);
}
}

}

5. java的aes加密成多少位数

深圳远标帮你:
1.默认 Java 中仅支持 128 位密钥,当使用 256 位密钥的时候,会报告密钥长度错误
Invalid AES key length

你需要下载一个支持更长密钥的包。这个包叫做 Java Cryptography Extension (JCE) Unlimited Strength Jurisdiction Policy Files 6
看一下你的 JRE 环境,将 JRE 环境中 lib\lib\security 中的同名包替换掉。
2. Base64 问题
// 编码
String asB64 = new Base64().encodeToString("some string".getBytes("utf-8"));
System.out.println(asB64); // 输出为: c29tZSBzdHJpbmc=

解码
// 解码
byte[] asBytes = new Base64().getDecoder().decode("c29tZSBzdHJpbmc=");
System.out.println(new String(asBytes, "utf-8")); // 输出为: some string

如果你已经使用 Java 8,那么就不需要再选用第三方的实现了,在 java.util 包中已经包含了 Base64 的处理。
编码的方式
// 编码
String asB64 = Base64.getEncoder().encodeToString("some string".getBytes("utf-8"));
System.out.println(asB64); // 输出为: c29tZSBzdHJpbmc=

解码处理
// 解码
byte[] asBytes = Base64.getDecoder().decode("c29tZSBzdHJpbmc=");
System.out.println(new String(asBytes, "utf-8")); // 输出为: some string

3. 关于 PKCS5 和 PKCS7 填充问题
PKCS #7 填充字符串由一个字节序列组成,每个字节填充该填充字节序列的长度。
假定块长度为 8,数据长度为 9,
数据: FF FF FF FF FF FF FF FF FF
PKCS7 填充: FF FF FF FF FF FF FF FF FF 07 07 07 07 07 07 07
简单地说, PKCS5, PKCS7和SSL3, 以及CMS(Cryptographic Message Syntax)
有如下相同的特点:
1)填充的字节都是一个相同的字节
2)该字节的值,就是要填充的字节的个数
如果要填充8个字节,那么填充的字节的值就是0×8;
要填充7个字节,那么填入的值就是0×7;

如果只填充1个字节,那么填入的值就是0×1;
这种填充方法也叫PKCS5, 恰好8个字节时还要补8个字节的0×08
正是这种即使恰好是8个字节也需要再补充字节的规定,可以让解密的数据很确定无误的移除多余的字节。

比如, Java中
Cipher.getInstance(“AES/CBC/PKCS5Padding”)
这个加密模式
跟C#中的
RijndaelManaged cipher = new RijndaelManaged();
cipher.KeySize = 128;
cipher.BlockSize = 128;
cipher.Mode = CipherMode.CBC;
cipher.Padding = PaddingMode.PKCS7;
的加密模式是一样的
因为AES并没有64位的块, 如果采用PKCS5, 那么实质上就是采用PKCS7

6. JAVA中Given final block not properly padded怎么办

获取Cipher对象时必须要写成:Cipher cipher = Cipher.getInstance("DES/ECB/NoPadding");

不能写成:Cipher cipher = Cipher.getInstance("DES");

否则解密时候报错:Given final block not properly padded

原因:Cipher cipher = Cipher.getInstance("DES");与Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");

等同,填充方式错误,加密的时候会得到16长度的字节数组。

解密时报错:javax.crypto.BadPaddingException: Given final block not properly padded

仔细分析一下,不难发现,该异常是在解密的时候抛出的,加密的方法没有问题。

但是两个方法的唯一差别是Cipher对象的模式不一样,这就排除了程序写错的可能性。再看一下异常的揭示信息,大概的意思是:提供的字块不符合填补的。

原来在用DES加密的时候,最后一位长度不足64的,它会自动填补到64,那么在我们进行字节数组到字串的转化过程中,可以把它填补的不可见字符改变了,所以引发系统抛出异常。

为了方便使用,我们再写一个新的方法封装一下原来的方法:

public static String DataEncrypt(String str, byte[] key) {

String encrypt = null;

try {

byte[] ret = encode(str.getBytes("UTF-8"),key);

encrypt = new String(Base64.encode(ret));

}

catch(Exception e){

System.out.print(e); encrypt = str;

}

return encrypt;

}

public static String DataDecrypt(String str, byte[] key) {

String decrypt = null;

try {

byte[] ret = decode(Base64.decode(str),key);

decrypt = new String(ret,"UTF-8");

}

catch(Exception e) {

System.out.print(e);

decrypt = str;

}

return decrypt;

}

(6)javacipher扩展阅读:

java中的Cipher类

位于javax.crypto包下,声明为 public classCipherextends Object

此类为加密和解密提供密码功能。它构成了 Java Cryptographic Extension (JCE) 框架的核心。

为创建 Cipher 对象,应用程序调用 Cipher 的getInstance方法并将所请求转换的名称传递给它。还可以指定提供者的名称(可选)。

转换是一个字符串,它描述为产生某种输出而在给定的输入上执行的操作(或一组操作)。转换始终包括加密算法的名称(例如,DES),后面可能跟有一个反馈模式和填充方案。

转换具有以下形式:

“算法/模式/填充”或“算法”

(后一种情况下,使用模式和填充方案特定于提供者的默认值)。例如,以下是有效的转换:

Cipher c = Cipher.getInstance("DES/CBC/PKCS5Padding");

使用CFB和OFB之类的模式,Cipher 块可以加密单元中小于该 Cipher 的实际块大小的数据。请求这样一个模式时,可以指定一次处理的位数(可选):将此数添加到模式名称中,正如 "DES/CFB8/NoPadding" 和 "DES/OFB32/PKCS5Padding" 转换所示。

如果未指定该数,则将使用特定于提供者的默认值。(例如,SunJCE 提供者对 DES 使用默认的 64 位)。因此,通过使用如 CFB8 或 OFB8 的 8 位模式,Cipher 块可以被转换为面向字节的 Cipher 流。

1、字段

public static final intENCRYPT_MODE 用于将 Cipher 初始化为加密模式的常量。

public static final int DECRYPT_MODE 用于将 Cipher 初始化为解密模式的常量。

public static final int WRAP_MODE 用于将 Cipher 初始化为密钥包装模式的常量。

public static final int UNWRAP_MODE 用于将 Cipher 初始化为密钥解包模式的常量。

public static final int PUBLIC_KEY 用于表示要解包的密钥为“公钥”的常量。

public static final int PRIVATE_KEY 用于表示要解包的密钥为“私钥”的常量。

public static final int SECRET_KEY 用于表示要解包的密钥为“秘密密钥”的常量。

热点内容
java返回this 发布:2025-10-20 08:28:16 浏览:582
制作脚本网站 发布:2025-10-20 08:17:34 浏览:876
python中的init方法 发布:2025-10-20 08:17:33 浏览:571
图案密码什么意思 发布:2025-10-20 08:16:56 浏览:757
怎么清理微信视频缓存 发布:2025-10-20 08:12:37 浏览:673
c语言编译器怎么看执行过程 发布:2025-10-20 08:00:32 浏览:1000
邮箱如何填写发信服务器 发布:2025-10-20 07:45:27 浏览:244
shell脚本入门案例 发布:2025-10-20 07:44:45 浏览:103
怎么上传照片浏览上传 发布:2025-10-20 07:44:03 浏览:795
python股票数据获取 发布:2025-10-20 07:39:44 浏览:701