當前位置:首頁 » 編程語言 » 加解密java

加解密java

發布時間: 2023-06-14 06:39:36

㈠ 如何用java實現字元串簡單加密解密

importjava.util.Scanner;

publicclass加密
{
privatestaticScannersc=newScanner(System.in);
publicstaticvoidmain(String[]Args)
{
System.out.println(" ================字元串加密演示===================== ");
init();
}
//初始化!
privatestaticvoidinit()
{
for(;;)
{
char[]arr=input();
jiaMi(arr,20140908);
jiaMi(20140908,arr);
}

}
//鍵盤錄取!
privatestaticchar[]input()
{
Strings=sc.nextLine();
inta=s.length();
char[]arr=newchar[a];
//char[]arr=s.toCharArray();
for(inti=0;i<s.length();i++)
{
arr[i]=s.charAt(i);
}
returnarr;
}
//加密!!
privatestaticvoidjiaMi(char[]arr,inta)
{
for(inti=0;i<arr.length;i++)
{
arr[i]=((char)(arr[i]^a));
}
System.out.println("加密完成!");
print(arr);
}
//解密!!
privatestaticvoidjiaMi(inta,char[]arr)
{
for(inti=0;i<arr.length;i++)
{
arr[i]=((char)(arr[i]^a));
}
System.out.println("解密完成");
print(arr);
}
//列印!!
privatestaticvoidprint(char[]arr)
{
for(inti=0;i<arr.length;i++)
{
System.out.print(arr[i]);
}
System.out.println(" ========================= ");
}
}

㈡ java如何用Aes加密和解密

你解密的key必須是加密的key啊
你看看,你解密的時候又KeyGenerator.getInstance("AES").generateKey();這是重新搞了一個key啊,當然解不出來了
我估計你這代碼人家原先是寫在一起的吧,加密完了再直接解密給你看,人家只generateKey一次,自然很順利,你分成了兩個例子,居然分別generateKey,自然失敗

㈢ 請教個關於Java實現AES加解密的問題

JDK對DESede演算法的支持

密鑰長度:128位
工作模式:ECB/CBC/PCBC/CTR/CTS/CFB/CFB8 to CFB128/OFB/OBF8 to OFB128
填充方式:Nopadding/PKCS5Padding/ISO10126Padding/

AES加密解密的java實現:

package com.kongxincai.encanddec;import java.security.Key;import java.security.NoSuchAlgorithmException;import javax.crypto.Cipher;import javax.crypto.KeyGenerator;import javax.crypto.SecretKey;import javax.crypto.spec.SecretKeySpec;public class AESCoder { private static final String KEY_ALGORITHM = "AES"; private static final String DEFAULT_CIPHER_ALGORITHM = "AES/ECB/PKCS5Padding";//默認的加密演算法

public static byte[] initSecretKey() { //返回生成指定演算法密鑰生成器的 KeyGenerator 對象
KeyGenerator kg = null; try {
kg = KeyGenerator.getInstance(KEY_ALGORITHM);
} catch (NoSuchAlgorithmException e) {
e.printStackTrace(); return new byte[0];
} //初始化此密鑰生成器,使其具有確定的密鑰大小 //AES 要求密鑰長度為 128
kg.init(128); //生成一個密鑰
SecretKey secretKey = kg.generateKey(); return secretKey.getEncoded();
} private static Key toKey(byte[] key){ //生成密鑰
return new SecretKeySpec(key, KEY_ALGORITHM);
} public static byte[] encrypt(byte[] data,Key key) throws Exception{ return encrypt(data, key,DEFAULT_CIPHER_ALGORITHM);
} public static byte[] encrypt(byte[] data,byte[] key) throws Exception{ return encrypt(data, key,DEFAULT_CIPHER_ALGORITHM);
} public static byte[] encrypt(byte[] data,byte[] key,String cipherAlgorithm) throws Exception{ //還原密鑰
Key k = toKey(key); return encrypt(data, k, cipherAlgorithm);
} public static byte[] encrypt(byte[] data,Key key,String cipherAlgorithm) throws Exception{ //實例化
Cipher cipher = Cipher.getInstance(cipherAlgorithm); //使用密鑰初始化,設置為加密模式 cipher.init(Cipher.ENCRYPT_MODE, key); //執行操作
return cipher.doFinal(data);
} public static byte[] decrypt(byte[] data,byte[] key) throws Exception{ return decrypt(data, key,DEFAULT_CIPHER_ALGORITHM);
} public static byte[] decrypt(byte[] data,Key key) throws Exception{ return decrypt(data, key,DEFAULT_CIPHER_ALGORITHM);
} public static byte[] decrypt(byte[] data,byte[] key,String cipherAlgorithm) throws Exception{ //還原密鑰
Key k = toKey(key); return decrypt(data, k, cipherAlgorithm);
} public static byte[] decrypt(byte[] data,Key key,String cipherAlgorithm) throws Exception{ //實例化
Cipher cipher = Cipher.getInstance(cipherAlgorithm); //使用密鑰初始化,設置為解密模式 cipher.init(Cipher.DECRYPT_MODE, key); //執行操作
return cipher.doFinal(data);
} private static String showByteArray(byte[] data){ if(null == data){ return null;
}
StringBuilder sb = new StringBuilder("{"); for(byte b:data){
sb.append(b).append(",");
}
sb.deleteCharAt(sb.length()-1);
sb.append("}"); return sb.toString();
} public static void main(String[] args) throws Exception { byte[] key = initSecretKey();
System.out.println("key:"+showByteArray(key));
Key k = toKey(key); //生成秘鑰
String data ="AES數據";
System.out.println("加密前數據: string:"+data);
System.out.println("加密前數據: byte[]:"+showByteArray(data.getBytes()));
System.out.println(); byte[] encryptData = encrypt(data.getBytes(), k);//數據加密
System.out.println("加密後數據: byte[]:"+showByteArray(encryptData));// System.out.println("加密後數據: hexStr:"+Hex.encodeHexStr(encryptData)); System.out.println(); byte[] decryptData = decrypt(encryptData, k);//數據解密
System.out.println("解密後數據: byte[]:"+showByteArray(decryptData));
System.out.println("解密後數據: string:"+new String(decryptData));
}
}

㈣ 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實現字元串簡單加密解密

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加密解密代碼

package com.cube.limail.util;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;/**
* 加密解密類
*/
public class Eryptogram
{
private static String Algorithm ="DES";
private String key="CB7A92E3D3491964";
//定義 加密演算法,可用 DES,DESede,Blowfish
static boolean debug = false ;
/**
* 構造子註解.
*/
public Eryptogram ()
{

} /**
* 生成密鑰
* @return byte[] 返回生成的密鑰
* @throws exception 扔出異常.
*/
public static byte [] getSecretKey () throws Exception
{
KeyGenerator keygen = KeyGenerator.getInstance (Algorithm );
SecretKey deskey = keygen.generateKey ();
System.out.println ("生成密鑰:"+bytesToHexString (deskey.getEncoded ()));
if (debug ) System.out.println ("生成密鑰:"+bytesToHexString (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 ("加密前的二進串:"+byte2hex (input ));
System.out.println ("加密前的字元串:"+new String (input ));

} Cipher c1 = Cipher.getInstance (Algorithm );
c1.init (Cipher.ENCRYPT_MODE ,deskey );
byte [] cipherByte =c1.doFinal (input );
if (debug ) System.out.println ("加密後的二進串:"+byte2hex (cipherByte ));
return cipherByte ;

} /**
* 將給定的已加密的數據通過指定的密鑰進行解密
* @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 ("解密前的信息:"+byte2hex (input ));
Cipher c1 = Cipher.getInstance (Algorithm );
c1.init (Cipher.DECRYPT_MODE ,deskey );
byte [] clearByte =c1.doFinal (input );
if (debug )
{
System.out.println ("解密後的二進串:"+byte2hex (clearByte ));
System.out.println ("解密後的字元串:"+(new String (clearByte )));

} return clearByte ;

} /**
* 位元組碼轉換成16進制字元串
* @param byte[] b 輸入要轉換的位元組碼
* @return String 返回轉換後的16進制字元串
*/
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 ();

}

/**
* 字元串轉成位元組數組.
* @param hex 要轉化的字元串.
* @return byte[] 返回轉化後的字元串.
*/
public static byte[] hexStringToByte(String hex) {
int len = (hex.length() / 2);
byte[] result = new byte[len];
char[] achar = hex.toCharArray();
for (int i = 0; i < len; i++) {
int pos = i * 2;
result[i] = (byte) (toByte(achar[pos]) << 4 | toByte(achar[pos + 1]));
}
return result;
}
private static byte toByte(char c) {
byte b = (byte) "0123456789ABCDEF".indexOf(c);
return b;
}

/**
* 位元組數組轉成字元串.
* @param String 要轉化的字元串.
* @return 返回轉化後的位元組數組.
*/
public static final String bytesToHexString(byte[] bArray) {
StringBuffer sb = new StringBuffer(bArray.length);
String sTemp;
for (int i = 0; i < bArray.length; i++) {
sTemp = Integer.toHexString(0xFF & bArray[i]);
if (sTemp.length() < 2)
sb.append(0);
sb.append(sTemp.toUpperCase());
}
return sb.toString();
}

/**
* 從資料庫中獲取密鑰.
* @param deptid 企業id.
* @return 要返回的位元組數組.
* @throws Exception 可能拋出的異常.
*/
public static byte[] getSecretKey(long deptid) throws Exception {
byte[] key=null;
String value=null;
//CommDao =new CommDao();
// List list=.getRecordList("from Key k where k.deptid="+deptid);
//if(list.size()>0){
//value=((com.csc.sale.bean.Key)list.get(0)).getKey();
value = "CB7A92E3D3491964";
key=hexStringToByte(value);
//}
if (debug)
System.out.println("密鑰:" + value);
return key;
}

public String encryptData2(String data) {
String en = null;
try {
byte[] key=hexStringToByte(this.key);
en = bytesToHexString(encryptData(data.getBytes(),key));
} catch (Exception e) {
e.printStackTrace();
}
return en;
}

public String decryptData2(String data) {
String de = null;
try {
byte[] key=hexStringToByte(this.key);
de = new String(decryptData(hexStringToByte(data),key));
} catch (Exception e) {
e.printStackTrace();
}
return de;
}
} 加密使用: byte[] key=Eryptogram.getSecretKey(deptid); //獲得鑰匙(位元組數組)
byte[] tmp=Eryptogram.encryptData(password.getBytes(), key); //傳入密碼和鑰匙,獲得加密後的位元組數組的密碼
password=Eryptogram.bytesToHexString(tmp); //將位元組數組轉化為字元串,獲得加密後的字元串密碼解密與之差不多

㈦ java編寫數字加密解密

//package wangcai.test;

public interface Endecryption {
public static final byte[] EN={48,49,50,51,52,53,54,55,56,57};
public static final byte[] DE={55,53,57,49,51,54,56,48,50,52};
}

//package wangcai.test;
import java.util.Scanner;

public class Cryption implements Endecryption{
/*
* 原始數字與加密後得到的密文數字之間的對應關系如下:

原始數字:0 1 2 3 4 5 6 7 8 9
密文數字:7 5 9 1 3 6 8 0 2 4

試編寫程序把原始數字轉換成加密密文或把加密密文轉換成原始數字。
輸入:
1 6 (第一個數表示加密或解密:1加密,2解密;第二個數表示數字的個數)
1 9 9 7 7 1 (待處理的數字內容)
輸出:
5 4 4 0 0 5
*/

public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);

Cryption c=new Cryption();
System.out.println("請輸入是加密還是解密:1加密,2解密");
int ende=sc.nextInt();
if(ende==1)
{
System.out.println("請輸入加密的數字個數");
int num=sc.nextInt();
System.out.println("請輸入"+num+"個數字");
String temp=new Scanner(System.in).nextLine();
System.out.println(c.Encryption(temp));
}
else if(ende==2)
{
System.out.println("請輸入解密的數字個數");
int num=sc.nextInt();
System.out.println("請輸入"+num+"個數字");
String temp=new Scanner(System.in).nextLine();
System.out.println(c.Decryption(temp));
}
else
{
System.out.println("輸入錯誤");
}

}

/**
* 加密
* @param temp
* @return
*/
public String Encryption(String temp)
{
String result="";
byte[] temp_byte=temp.getBytes();
for(byte b:temp_byte)
{
int i=0;
for(;i<EN.length;i++)
{
if(b==EN[i])
{
result+=(char)DE[i];
break;
}
}
if(i==EN.length)
{
result+=(char)b;
}
}
return result;
}

/**
* 解密
* @param temp
* @return
*/
public String Decryption(String temp)
{
String result="";
byte[] temp_byte=temp.getBytes();
for(byte b:temp_byte)
{
int i=0;
for(;i<DE.length;i++)
{
if(b==DE[i])
{
result+=(char)EN[i];
break;
}
}
if(i==DE.length)
{
result+=(char)b;
}
}
return result;
}

}
加密解密方面的一般採用byte來實現

㈧ Java 加密解密的方法都有哪些

加密解密並非java才有的,所有編程語言都有加密和解密。

目前的加密解密主要可分為以下2大類:

  1. 對稱秘鑰加密:如DES演算法,3DES演算法,TDEA演算法,Blowfish演算法,RC5演算法,IDEA演算法等。其主要特點是加密方和解密方都有同一個密碼,加密方和解密方可以使用秘鑰任意加密解密。

  2. 非對稱密碼加密:這種加密方式加密方僅有加密秘鑰,對加密後的密文無法反向解密,解密方僅有解密秘鑰,無法對明文進行加密。


另外還有一些摘要演算法,比如MD5和HASH此類演算法不可逆,但經常用來作為確認欄位或者對一些重要匹配信息簽名防止明文內容被修改。

㈨ Java文件加解密

做網站有時會處理一些上傳下載的文件 可能會用到加解密功能 以下是一個加解密方法

Java代碼

import java io File;

import java io FileInputStream;

import java io FileOutputStream;

import java io IOException;

import nf Conf;

import mon time TimeHandler;

/**

* 加解密單元

* @author lupingui

* : :

*/

public class EncryptDecrypt {

//加解密KEY 這個不能變動 這里可以由任意的字元組成 盡量用特殊字元

static final byte[] KEYVALUE = getBytes();

//讀取位元組的長度

static final int BUFFERLEN = ;

//加密臨時存儲目錄

static final String TRANSIT_DIR_ENC = ;

//解密臨時存儲目錄

static final String TRANSIT_DIR_DEC = ;

/**

* 文件加密

* @param oldFile 待加密文件

* @param saveFileName 加密後文件保存路徑

* @return

* @throws IOException

*/

public static boolean encryptFile(File oldFile String saveFileName) throws IOException{

//如果傳入的文件不存在或者不是文件則直接返回

if (!oldFile exists() || !oldFile isFile()){

return false;

}

FileInputStream in = new FileInputStream(oldFile);

//加密後存儲的文件

File file = new File(saveFileName);

if (!file exists()){

return false;

}

//讀取待加密文件加密後寫入加密存儲文件中

FileOutputStream out = new FileOutputStream(file);

int c pos keylen;

pos = ;

keylen = KEYVALUE length;

byte buffer[] = new byte[BUFFERLEN];

while ((c = in read(buffer)) != ) {

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

buffer[i] ^= KEYVALUE[pos];

out write(buffer[i]);

pos++;

if (pos == keylen){

pos = ;

}

}

}

in close();

out close();

return true;

}

/**

* 文件加密

* @param oldFile:待加密文件

* @param saveFile 加密後的文件

* @return

* @throws IOException

*/

public static boolean encryptFile(File oldFile File saveFile) throws IOException{

//如果傳入的文件不存在或者不是文件則直接返回

if (!oldFile exists() || !oldFile isFile() || !saveFile exists() || !saveFile isFile()){

return false;

}

FileInputStream in = new FileInputStream(oldFile);

//讀取待加密文件加密後寫入加密存儲文件中

FileOutputStream out = new FileOutputStream(saveFile);

int c pos keylen;

pos = ;

keylen = KEYVALUE length;

byte buffer[] = new byte[BUFFERLEN];

while ((c = in read(buffer)) != ) {

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

buffer[i] ^= KEYVALUE[pos];

out write(buffer[i]);

pos++;

if (pos == keylen){

pos = ;

}

}

}

in close();

out close();

return true;

}

/**

* 文件加密

* @param oldFile 待加密文件

* @return

* @throws IOException

*/

public static File encryptFile(File oldFile) throws IOException{

//如果傳入的文件不存在或者不是文件則直接返回

if (!oldFile exists() || !oldFile isFile()){

return null;

}

FileInputStream in = new FileInputStream(oldFile);

//臨時加密文件存儲目錄

File dirFile = new File(TRANSIT_DIR_ENC);

//如果臨時存儲目錄不存在或不是目錄則直接返回

if (!dirFile exists() || !dirFile isDirectory()){

return null;

}

//加密後存儲的文件

File file = new File(dirFile enc_ + TimeHandler getInstance() getTimeInMillis() + _ + oldFile getName());

if (!file exists()){

file createNewFile();

}

//讀取待加密文件加密後寫入加密存儲文件中

FileOutputStream out = new FileOutputStream(file);

int c pos keylen;

pos = ;

keylen = KEYVALUE length;

byte buffer[] = new byte[BUFFERLEN];

while ((c = in read(buffer)) != ) {

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

buffer[i] ^= KEYVALUE[pos];

out write(buffer[i]);

pos++;

if (pos == keylen){

pos = ;

}

}

}

in close();

out close();

//返回加密後的文件

return file;

}

/**

* 文件加密

* @param oldFileName 待加密文件路徑

* @return

* @throws IOException

* @throws Exception

*/

public static File encryptFile(String oldFileName) throws IOException {

//如果待加密文件路徑不正確則直接返回

if (oldFileName == null || oldFileName trim() equals( )){

return null;

}

//待加密文件

File oldFile = new File(oldFileName);

//如果傳入的文件不存在或者不是文件則直接返回

if (!oldFile exists() || !oldFile isFile()){

return null;

}

//調用文件加密方法並返回結果

return encryptFile(oldFile);

}

/**

* 文件解密

* @param oldFile 待解密文件

* @return

* @throws IOException

*/

public static File decryptFile(File oldFile) throws IOException{

//如果待解密文件不存在或者不是文件則直接返回

if (!oldFile exists() || !oldFile isFile()){

return null;

}

FileInputStream in = new FileInputStream(oldFile);

//臨時解密文件存儲目錄

File dirFile = new File(TRANSIT_DIR_DEC);

//如果臨時解密文件存儲目錄不存在或不是目錄則返回

if (!dirFile exists() || !dirFile isDirectory()){

return null;

}

//解密存儲文件

File file = new File(dirFile dec_ + TimeHandler getInstance() getTimeInMillis() + _ + oldFile getName() substring(oldFile getName() lastIndexOf( )));

if (!file exists()){

file createNewFile();

}

//讀取待解密文件並進行解密存儲

FileOutputStream out = new FileOutputStream(file);

int c pos keylen;

pos = ;

keylen = KEYVALUE length;

byte buffer[] = new byte[BUFFERLEN];

while ((c = in read(buffer)) != ) {

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

buffer[i] ^= KEYVALUE[pos];

out write(buffer[i]);

pos++;

if (pos == keylen){

pos = ;

}

}

}

in close();

out close();

//返回解密結果文件

return file;

}

/**

* 文件解密

* @param oldFileName 待解密文件路徑

* @return

* @throws Exception

*/

public static File decryptFile(String oldFileName) throws Exception {

//如果待解密文件路徑不正確則直接返回

if (oldFileName == null || oldFileName trim() equals( )){

return null;

}

//待解密文件

File oldFile = new File(oldFileName);

//如果待解密文件不存在或不是文件則直接返回

if (!oldFile exists() || !oldFile isFile()){

return null;

}

//調用文件解密方法並返回結果

return decryptFile(oldFile);

}

lishixin/Article/program/Java/hx/201311/26983

㈩ 如何用java實現加密與解密

通常比較簡單的加密方法就是你把文本文件載入讀取以後,得到的每一個char加上一個固定的整數,然後再保存,這樣內容就看不懂了。
再讀取以後,把每一個char減去固定的整數,然後保存,就還原回來了。
這種方法是最最簡單的加密方式,不需要使用任何的加密演算法。

熱點內容
php把數據插入資料庫 發布:2025-02-13 00:09:48 瀏覽:369
eclipse查看jar包源碼 發布:2025-02-12 23:59:35 瀏覽:973
電腦主機伺服器維修 發布:2025-02-12 23:59:26 瀏覽:302
sqlserver標識 發布:2025-02-12 23:51:33 瀏覽:463
安卓怎麼玩地牢獵人 發布:2025-02-12 23:50:25 瀏覽:944
思鄉腳本 發布:2025-02-12 23:43:32 瀏覽:440
java的job 發布:2025-02-12 23:38:43 瀏覽:893
我的世界伺服器授權指令 發布:2025-02-12 23:30:13 瀏覽:597
電腦伺服器號在哪裡找 發布:2025-02-12 23:22:29 瀏覽:13
linux查看系統是32位 發布:2025-02-12 23:17:29 瀏覽:990