bcprov-ext-jdk16-143.jar
应该放到你应用的classpath下。放ext中,修改java.security 我在windows系统下居然无效的。但在linux/unix下是好的
❷ java的 DES 加密解密方法 求对应php的加密解密方法!!!!急切
DES是一种标准的数据加密算法,关于这个算法的详细介绍可以参考wiki和网络:
php中有一个扩展可以支持DES的加密算法,是:extension=php_mcrypt.dll
在配置文件中将这个扩展打开还不能够在windows环境下使用
需要将PHP文件夹下的 libmcrypt.dll 拷贝到系统的 system32 目录下,这是通过phpinfo可以查看到mcrypt表示这个模块可以正常试用了。
下面是PHP中使用DES加密解密的一个例子:
//$input-stufftodecrypt
//$key-thesecretkeytouse
functiondo_mencrypt($input,$key)
{
$input=str_replace(""n","",$input);
$input=str_replace(""t","",$input);
$input=str_replace(""r","",$input);
$key=substr(md5($key),0,24);
$td=mcrypt_mole_open('tripledes','','ecb','');
$iv=mcrypt_create_iv(mcrypt_enc_get_iv_size($td),MCRYPT_RAND);
mcrypt_generic_init($td,$key,$iv);
$encrypted_data=mcrypt_generic($td,$input);
mcrypt_generic_deinit($td);
mcrypt_mole_close($td);
returntrim(chop(base64_encode($encrypted_data)));
}
//$input-stufftodecrypt
//$key-thesecretkeytouse
functiondo_mdecrypt($input,$key)
{
$input=str_replace(""n","",$input);
$input=str_replace(""t","",$input);
$input=str_replace(""r","",$input);
$input=trim(chop(base64_decode($input)));
$td=mcrypt_mole_open('tripledes','','ecb','');
$key=substr(md5($key),0,24);
$iv=mcrypt_create_iv(mcrypt_enc_get_iv_size($td),MCRYPT_RAND);
mcrypt_generic_init($td,$key,$iv);
$decrypted_data=mdecrypt_generic($td,$input);
mcrypt_generic_deinit($td);
mcrypt_mole_close($td);
returntrim(chop($decrypted_data));
}
参考自:http://www.cnblogs.com/cocowool/archive/2009/01/07/1371309.html
❸ Java中 DES加密算法
package des;
import javax.crypto.Cipher;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import java.security.NoSuchAlgorithmException;
import sun.misc.*;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import javax.crypto.BadPaddingException;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.spec.SecretKeySpec;
import java.security.*;
import javax.crypto.SecretKeyFactory;
import java.security.spec.*;
import javax.crypto.spec.DESedeKeySpec;
/**
解密
*/
class DES {
private static String Algorithm = "DESede";//加密算法的名称
private static Cipher c;//密码器
private static byte[] cipherByte;
private static SecretKey deskey;//密钥
private static String keyString = "";//获得密钥的参数
//对base64编码的string解码成byte数组
public byte[] deBase64(String parm) throws IOException {
BASE64Decoder dec=new BASE64Decoder();
byte[] dnParm = dec.decodeBuffer(parm);
System.out.println(dnParm.length);
System.out.println(dnParm);
return dnParm;
}
//把密钥参数转为byte数组
public byte[] dBase64(String parm) throws IOException {
BASE64Decoder dec=new BASE64Decoder();
byte[] dnParm = dec.decodeBuffer(parm);
return dnParm;
}
/**
* 对 Byte 数组进行解密
* @param buff 要解密的数据
* @return 返回加密后的 String
*/
public static String createDecryptor(byte[] buff) throws
NoSuchPaddingException, NoSuchAlgorithmException,
UnsupportedEncodingException {
try {
c.init(Cipher.DECRYPT_MODE, deskey);//初始化密码器,用密钥deskey,进入解密模式
cipherByte = c.doFinal(buff);
}
catch(java.security.InvalidKeyException ex){
ex.printStackTrace();
}
catch(javax.crypto.BadPaddingException ex){
ex.printStackTrace();
}
catch(javax.crypto.IllegalBlockSizeException ex){
ex.printStackTrace();
}
return (new String(cipherByte,"UTF-8"));
}
public void getKey(String key) throws IOException, InvalidKeyException,
InvalidKeySpecException {
byte[] dKey = dBase64(key);
try {
deskey=new javax.crypto.spec.SecretKeySpec(dKey,Algorithm);
c = Cipher.getInstance(Algorithm);
}
catch (NoSuchPaddingException ex) {
}
catch (NoSuchAlgorithmException ex) {
}
}
public static void main(String args[]) throws IOException,
NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeySpecException,
InvalidKeyException, IOException {
DES des = new DES();
des.getKey(keyString);//获取密钥
byte[] dBy = des.deBase64("t0/fDOZ5NaQ=");//获取需要解密的字符串
String dStr = des.createDecryptor(dBy);
System.out.println("解密:"+dStr);
}
}
❹ java DES加密
java可以调用C的dll,上网搜下用法,直接调用吧。
❺ java des加密,密钥的长度是多少
3des算法是指使用双长度(16字节)密钥k=(kl||kr)将8字节明文数据块进行3次des加密/解密。如下所示:
y
=
des(kl)[des-1(kr)[des(kl[x])]]
解密方式为:
x
=
des-1
(kl)[des
(kr)[
des-1
(kl[y])]]
其中,des(kl[x])表示用密钥k对数据x进行des加密,des-1
(kl[y])表示用密钥k对数据y进行解密。
sessionkey的计算采用3des算法,计算出单倍长度的密钥。表示法为:sk
=
session(dk,data)
3des加密算法为:
void
3des(byte
doublekeystr[16],
byte
data[8],
byte
out[8])
{
byte
buf1[8],
buf2[8];
des
(&doublekeystr[0],
data,
buf1);
udes(&doublekeystr[8],
buf1,
buf2);
des
(&doublekeystr[0],
buf2,
out);
}
❻ 用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;
import com.huateng.util.common.Log;
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();
Log.sKeyPath(path);
} 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();
Log.sKeyPath(path);
} 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/");
}
}
/*加解密*/
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;
public class SecUtil {
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) {
throw new RuntimeException(ey1);
}
catch (Exception ey2) {
throw new RuntimeException(ey2);
}
//用key产生Cipher
Cipher cipher = null;
try {
//设置算法,应该与加密时的设置一样
cipher = Cipher.getInstance("DES");
//设置解密模式
cipher.init(Cipher.DECRYPT_MODE, key);
}
catch (Exception ey3) {
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) {
throw new RuntimeException(ey5);
}
}
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) {
throw new RuntimeException(ey1);
}
catch (Exception ey2) {
throw new RuntimeException(ey2);
}
//用key产生Cipher
Cipher cipher = null;
try {
//设置算法,应该与加密时的设置一样
cipher = Cipher.getInstance("DES");
//设置解密模式
cipher.init(Cipher.ENCRYPT_MODE, key);
}
catch (Exception ey3) {
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) {
throw new RuntimeException(ey5);
}
}
}
❼ Java 编写的DES文件加密问题
DES 加密, 建议是将整个文件一次性加密 和 解密,中旅 而不州拆是每行。
每行的效率太低, 而安全性并没卖迹凳有提高
❽ java des加密为什么和网站
JAVA实现
加密
代码有详细解释,不多废话。
注意:DES加密和解密过程中,密钥长度都必须是8的段行缓倍数
[java] view plain
public byte[] desCrypto(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;
}
解密
代码有详细注释,不多废话
[java] view plain
private 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] view plain
//待加密带漏内容
String str = "测试内容";
//密码,长度要是8的倍数
String password = "12345678";
byte[] result = DESCrypto.desCrypto(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();
}
❾ java的 DES 加密解密方法 求对应C#的加密解密方法,急切
/*
* @param arrB 需要转换的byte数组
* @return 转换后的字符串
* @throws Exception 本方法不处理任何异常,所有异常全部抛出
*/
public static String byteArr2HexStr(byte[] arrB) throws Exception {
int iLen = arrB.length;
// 每个byte用两个字符才能表示,所以字符串的长度是数组长度的两倍
StringBuffer sb = new StringBuffer(iLen * 2);
for (int i = 0; i < iLen; i++) {
int intTmp = arrB[i];
// 把负数转换为正数
while (intTmp < 0) {
intTmp = intTmp + 256;
}
// 小于0F的数需要在前面补0
if (intTmp < 16) {
sb.append("0");
}
sb.append(Integer.toString(intTmp, 16));
}
return sb.toString();
}
/*
* @param strIn 需要转换的字符串
* @return 转换后的byte数组
* @throws Exception 本方法不处理任何异常,所有异常全部抛出
*/
public static byte[] hexStr2ByteArr(String strIn) throws Exception {
byte[] arrB = strIn.getBytes();
int iLen = arrB.length;
// 两个字符表示一个字节,所以字节数组长度是字符串长度除以2
byte[] arrOut = new byte[iLen / 2];
for (int i = 0; i < iLen; i = i + 2) {
String strTmp = new String(arrB, i, 2);
arrOut[i / 2] = (byte) Integer.parseInt(strTmp, 16);
}
return arrOut;
}
/**
* 加密字节数组
*
* @param arrB
* 需加密的字节数组
* @return 加密后的字节数组
* @throws Exception
*/
@SuppressWarnings("restriction")
private static byte[] encrypt(byte[] arrB,String keyParameter) throws Exception {
Security.addProvider(new com.sun.crypto.provider.SunJCE());
Key key = getKey(keyParameter.getBytes());
Cipher encryptCipher = Cipher.getInstance("DES");
encryptCipher.init(Cipher.ENCRYPT_MODE, key);
return encryptCipher.doFinal(arrB);
}
/**
* 加密字符串
*
* @param strIn
* 需加密的字符串
* @return 加密后的字符串
* @throws Exception
*/
public static String encrypt(String strIn,String keyParameter) throws Exception {
return HexStrByteArrUtils.byteArr2HexStr(encrypt(strIn.getBytes(PiccConfig.PICC_INPUT_CHARSET),keyParameter));
}
/**
* 解密字节数组
*
* @param arrB
* 需解密的字节数组
* @return 解密后的字节数组
* @throws Exception
*/
@SuppressWarnings("restriction")
private static byte[] decrypt(byte[] arrB,String keyParameter) throws Exception {
Security.addProvider(new com.sun.crypto.provider.SunJCE());
Key key = getKey(keyParameter.getBytes());
Cipher decryptCipher = Cipher.getInstance("DES");
decryptCipher.init(Cipher.DECRYPT_MODE, key);
return decryptCipher.doFinal(arrB);
}
/**
* 解密字符串
*
* @param strIn
* 需解密的字符串
* @return 解密后的字符串
* @throws Exception
*/
public static String decrypt(String strIn,String keyParameter) throws Exception {
return new String(decrypt(HexStrByteArrUtils.hexStr2ByteArr(strIn),keyParameter),PiccConfig.PICC_INPUT_CHARSET);
}
❿ 用java实现des算法
分类: 电脑/网络 >> 程序设计 >> 其并运他编程语言
问题描述:
各位好,请求各位java学习者帮助钉解决这个问题。
我想用des算法对我的名字进行加密
我也在网上下载了des算法,包括FileDES,SubKey,Des各程序,
可能没真正理解这些程序,所以我想调用都键让不知道将这些东西
组合起来,有知道的请帮帮忙啊!
解析:
package des;
import java.io.*;
import java.nio.*;
import java.nio.channels.FileChannel;
public class FileDES{
private static final boolean enc=true; 加密
private static final boolean dec=false; 解密
private String srcFileName;
private String destFileName;
private String inKey;
private boolean actionType;
private File srcFile;
private File destFile;
private Des des;
private void *** yzePath(){
String dirName;
int pos=srcFileNamestIndexOf("/稿蔽局");
dirName=srcFileName.substring(0,pos);
File dir=new File(dirName);
if (!dir.exists()){
System.err.println(dirName+" is not exist");
System.exit(1);
}else if(!dir.isDirectory()){
System.err.println(dirName+" is not a directory");
System.exit(1);
}
pos=destFileNamestIndexOf("/");
dirName=destFileName.substring(0,pos);
dir=new File(dirName);
if (!dir.exists()){
if(!dir.mkdirs()){
System.out.println ("can not creat directory:"+dirName);
System.exit(1);
}
}else if(!dir.isDirectory()){
System.err.println(dirName+" is not a directory");
System.exit(1);
}
}
private static int replenish(FileChannel channel,ByteBuffer buf) throws IOException{
long byteLeft=channel.size()-channel.position();
if(byteLeft==0L)
return -1;
buf.position(0);
buf.limit(buf.position()+(byteLeft<8 ? (int)byteLeft :8));
return channel.read(buf);
}
private void file_operate(boolean flag){
des=new Des(inKey);
FileOutputStream outputFile=null;
try {
outputFile=new FileOutputStream(srcFile,true);
}catch (java.io.FileNotFoundException e) {
e.printStackTrace(System.err);
}
FileChannel outChannel=outputFile.getChannel();
try{
if(outChannel.size()%2!=0){
ByteBuffer bufTemp=ByteBuffer.allocate(1);
bufTemp.put((byte)32);
bufTemp.flip();
outChannel.position(outChannel.size());
outChannel.write(bufTemp);
bufTemp.clear();
}
}catch(Exception ex){
ex.printStackTrace(System.err);
System.exit(1);
}
FileInputStream inFile=null;
try{
inFile=new FileInputStream(srcFile);
}catch(java.io.FileNotFoundException e){
e.printStackTrace(System.err);
System.exit(1);
}
outputFile=null;
try {
outputFile=new FileOutputStream(destFile,true);
}catch (java.io.FileNotFoundException e) {
e.printStackTrace(System.err);
}
FileChannel inChannel=inFile.getChannel();
outChannel=outputFile.getChannel();
ByteBuffer inBuf=ByteBuffer.allocate(8);
ByteBuffer outBuf=ByteBuffer.allocate(8);
try{
String srcStr;
String destStr;
while(true){
if (replenish(inChannel,inBuf)==-1) break;
srcStr=((ByteBuffer)(inBuf.flip())).asCharBuffer().toString();
inBuf.clear();
if (flag)
destStr=des.enc(srcStr,srcStr.length());
else
destStr=des.dec(srcStr,srcStr.length());
outBuf.clear();
if (destStr.length()==4){
for (int i = 0; i<4; i++) {
outBuf.putChar(destStr.charAt(i));
}
outBuf.flip();
}else{
outBuf.position(0);
outBuf.limit(2*destStr.length());
for (int i = 0; i<destStr.length(); i++) {
outBuf.putChar(destStr.charAt(i));
}
outBuf.flip();
}
try {
outChannel.write(outBuf);
outBuf.clear();
}catch (java.io.IOException ex) {
ex.printStackTrace(System.err);
}
}
System.out.println (inChannel.size());
System.out.println (outChannel.size());
System.out.println ("EoF reached.");
inFile.close();
outputFile.close();
}catch(java.io.IOException e){
e.printStackTrace(System.err);
System.exit(1);
}
}
public FileDES(String srcFileName,String destFileName,String inKey,boolean actionType){
this.srcFileName=srcFileName;
this.destFileName=destFileName;
this.actionType=actionType;
*** yzePath();
srcFile=new File(srcFileName);
destFile=new File(destFileName);
this.inKey=inKey;
if (actionType==enc)
file_operate(enc);
else
file_operate(dec);
}
public static void main(String[] args){
String file1=System.getProperty("user.dir")+"/111.doc";
String file2=System.getProperty("user.dir")+"/222.doc";
String file3=System.getProperty("user.dir")+"/333.doc";
String passWord="1234ABCD";
FileDES fileDes=new FileDES(file1,file2,passWord,true);
FileDES fileDes1=new FileDES(file2,file3,passWord,false);
}