导航:首页 > 编程语言 > javades密钥生成

javades密钥生成

发布时间:2024-05-10 02:25:18

java 给定十六位密钥 如何进行des加密

packagecom.palic.pss.afcs.worldthrough.common.util;

importjavax.crypto.Cipher;
importjavax.crypto.spec.SecretKeySpec;

importrepack.com.thoughtworks.xstream.core.util.Base64Encoder;
/**
*AES加密解密
*@authorEX-CHENQI004
*
*/
publicclassAesUtils{
publicstaticfinalStringcKey="assistant7654321";
/**
*加密--把加密后的byte数组先进行二进制转16进制在进行base64编码
*@paramsSrc
*@paramsKey
*@return
*@throwsException
*/
publicstaticStringencrypt(StringsSrc,StringsKey)throwsException{
if(sKey==null){
("ArgumentsKeyisnull.");
}
if(sKey.length()!=16){
(
"ArgumentsKey'lengthisnot16.");
}
byte[]raw=sKey.getBytes("ASCII");
SecretKeySpecskeySpec=newSecretKeySpec(raw,"AES");

Ciphercipher=Cipher.getInstance("AES");
cipher.init(Cipher.ENCRYPT_MODE,skeySpec);

byte[]encrypted=cipher.doFinal(sSrc.getBytes("UTF-8"));
StringtempStr=parseByte2HexStr(encrypted);

Base64Encoderencoder=newBase64Encoder();
returnencoder.encode(tempStr.getBytes("UTF-8"));
}

/**
*解密--先进行base64解码,在进行16进制转为2进制然后再解码
*@paramsSrc
*@paramsKey
*@return
*@throwsException
*/
publicstaticStringdecrypt(StringsSrc,StringsKey)throwsException{

if(sKey==null){
("499");
}
if(sKey.length()!=16){
("498");
}

byte[]raw=sKey.getBytes("ASCII");
SecretKeySpecskeySpec=newSecretKeySpec(raw,"AES");

Ciphercipher=Cipher.getInstance("AES");
cipher.init(Cipher.DECRYPT_MODE,skeySpec);

Base64Encoderencoder=newBase64Encoder();
byte[]encrypted1=encoder.decode(sSrc);

StringtempStr=newString(encrypted1,"utf-8");
encrypted1=parseHexStr2Byte(tempStr);
byte[]original=cipher.doFinal(encrypted1);
StringoriginalString=newString(original,"utf-8");
returnoriginalString;
}

/**
*将二进制转换成16进制
*
*@parambuf
*@return
*/
(bytebuf[]){
StringBuffersb=newStringBuffer();
for(inti=0;i<buf.length;i++){
Stringhex=Integer.toHexString(buf[i]&0xFF);
if(hex.length()==1){
hex='0'+hex;
}
sb.append(hex.toUpperCase());
}
returnsb.toString();
}

/**
*将16进制转换为二进制
*
*@paramhexStr
*@return
*/
publicstaticbyte[]parseHexStr2Byte(StringhexStr){
if(hexStr.length()<1)
returnnull;
byte[]result=newbyte[hexStr.length()/2];
for(inti=0;i<hexStr.length()/2;i++){
inthigh=Integer.parseInt(hexStr.substring(i*2,i*2+1),16);
intlow=Integer.parseInt(hexStr.substring(i*2+1,i*2+2),
16);
result[i]=(byte)(high*16+low);
}
returnresult;
}
publicstaticvoidmain(String[]args)throwsException{
/*
*加密用的Key可以用26个字母和数字组成,最好不要用保留字符,虽然不会错,至于怎么裁决,个人看情况而定
*/
StringcKey="assistant7654321";
//需要加密的字串
StringcSrc="123456";
//加密
longlStart=System.currentTimeMillis();
StringenString=encrypt(cSrc,cKey);
System.out.println("加密后的字串是:"+enString);
longlUseTime=System.currentTimeMillis()-lStart;
System.out.println("加密耗时:"+lUseTime+"毫秒");
//解密
lStart=System.currentTimeMillis();
StringDeString=decrypt(enString,cKey);
System.out.println("解密后的字串是:"+DeString);
lUseTime=System.currentTimeMillis()-lStart;
System.out.println("解密耗时:"+lUseTime+"毫秒");
}
}

② 如何用Java进行3DES加密解密

这里是例子,直接拿来用就可以了。
package com.nnff.des;

import java.security.Security;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

/*字符串 DESede(3DES) 加密
* ECB模式/使用PKCS7方式填充不足位,目前给的密钥是192位
* 3DES(即Triple DES)是DES向AES过渡的加密算法(1999年,NIST将3-DES指定为过渡的
* 加密标准),是DES的一个更安全的变形。它以DES为基本模块,通过组合分组方法设计出分组加
* 密算法,其具体实现如下:设Ek()和Dk()代表DES算法的加密和解密过程,K代表DES算法使用的
* 密钥,P代表明文,C代表密表,这样,
* 3DES加密过程为:C=Ek3(Dk2(Ek1(P)))
* 3DES解密过程为:P=Dk1((EK2(Dk3(C)))
* */
public class ThreeDes {

/**
* @param args在java中调用sun公司提供的3DES加密解密算法时,需要使
* 用到$JAVA_HOME/jre/lib/目录下如下的4个jar包:
*jce.jar
*security/US_export_policy.jar
*security/local_policy.jar
*ext/sunjce_provider.jar
*/

private static final String Algorithm = "DESede"; //定义加密算法,可用 DES,DESede,Blowfish
//keybyte为加密密钥,长度为24字节
//src为被加密的数据缓冲区(源)
public static byte[] encryptMode(byte[] keybyte,byte[] src){
try {
//生成密钥
SecretKey deskey = new SecretKeySpec(keybyte, Algorithm);
//加密
Cipher c1 = Cipher.getInstance(Algorithm);
c1.init(Cipher.ENCRYPT_MODE, deskey);
return c1.doFinal(src);//在单一方面的加密或解密
} catch (java.security.NoSuchAlgorithmException e1) {
// TODO: handle exception
e1.printStackTrace();
}catch(javax.crypto.NoSuchPaddingException e2){
e2.printStackTrace();
}catch(java.lang.Exception e3){
e3.printStackTrace();
}
return null;
}

//keybyte为加密密钥,长度为24字节
//src为加密后的缓冲区
public static byte[] decryptMode(byte[] keybyte,byte[] src){
try {
//生成密钥
SecretKey deskey = new SecretKeySpec(keybyte, Algorithm);
//解密
Cipher c1 = Cipher.getInstance(Algorithm);
c1.init(Cipher.DECRYPT_MODE, deskey);
return c1.doFinal(src);
} catch (java.security.NoSuchAlgorithmException e1) {
// TODO: handle exception
e1.printStackTrace();
}catch(javax.crypto.NoSuchPaddingException e2){
e2.printStackTrace();
}catch(java.lang.Exception e3){
e3.printStackTrace();
}
return null;
}

//转换成十六进制字符串
public static 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;
}
if(n<b.length-1)hs=hs+":";
}
return hs.toUpperCase();
}
public static void main(String[] args) {
// TODO Auto-generated method stub
//添加新安全算法,如果用JCE就要把它添加进去
Security.addProvider(new com.sun.crypto.provider.SunJCE());
final byte[] keyBytes = {0x11, 0x22, 0x4F, 0x58,
(byte)0x88, 0x10, 0x40, 0x38, 0x28, 0x25, 0x79, 0x51,
(byte)0xCB,
(byte)0xDD, 0x55, 0x66, 0x77, 0x29, 0x74,
(byte)0x98, 0x30, 0x40, 0x36,
(byte)0xE2
}; //24字节的密钥
String szSrc = "This is a 3DES test. 测试";
System.out.println("加密前的字符串:" + szSrc);
byte[] encoded = encryptMode(keyBytes,szSrc.getBytes());
System.out.println("加密后的字符串:" + new String(encoded));

byte[] srcBytes = decryptMode(keyBytes,encoded);
System.out.println("解密后的字符串:" + (new String(srcBytes)));
}
}

③ 求java加密源代码(MD5,base64)

加密什么加密字符串吗,我这里有md5的算法
public final static String MD5(String pwd) {
char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
'A', 'B', 'C', 'D', 'E', 'F' };
try {
byte[] strTemp = pwd.getBytes();
MessageDigest mdTemp = MessageDigest.getInstance("MD5");
mdTemp.update(strTemp);
byte[] md = mdTemp.digest();
int j = md.length;
char str[] = new char[j * 2];
int k = 0;
for (int i = 0; i < j; i++) {
byte byte0 = md[i];
str[k++] = hexDigits[byte0 >>> 4 & 0xf];
str[k++] = hexDigits[byte0 & 0xf];
}
return new String(str);
} catch (Exception e) {
return null;
}
}

④ java密码加密与解密

以下两个类可以很方便的完成字符串的加密和解密

加密 CryptHelper encrypt(password)

解密 CrypHelper decrypt(password)

代码如下

CryptUtils java

[java]

package gdie lab crypt;

import java io IOException;

import javax crypto Cipher;

import javax crypto KeyGenerator;

import javax crypto SecretKey;

import apache xerces internal impl dv util Base ;

public class CryptUtils {

private static String Algorithm = DES ;

private static byte[] DEFAULT_KEY=new byte[] { };

private static String VALUE_ENCODING= UTF ;

/**

* 生成密钥

*

* @return byte[] 返回生成的密钥

* @throws exception

* 扔出异常

*/

public static byte[] getSecretKey() throws Exception {

KeyGenerator keygen = KeyGenerator getInstance(Algorithm)

SecretKey deskey = keygen generateKey()

// if (debug ) System out println ( 生成密钥 +byte hex (deskey getEncoded

// ()))

return deskey getEncoded()

}

/**

* 将指定的数据根据提供的密钥进行加密

*

* @param input

* 需要加密的数据

* @param key

* 密钥

* @return byte[] 加密后的数据

* @throws Exception

*/

public static byte[] encryptData(byte[] input byte[] key) throws Exception {

SecretKey deskey = new javax crypto spec SecretKeySpec(key Algorithm)

// if (debug )

// {

// System out println ( 加密前的二进串 +byte hex (input ))

// System out println ( 加密前的字符串 +new String (input ))

//

// }

Cipher c = Cipher getInstance(Algorithm)

c init(Cipher ENCRYPT_MODE deskey)

byte[] cipherByte = c doFinal(input)

// if (debug ) System out println ( 加密后的二进串 +byte hex (cipherByte ))

return cipherByte;

}

public static byte[] encryptData(byte[] input) throws Exception {

return encryptData(input DEFAULT_KEY)

}

/**

* 将给定的已加密的数据通过指定的密钥进行解密

*

* @param input

* 待解密的数据

* @param key

* 密钥

* @return byte[] 解密后的数据

* @throws Exception

*/

public static byte[] decryptData(byte[] input byte[] key) throws Exception {

SecretKey deskey = new javax crypto spec SecretKeySpec(key Algorithm)

// if (debug ) System out println ( 解密前的信息 +byte hex (input ))

Cipher c = Cipher getInstance(Algorithm)

c init(Cipher DECRYPT_MODE deskey)

byte[] clearByte = c doFinal(input)

// if (debug )

// {

// System out println ( 解密后的二进串 +byte hex (clearByte ))

// System out println ( 解密后的字符串 +(new String (clearByte )))

//

// }

return clearByte;

}

public static byte[] decryptData(byte[] input) throws Exception {

return decryptData(input DEFAULT_KEY)

}

/**

* 字节码转换成 进制字符串

*

* @param byte[] b 输入要转换的字节码

* @return String 返回转换后的 进制字符串

*/

public static String byte hex(byte[] bytes) {

StringBuilder hs = new StringBuilder()

for(byte b : bytes)

hs append(String format( % $ X b))

return hs toString()

}

public static byte[] hex byte(String content) {

int l=content length()》 ;

byte[] result=new byte[l];

for(int i= ;i<l;i++) {

int j=i《 ;

String s=content substring(j j+ )

result[i]=Integer valueOf(s ) byteValue()

}

return result;

}

/**

* 将字节数组转换为base 编码字符串

* @param buffer

* @return

*/

public static String bytesToBase (byte[] buffer) {

//BASE Encoder en=new BASE Encoder()

return Base encode(buffer)

// return encoder encode(buffer)

}

/**

* 将base 编码的字符串解码为字节数组

* @param value

* @return

* @throws IOException

*/

public static byte[] base ToBytes(String value) throws IOException {

//return Base decodeToByteArray(value)

// System out println(decoder decodeBuffer(value))

// return decoder decodeBuffer(value)

return Base decode(value)

}

/**

* 加密给定的字符串

* @param value

* @return 加密后的base 字符串

*/

public static String encryptString(String value) {

return encryptString(value DEFAULT_KEY)

}

/**

* 根据给定的密钥加密字符串

* @param value 待加密的字符串

* @param key 以BASE 形式存在的密钥

* @return 加密后的base 字符串

* @throws IOException

*/

public static String encryptString(String value String key) throws IOException {

return encryptString(value base ToBytes(key))

}

/**

* 根据给定的密钥加密字符串

* @param value 待加密的字符串

* @param key 字节数组形式的密钥

* @return 加密后的base 字符串

*/

public static String encryptString(String value byte[] key) {

try {

byte[] data=value getBytes(VALUE_ENCODING)

data=CryptUtils encryptData(data key)

return bytesToBase (data)

} catch (Exception e) {

// TODO Auto generated catch block

e printStackTrace()

return null;

}

}

/**

* 解密字符串

* @param value base 形式存在的密文

* @return 明文

*/

public static String decryptString(String value) {

return decryptString(value DEFAULT_KEY)

}

/**

* 解密字符串

* @param value base 形式存在的密文

* @param key base 形式存在的密钥

* @return 明文

* @throws IOException

*/

public static String decryptString(String value String key) throws IOException {

String s=decryptString(value base ToBytes(key))

return s;

}

/**

* 解密字符串

* @param value base 形式存在的密文

* @param key 字节数据形式存在的密钥

* @return 明文

*/

public static String decryptString(String value byte[] key) {

try {

byte[] data=base ToBytes(value)

data=CryptUtils decryptData(data key)

return new String(data VALUE_ENCODING)

}catch(Exception e) {

e printStackTrace()

return null;

}

}

}

package gdie lab crypt;

import java io IOException;

import javax crypto Cipher;

import javax crypto KeyGenerator;

import javax crypto SecretKey;

import apache xerces internal impl dv util Base ;

public class CryptUtils {

private static String Algorithm = DES ;

private static byte[] DEFAULT_KEY=new byte[] { };

private static String VALUE_ENCODING= UTF ;

/**

* 生成密钥

*

* @return byte[] 返回生成的密钥

* @throws exception

* 扔出异常

*/

public static byte[] getSecretKey() throws Exception {

KeyGenerator keygen = KeyGenerator getInstance(Algorithm)

SecretKey deskey = keygen generateKey()

// if (debug ) System out println ( 生成密钥 +byte hex (deskey getEncoded

// ()))

return deskey getEncoded()

}

/**

* 将指定的数据根据提供的密钥进行加密

*

* @param input

* 需要加密的数据

* @param key

* 密钥

* @return byte[] 加密后的数据

* @throws Exception

*/

public static byte[] encryptData(byte[] input byte[] key) throws Exception {

SecretKey deskey = new javax crypto spec SecretKeySpec(key Algorithm)

// if (debug )

// {

// System out println ( 加密前的二进串 +byte hex (input ))

// System out println ( 加密前的字符串 +new String (input ))

//

// }

Cipher c = Cipher getInstance(Algorithm)

c init(Cipher ENCRYPT_MODE deskey)

byte[] cipherByte = c doFinal(input)

// if (debug ) System out println ( 加密后的二进串 +byte hex (cipherByte ))

return cipherByte;

}

public static byte[] encryptData(byte[] input) throws Exception {

return encryptData(input DEFAULT_KEY)

}

/**

* 将给定的已加密的数据通过指定的密钥进行解密

*

* @param input

* 待解密的数据

* @param key

* 密钥

* @return byte[] 解密后的数据

* @throws Exception

*/

public static byte[] decryptData(byte[] input byte[] key) throws Exception {

SecretKey deskey = new javax crypto spec SecretKeySpec(key Algorithm)

// if (debug ) System out println ( 解密前的信息 +byte hex (input ))

Cipher c = Cipher getInstance(Algorithm)

c init(Cipher DECRYPT_MODE deskey)

byte[] clearByte = c doFinal(input)

// if (debug )

// {

// System out println ( 解密后的二进串 +byte hex (clearByte ))

// System out println ( 解密后的字符串 +(new String (clearByte )))

//

// }

return clearByte;

}

public static byte[] decryptData(byte[] input) throws Exception {

return decryptData(input DEFAULT_KEY)

}

/**

* 字节码转换成 进制字符串

*

* @param byte[] b 输入要转换的字节码

* @return String 返回转换后的 进制字符串

*/

public static String byte hex(byte[] bytes) {

StringBuilder hs = new StringBuilder()

for(byte b : bytes)

hs append(String format( % $ X b))

return hs toString()

}

public static byte[] hex byte(String content) {

int l=content length()》 ;

byte[] result=new byte[l];

for(int i= ;i<l;i++) {

int j=i《 ;

String s=content substring(j j+ )

result[i]=Integer valueOf(s ) byteValue()

}

return result;

}

/**

* 将字节数组转换为base 编码字符串

* @param buffer

* @return

*/

public static String bytesToBase (byte[] buffer) {

//BASE Encoder en=new BASE Encoder()

return Base encode(buffer)

// return encoder encode(buffer)

}

/**

* 将base 编码的字符串解码为字节数组

* @param value

* @return

* @throws IOException

*/

public static byte[] base ToBytes(String value) throws IOException {

//return Base decodeToByteArray(value)

// System out println(decoder decodeBuffer(value))

// return decoder decodeBuffer(value)

return Base decode(value)

}

/**

* 加密给定的字符串

* @param value

* @return 加密后的base 字符串

*/

public static String encryptString(String value) {

return encryptString(value DEFAULT_KEY)

}

/**

* 根据给定的密钥加密字符串

* @param value 待加密的字符串

* @param key 以BASE 形式存在的密钥

* @return 加密后的base 字符串

* @throws IOException

*/

public static String encryptString(String value String key) throws IOException {

return encryptString(value base ToBytes(key))

}

/**

* 根据给定的密钥加密字符串

* @param value 待加密的字符串

* @param key 字节数组形式的密钥

* @return 加密后的base 字符串

*/

public static String encryptString(String value byte[] key) {

try {

byte[] data=value getBytes(VALUE_ENCODING)

data=CryptUtils encryptData(data key)

return bytesToBase (data)

} catch (Exception e) {

// TODO Auto generated catch block

e printStackTrace()

return null;

}

}

/**

* 解密字符串

* @param value base 形式存在的密文

* @return 明文

*/

public static String decryptString(String value) {

return decryptString(value DEFAULT_KEY)

}

/**

* 解密字符串

* @param value base 形式存在的密文

* @param key base 形式存在的密钥

* @return 明文

* @throws IOException

*/

public static String decryptString(String value String key) throws IOException {

String s=decryptString(value base ToBytes(key))

return s;

}

/**

* 解密字符串

* @param value base 形式存在的密文

* @param key 字节数据形式存在的密钥

* @return 明文

*/

public static String decryptString(String value byte[] key) {

try {

byte[] data=base ToBytes(value)

data=CryptUtils decryptData(data key)

return new String(data VALUE_ENCODING)

}catch(Exception e) {

e printStackTrace()

return null;

}

}

}

CryptHelper java

[java]

package gdie lab crypt;

import javax crypto Cipher;

import javax crypto SecretKey;

import javax crypto SecretKeyFactory;

import javax crypto spec DESKeySpec;

import javax crypto spec IvParameterSpec;

import springframework util DigestUtils;

public class CryptHelper{

private static String CRYPT_KEY = zhongqian ;

//加密

private static Cipher ecip;

//解密

private static Cipher dcip;

static {

try {

String KEY = DigestUtils md DigestAsHex(CRYPT_KEY getBytes()) toUpperCase()

KEY = KEY substring( )

byte[] bytes = KEY getBytes()

DESKeySpec ks = new DESKeySpec(bytes)

SecretKeyFactory skf = SecretKeyFactory getInstance( DES )

SecretKey sk = skf generateSecret(ks)

IvParameterSpec iv = new IvParameterSpec(bytes)

ecip = Cipher getInstance( DES/CBC/PKCS Padding )

ecip init(Cipher ENCRYPT_MODE sk iv )

dcip = Cipher getInstance( DES/CBC/PKCS Padding )

dcip init(Cipher DECRYPT_MODE sk iv )

}catch(Exception ex) {

ex printStackTrace()

}

}

public static String encrypt(String content) throws Exception {

byte[] bytes = ecip doFinal(content getBytes( ascii ))

return CryptUtils byte hex(bytes)

}

public static String decrypt(String content) throws Exception {

byte[] bytes = CryptUtils hex byte(content)

bytes = dcip doFinal(bytes)

return new String(bytes ascii )

}

//test

public static void main(String[] args) throws Exception {

String password = gly ;

String en = encrypt(password)

System out println(en)

System out println(decrypt(en))

}

}

package gdie lab crypt;

import javax crypto Cipher;

import javax crypto SecretKey;

import javax crypto SecretKeyFactory;

import javax crypto spec DESKeySpec;

import javax crypto spec IvParameterSpec;

import springframework util DigestUtils;

public class CryptHelper{

private static String CRYPT_KEY = zhongqian ;

//加密

private static Cipher ecip;

//解密

private static Cipher dcip;

static {

try {

String KEY = DigestUtils md DigestAsHex(CRYPT_KEY getBytes()) toUpperCase()

KEY = KEY substring( )

byte[] bytes = KEY getBytes()

DESKeySpec ks = new DESKeySpec(bytes)

SecretKeyFactory skf = SecretKeyFactory getInstance( DES )

SecretKey sk = skf generateSecret(ks)

IvParameterSpec iv = new IvParameterSpec(bytes)

ecip = Cipher getInstance( DES/CBC/PKCS Padding )

ecip init(Cipher ENCRYPT_MODE sk iv )

dcip = Cipher getInstance( DES/CBC/PKCS Padding )

dcip init(Cipher DECRYPT_MODE sk iv )

}catch(Exception ex) {

ex printStackTrace()

}

}

public static String encrypt(String content) throws Exception {

byte[] bytes = ecip doFinal(content getBytes( ascii ))

return CryptUtils byte hex(bytes)

}

public static String decrypt(String content) throws Exception {

byte[] bytes = CryptUtils hex byte(content)

bytes = dcip doFinal(bytes)

return new String(bytes ascii )

}

//test

public static void main(String[] args) throws Exception {

String password = gly ;

String en = encrypt(password)

System out println(en)

System out println(decrypt(en))

}

lishixin/Article/program/Java/hx/201311/26449

⑤ java des 加密 解密 密钥随机取得方法

java DES 加密 解密 生成随机密钥
举例说明:
//保存生成的key
public static void saveDesKey() {
try {
SecureRandom sr = new SecureRandom();
// 选择的DES算法生成一个KeyGenerator对象
KeyGenerator kg = KeyGenerator.getInstance("DES");
kg.init(sr);
// 相对路径 需要新建 conf 文件夹
// String fileName = "conf/DesKey.xml";
// 绝对路径
String fileName = "d:/DesKey.xml";
FileOutputStream fos = new FileOutputStream(fileName);
ObjectOutputStream oos = new ObjectOutputStream(fos);
// 生成密钥
Key key = kg.generateKey();
oos.writeObject(key);
oos.close();
} catch (Exception e) {
e.printStackTrace();
}
}
//获取生成的key
public static Key getKey() {
Key kp = null;
try {
// 相对路径 需要新建 conf 文件夹
// String fileName = "conf/DesKey.xml";
// InputStream is = Encrypt.class.getClassLoader().getResourceAsStream(fileName);
// 绝对路径
String fileName = "d:/DesKey.xml";
FileInputStream is = new FileInputStream(fileName);
ObjectInputStream oos = new ObjectInputStream(is);
kp = (Key) oos.readObject();
oos.close();
} catch (Exception e) {
e.printStackTrace();
}
return kp;
}
//加密开始
public static void encrypt(String file, String dest) throws Exception {
Cipher cipher = Cipher.getInstance("DES");
cipher.init(Cipher.ENCRYPT_MODE, getKey());
InputStream is = new FileInputStream(file);
OutputStream out = new FileOutputStream(dest);
CipherInputStream cis = new CipherInputStream(is, cipher);
byte[] buffer = new byte[1024];
int r;
while ((r = cis.read(buffer)) > 0) {
out.write(buffer, 0, r);
}
cis.close();
is.close();
out.close();
}
//解密开始
public static void decrypt(String file, String dest) throws Exception {
Cipher cipher = Cipher.getInstance("DES");
cipher.init(Cipher.DECRYPT_MODE, getKey());
InputStream is = new FileInputStream(file);
OutputStream out = new FileOutputStream(dest);
CipherOutputStream cos = new CipherOutputStream(out, cipher);
byte[] buffer = new byte[1024];
int r;
while ((r = is.read(buffer)) >= 0) {
cos.write(buffer, 0, r);
}
cos.close();
out.close();
is.close();
}
}
//des加密主方法
public class DES {
public static void main(String[] args) throws Exception {
Encrypt.saveDesKey();
System.out.println("生成key");
Encrypt.getKey();
System.out.println("获取key");
Encrypt.encrypt("d:\\hello.txt", "d:\\encrypt.txt");
System.out.println("加密");
Encrypt.decrypt("d:\\encrypt.txt", "d:\\decrypt.txt");
System.out.println("解密");
}
以上方法亲测可用。

⑥ 求一个java des32加密解密算法

packagecn.xinxi.des;

importjava.security.Key;
importjava.security.Security;

importjavax.crypto.Cipher;
importjavax.crypto.KeyGenerator;
importjavax.crypto.SecretKey;
importjavax.crypto.SecretKeyFactory;
importjavax.crypto.spec.DESKeySpec;
importorg.apache.commons.codec.binary.Hex;
importorg.bouncycastle.jce.provider.BouncyCastleProvider;


publicclassDES{
privatestaticfinalStringstr="xinxi";
publicstaticvoidmain(String[]args)throwsException{
jdkDES();
bcDES();
}
publicstaticvoidjdkDES()throwsException{
//生成key
//KeyGenerator,密钥生成器
KeyGeneratorkeyGenerator=KeyGenerator.getInstance("DES");
keyGenerator.init(56);//指定keysize这里使用默认值56位
//声称密钥
SecretKeysecreKey=keyGenerator.generateKey();
byte[]bytesKey=secreKey.getEncoded();

//key转换(恢复密钥)
// SecretKeyconvertSecreKey=newSecretKeySpec(bytesKey,"DES");//与下面三行效果貌似差不多
DESKeySpecdesKeySpec=newDESKeySpec(bytesKey);
SecretKeyFactoryfactory=SecretKeyFactory.getInstance("DES");
// System.out.println(keyGenerator.getProvider());
KeyconvertSecreKey=factory.generateSecret(desKeySpec);

//加密
Ciphercipher=Cipher.getInstance("DES/ECB/PKCS5Padding");//加密算法/工作方式/填充方式
cipher.init(Cipher.ENCRYPT_MODE,convertSecreKey);//模式(此处是加密模式)、key
byte[]result=cipher.doFinal(str.getBytes());//参数是要被加密的内容
System.out.println("JDKDES加密结果:"+Hex.encodeHexString(result));//转成16进制

//解密生成key和key转换与加密一样
cipher.init(Cipher.DECRYPT_MODE,convertSecreKey);//模式(此处是解密模式)、key
result=cipher.doFinal(result);
System.out.println("JDKDES解密结果:"+newString(result));
}
publicstaticvoidbcDES()throwsException{
Security.addProvider(newBouncyCastleProvider());

//生成key
KeyGeneratorkeyGenerator=KeyGenerator.getInstance("DES","BC");
// System.out.println(keyGenerator.getProvider());
keyGenerator.init(56);//指定keysize这里使用默认值56位
SecretKeysecreKey=keyGenerator.generateKey();
byte[]bytesKey=secreKey.getEncoded();

//key转换
DESKeySpecdesKeySpec=newDESKeySpec(bytesKey);
SecretKeyFactoryfactory=SecretKeyFactory.getInstance("DES");
KeyconvertSecreKey=factory.generateSecret(desKeySpec);

//加密
Ciphercipher=Cipher.getInstance("DES/ECB/PKCS5Padding");//加密算法/工作方式/填充方式
cipher.init(Cipher.ENCRYPT_MODE,convertSecreKey);//模式(此处是加密模式)、key
byte[]result=cipher.doFinal(str.getBytes());//参数是要被加密的内容
System.out.println("BCDES加密结果:"+Hex.encodeHexString(result));//转成16进制

//解密生成key和key转换与加密一样
cipher.init(Cipher.DECRYPT_MODE,convertSecreKey);//模式(此处是解密模式)、key
result=cipher.doFinal(result);
System.out.println("BCDES解密结果:"+newString(result));
}
}

是你想要的么?

⑦ java 中使用DES加密算法 生产的密钥为啥是8个字节

使用DES加密算法生产密钥,java6对DES算法仅支持56位密钥长度,但生成的密钥是64位的.在这64位中,实际的密钥只有56位,另有8位是奇偶校验位,分布于64位密钥中,每8位中有1 位奇偶检验位.

⑧ des密钥如何生成 java

package Encrypt;
import java.security.*;
import javax.crypto.*;
import sun.misc.*;
/**
* 使用DES加密与解密,可对byte[],String类型进行加密与解密
* 密文可使用String,byte[]存储.
* 方法:
* void getKey(String strKey)从strKey的字条生成一个Key
* String getEncString(String strMing)对strMing进行加密,返回String密文
* String getDesString(String strMi)对strMin进行解密,返回String明文
* byte[] getEncCode(byte[] byteS)byte[]型的加密
* byte[] getDesCode(byte[] byteD)byte[]型的解密
*/
public class Encrypt{
private Key key;
private byte[] byteMi = null;
private byte[] byteMing = null;
private String strMi= "";
private String strM= "";
// 根据参数生成KEY
public void setKey(String strKey){
try{
KeyGenerator _generator = KeyGenerator.getInstance("DES");
_generator.init(new SecureRandom(strKey.getBytes()));
this.key = _generator.generateKey();
_generator=null;
}
catch(Exception e){
e.printStackTrace();
}

}
// 加密String明文输入,String密文输出
public void setEncString(String strMing){
BASE64Encoder base64en = new BASE64Encoder();
try {
this.byteMing = strMing.getBytes("UTF8");
this.byteMi = this.getEncCode(this.byteMing);
this.strMi = base64en.encode(this.byteMi);
}
catch(Exception e)
{
e.printStackTrace();
}
finally
{

this.byteMing = null;
this.byteMi = null;
}
}
//加密以byte[]明文输入,byte[]密文输出
private byte[] getEncCode(byte[] byteS){
byte[] byteFina = null;
Cipher cipher;
try
{
cipher = Cipher.getInstance("DES");
cipher.init(Cipher.ENCRYPT_MODE,key);
byteFina = cipher.doFinal(byteS);
}
catch(Exception e)
{
e.printStackTrace();
}
finally
{
cipher = null;
}

return byteFina;
}
// 解密:以String密文输入,String明文输出
public void setDesString(String strMi){
BASE64Decoder base64De = new BASE64Decoder();
try
{
this.byteMi = base64De.decodeBuffer(strMi);
this.byteMing = this.getDesCode(byteMi);
this.strM = new String(byteMing,"UTF8");
}
catch(Exception e)
{
e.printStackTrace();
}
finally
{
base64De = null;
byteMing = null;
byteMi = null;
}

}
// 解密以byte[]密文输入,以byte[]明文输出
private byte[] getDesCode(byte[] byteD){
Cipher cipher;
byte[] byteFina=null;
try{
cipher = Cipher.getInstance("DES");
cipher.init(Cipher.DECRYPT_MODE,key);
byteFina = cipher.doFinal(byteD);
}
catch(Exception e)
{
e.printStackTrace();
}
finally
{
cipher=null;
}
return byteFina;
}
//返回加密后的密文strMi
public String getStrMi()
{
return strMi;
}
//返回解密后的明文
public String getStrM()
{
return strM;
}
}
*注意:因为我用的时候是作为后台的BEAN来调用的,所以没有写main函数,也就不能直接运行了。必须加一个main()函数才能做为一个完成的JAVA程序使用。一个很简单的 main()函数就ok了,不用我写在这里了吧?呵呵!

在WEB前台调用这个BEAN文件时的语句:
<jsp:useBean id="abc" scope="page" class="oaweb.Encrypt" />
//id="abc" 用来初始化一个对象
<%
//明文加密:
String key = “06”; //初始化密钥。
abc.setKey(key); //调用set函数设置密钥。
abc.setEncString(re[i][j]);//将要加密的明文传送给Encrypt.java进行加密计算。
String Mi=abc.getStrMi(); //调用get函数获取加密后密文。
%>
//变量Mi就是密文.
<%
//密文解密:
abc. setDesString(String Mi); //将要解密的密文传送给Encrypt.java进行解密计算。
String M=abc. String getStrM(); //调用get函数获取解密后明文。
%>
//变量M就是明文.

⑨ 如何用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!");
}
}
}

阅读全文

与javades密钥生成相关的资料

热点内容
狗狗币加密支付服务 浏览:895
怎么使用指南针APP确定方向 浏览:370
php读取图片并输出 浏览:319
如何组合多个pdf文件 浏览:668
工作表格excel取消加密 浏览:132
真空压缩袋手泵怎么用 浏览:425
镜面的命令 浏览:202
51单片机蓝牙模块有延迟 浏览:114
b解压药 浏览:568
跳空缺口指标源码怎么写 浏览:699
怎么杀掉服务器上所有进程 浏览:179
c语言中水仙花数的算法分析 浏览:493
心烦时玩儿的解压神器 浏览:496
linux安装的库文件 浏览:919
加密货币架构分析 浏览:523
我的世界怎么把材料包加到服务器里 浏览:757
平板内存卡新建文件夹失败 浏览:204
python模块打包 浏览:361
腾讯云服务器centos没有桌面 浏览:891
冒泡排序算法实验心得 浏览:688