導航:首頁 > 編程語言 > java加密key加密

java加密key加密

發布時間:2024-06-25 11:35:03

java 鍔犲瘑鐨勭ず渚

import java.security.*;
import javax.crypto.*;
import java.io.*;
public class tCipher
{
public static void main(String[] args)
{
test_Cipher();
}
public static void test_Cipher()
{
try
{
//寰呭姞瀵嗙殑鏁版嵁
String strToEnc = "Hello Java!";
byte[] plainText = strToEnc.getBytes();
System.out.println( "\n寮濮嬬敓鎴怐ES瀵嗛掗" );
KeyGenerator keyGen = KeyGenerator.getInstance("DES"); //鍒濆嬪寲涓篋ES綆楁硶
keyGen.init(56); //璁劇疆鍏跺瘑閽ラ暱搴︼紝56bits
Key key = keyGen.generateKey(); //鐢熸垚瀵嗛掗
System.out.println( "鐢熸垚DES瀵嗛掗鎴愬姛銆" );
//鎵撳嵃鍑篋ES瀵嗛掗
byte[] keyencode=key.getEncoded();
PrintHex(keyencode,keyencode.length);

//鐢熸垚Cipher瀵硅薄錛岃劇疆綆楁硶涓篍CB妯″紡鐨凞ES綆楁硶錛岃ˉ浣嶅~鍏呮ā寮忎負PKCS5
Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
//鎵撳嵃Cipher瀵硅薄瀵嗙爜鏈嶅姟鎻愪緵鑰呬俊鎮
System.out.println( "\n" + cipher.getProvider().getInfo() );
// 鍔犲瘑
System.out.println( "\n寮濮嬪姞瀵" );
cipher.init(Cipher.ENCRYPT_MODE, key);//cipher瀵硅薄鍒濆嬪寲錛岃劇疆涓哄姞瀵
byte[] cipherText = cipher.doFinal(plainText);//緇撴潫鏁版嵁鍔犲瘑錛岃緭鍑哄瘑鏂
System.out.println( "鍔犲瘑瀹屾垚錛屽瘑鏂囦負錛 " );
PrintHex(cipherText,cipherText.length);//鎵撳嵃瀵嗘枃

// 浣跨敤鐩稿悓鐨刱ey瑙e瘑鏁版嵁
System.out.println( "\n寮濮嬭В瀵" );
cipher.init(Cipher.DECRYPT_MODE, key);
byte[] newPlainText = cipher.doFinal(cipherText);
System.out.println( "瑙e瘑瀹屾垚 錛屾槑鏂囦負錛" );
//杈撳嚭鍘熸枃
System.out.println( new String(newPlainText, "UTF8") );
}
catch (Exception e)
{
System.out.println("鍔犺В瀵嗗嚭閿欍");
}
}
public static void PrintHex(byte data[],int len)
{
int i;
int tmp;
String Tmp="";
for(i=0; i<len; i++)
{
if(i%16 == 0)
{
System.out.println("");
//0x0000
if(i<0x10)
Tmp = "0x000";
if((i<0x100) && (i>=0x10))
Tmp = "0x00";
if((i>=0x100)&&(i<0x1000))
Tmp = "0x0";
if(i>=0x1000)
Tmp = "0x";
System.out.print(Tmp+Integer.toHexString(i)+"h: ");
}
tmp = data[i];
if(tmp < 0)
tmp = 256 + tmp;
if(tmp <0x10)
System.out.print("0"+Integer.toHexString(tmp) +" ");
else
System.out.print(Integer.toHexString(tmp) +" ");
}
System.out.println("");
}
}

② JAVA公鑰加密,私鑰解密,該怎麼解決

一個比較簡單的實現:一個三個類KeyGenerater生成公鑰私鑰對,Signaturer類使用私鑰簽名,SignProvider用公鑰驗證。公鑰和私鑰使用Base64加密Base64這個類也在博客裡面
public class KeyGenerater {
private byte[] priKey;
private byte[] pubKey;
public void generater() {
try {
Java.security.KeyPairGenerator keygen = java.security.KeyPairGenerator
.getInstance("RSA");
SecureRandom secrand = new SecureRandom();
secrand.setSeed("syj".getBytes()); // 初始化隨機產生器
keygen.initialize(1024, secrand);
KeyPair keys = keygen.genKeyPair();
PublicKey pubkey = keys.getPublic();
PrivateKey prikey = keys.getPrivate();
pubKey = Base64.encodeToByte(pubkey.getEncoded());
priKey = Base64.encodeToByte(prikey.getEncoded());
System.out.println("pubKey = " + new String(pubKey));
System.out.println("priKey = " + new String(priKey));
} catch (java.lang.Exception e) {
System.out.println("生成密鑰對失敗");
e.printStackTrace();
}
}
public byte[] getPriKey() {
return priKey;
}
public byte[] getPubKey() {
return pubKey;
}
}

public class Signaturer {
/**
*
* Description:數字簽名
*
* @param priKeyText
* @param plainText
* @return
* @author 孫鈺佳
* @since:2007-12-27 上午10:51:48
*/
public static byte[] sign(byte[] priKeyText, String plainText) {
try {
PKCS8EncodedKeySpec priPKCS8 = new PKCS8EncodedKeySpec(Base64
.decode(priKeyText));
KeyFactory keyf = KeyFactory.getInstance("RSA");
PrivateKey prikey = keyf.generatePrivate(priPKCS8);
// 用私鑰對信息生成數字簽名
java.security.Signature signet = java.security.Signature
.getInstance("MD5withRSA");
signet.initSign(prikey);
signet.update(plainText.getBytes());
byte[] signed = Base64.encodeToByte(signet.sign());
return signed;
} catch (java.lang.Exception e) {
System.out.println("簽名失敗");
e.printStackTrace();
}
return null;
}
}
public class SignProvider {
private SignProvider() {
}
/**
*
* Description:校驗數字簽名,此方法不會拋出任務異常,成功返回true,失敗返回false,要求全部參數不能為空
*
* @param pubKeyText
* 公鑰,base64編碼
* @param plainText
* 明文
* @param signTest
* 數字簽名的密文,base64編碼
* @return 校驗成功返回true 失敗返回false
* @author 孫鈺佳
* @since:2007-12-27 上午09:33:55
*/
public static boolean verify(byte[] pubKeyText, String plainText,
byte[] signText) {
try {
// 解密由base64編碼的公鑰,並構造X509EncodedKeySpec對象
java.security.spec.X509EncodedKeySpec bobPubKeySpec = new java.security.spec.X509EncodedKeySpec(
Base64.decode(pubKeyText));
// RSA對稱加密演算法
java.security.KeyFactory keyFactory = java.security.KeyFactory
.getInstance("RSA");
// 取公鑰匙對象
java.security.PublicKey pubKey = keyFactory
.generatePublic(bobPubKeySpec);
// 解密由base64編碼的數字簽名
byte[] signed = Base64.decode(signText);
java.security.Signature signatureChecker = java.security.Signature
.getInstance("MD5withRSA");
signatureChecker.initVerify(pubKey);
signatureChecker.update(plainText.getBytes());
// 驗證簽名是否正常
if (signatureChecker.verify(signed))
return true;
else
return false;
} catch (Throwable e) {
System.out.println("校驗簽名失敗");
e.printStackTrace();
return false;
}
}
}

望採納,謝謝。

③ 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加密

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加密的bug解決辦法,要求能用16位key並且不讓加密後長度多8個位元組;

在java中調用sun公司提供的3DES加密解密演算法時,需要使用到$JAVA_HOME/jre/lib/目錄下如下的4個jar包:
jce.jar
security/US_export_policy.jar
security/local_policy.jar
ext/sunjce_provider.jar
Java運行時會自動載入這些包,因此對於帶main函數的應用程序不需要設置到CLASSPATH環境變數中。對於WEB應用,不需要把這些包加到WEB-INF/lib目錄下。
以下是java中調用sun公司提供的3DES加密解密演算法的樣本代碼:
加密解密代碼
import java.security.Security;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
/*字元串 DESede(3DES) 加密*/
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實現字元串簡單加密解密

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

⑦ 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加密key加密相關的資料

熱點內容
風險app在哪裡下載 瀏覽:67
在線免費觀看網站 瀏覽:834
國外男男片 瀏覽:333
復雜零件加工編程 瀏覽:794
pdf如何加深顏色 瀏覽:774
android文件刪除命令 瀏覽:915
快播 瀏覽:622
雲伺服器測試作業 瀏覽:737
書簽怎麼移動到文件夾 瀏覽:577
iosoppo怎麼把數據傳輸到安卓 瀏覽:236
sql預處理命令 瀏覽:319
linux安裝swftools 瀏覽:621
python執行環境 瀏覽:326
c語言回歸演算法 瀏覽:136
色階命令實現的功能為 瀏覽:49
盲區雷達編程匹配 瀏覽:685
輕量應用伺服器如何下載qq 瀏覽:962
數據存放在ecs雲伺服器 瀏覽:974
文件夾和上網有關系嗎 瀏覽:472
求索app進去一直看不了怎麼辦 瀏覽:190