當前位置:首頁 » 編程語言 » javapkcs

javapkcs

發布時間: 2023-03-13 13:49:22

java使用AES/CBC/PKCS5方式加密的內容,怎樣在C#下解密

java和C#只是語言,AES這些是演算法,所以和語言沒太大關系,
JAVA加密的「1」和c#加密的「1」結果是一樣的,解密出來也是一樣的。
///<summary>
///AES解密
///</summary>
///<paramname="cipherText">密文字元串</param>
///<returns>返回明文字元串</returns>
publicstaticstringAESDecrypt(stringshowText)
{
byte[]cipherText=Convert.FromBase64String(showText);
SymmetricAlgorithmdes=Rijndael.Create();
des.Key=Encoding.UTF8.GetBytes(Key);
des.IV=_key1;
byte[]decryptBytes=newbyte[cipherText.Length];
using(MemoryStreamms=newMemoryStream(cipherText))
{
using(CryptoStreamcs=newCryptoStream(ms,des.CreateDecryptor(),CryptoStreamMode.Read))
{
cs.Read(decryptBytes,0,decryptBytes.Length);
cs.Close();
ms.Close();
}
}
returnEncoding.UTF8.GetString(decryptBytes).Replace("","");///將字元串後尾的''去掉
}
}
上文為使用c#進行AES解密,其他的可以自行網路。

Ⅱ 求ECDSA的Java代碼

【方案1】

package ECDSA;

import com.sun.org.apache.xerces.internal.impl.dv.util.HexBin;

import java.security.*;

import java.security.interfaces.ECPrivateKey;

import java.security.interfaces.ECPublicKey;

import java.security.spec.PKCS8EncodedKeySpec;

import java.security.spec.X509EncodedKeySpec;


public class Ecdsa {

private static String src = "hello berber" ;

public static void main(String []args){

jdkECDSA();

}

public static void jdkECDSA(){

// 1.初始化密鑰

try{

KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("EC");

keyPairGenerator.initialize(256);

KeyPair keyPair = keyPairGenerator.generateKeyPair() ;

ECPublicKey ecPublicKey = (ECPublicKey)keyPair.getPublic() ;

ECPrivateKey ecPrivateKey = (ECPrivateKey)keyPair.getPrivate() ;

// 執行簽名

PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(ecPrivateKey.getEncoded());

KeyFactory keyFactory = KeyFactory.getInstance("EC") ;

PrivateKey privateKey = keyFactory.generatePrivate(pkcs8EncodedKeySpec) ;

Signature signature = Signature.getInstance("SHA1withECDSA");

signature.initSign(privateKey);

signature.update(src.getBytes());

byte []arr = signature.sign();

System.out.println("jdk ecdsa sign :"+ HexBin.encode(arr));

// 驗證簽名

X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(ecPublicKey.getEncoded());

keyFactory = KeyFactory.getInstance("EC");

PublicKey publicKey = keyFactory.generatePublic(x509EncodedKeySpec);

signature = Signature.getInstance("SHA1withECDSA");

signature.initVerify(publicKey);

signature.update(src.getBytes());

boolean bool = signature.verify(arr);

System.out.println("jdk ecdsa verify:"+bool);

}catch(Exception e){


}

}

}

Java數字簽名——ECDSA演算法

【方案2】

public class MyTest {

/**
* @param args
*/
public static void main(String[] args) {
new MyTest().getSign();
}

void getSign() {
// Get the instance of the Key Generator with "EC" algorithm

try {
KeyPairGenerator g = KeyPairGenerator.getInstance("EC");
ECGenParameterSpec kpgparams = new ECGenParameterSpec("secp256r1");
g.initialize(kpgparams);

KeyPair pair = g.generateKeyPair();
// Instance of signature class with SHA256withECDSA algorithm
Signature ecdsaSign = Signature.getInstance("SHA256withECDSA");
ecdsaSign.initSign(pair.getPrivate());

System.out.println("Private Keys is::" + pair.getPrivate());
System.out.println("Public Keys is::" + pair.getPublic());

String msg = "text ecdsa with sha256";//getSHA256(msg)
ecdsaSign.update((msg + pair.getPrivate().toString())
.getBytes("UTF-8"));

byte[] signature = ecdsaSign.sign();
System.out.println("Signature is::"
+ new BigInteger(1, signature).toString(16));

// Validation
ecdsaSign.initVerify(pair.getPublic());
ecdsaSign.update(signature);
if (ecdsaSign.verify(signature))
System.out.println("valid");
else
System.out.println("invalid!!!!");

} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}

}}
java – 使用secp256r1曲線和SHA256演算法生


怎麼驗證生成的Ecdsa簽名是正確的呢,可以看下這篇文章:RSA,ECC,Ecdsa,國密SM2的簽名,驗簽,加密

Ⅲ RSA PKCS#1在java中怎麼實現

樓主看看下面的代碼是不是你所需要的,這是我原來用的時候收集的
import javax.crypto.Cipher;
import java.security.*;
import java.security.spec.RSAPublicKeySpec;
import java.security.spec.RSAPrivateKeySpec;
import java.security.spec.InvalidKeySpecException;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.io.*;
import java.math.BigInteger;

/**
* RSA 工具類。提供加密,解密,生成密鑰對等方法。
* 需要到http://www.bouncycastle.org下載bcprov-jdk14-123.jar。
* RSA加密原理概述
* RSA的安全性依賴於大數的分解,公鑰和私鑰都是兩個大素數(大於100的十進制位)的函數。
* 據猜測,從一個密鑰和密文推斷出明文的難度等同於分解兩個大素數的積
* ===================================================================
* (該演算法的安全性未得到理論的證明)
* ===================================================================
* 密鑰的產生:
* 1.選擇兩個大素數 p,q ,計算 n=p*q;
* 2.隨機選擇加密密鑰 e ,要求 e 和 (p-1)*(q-1)互質
* 3.利用 Euclid 演算法計算解密密鑰 d , 使其滿足 e*d = 1(mod(p-1)*(q-1)) (其中 n,d 也要互質)
* 4:至此得出公鑰為 (n,e) 私鑰為 (n,d)
* ===================================================================
* 加解密方法:
* 1.首先將要加密的信息 m(二進製表示) 分成等長的數據塊 m1,m2,...,mi 塊長 s(盡可能大) ,其中 2^s<n
* 2:對應的密文是: ci = mi^e(mod n)
* 3:解密時作如下計算: mi = ci^d(mod n)
* ===================================================================
* RSA速度
* 由於進行的都是大數計算,使得RSA最快的情況也比DES慢上100倍,無論是軟體還是硬體實現。
* 速度一直是RSA的缺陷。一般來說只用於少量數據加密。
* 文件名:RSAUtil.java<br>
* @author 趙峰<br>
* 版本:1.0.1<br>
* 描述:本演算法摘自網路,是對RSA演算法的實現<br>
* 創建時間:2009-7-10 下午09:58:16<br>
* 文件描述:首先生成兩個大素數,然後根據Euclid演算法生成解密密鑰<br>
*/
public class RSAUtil {

//密鑰對
private KeyPair keyPair = null;

/**
* 初始化密鑰對
*/
public RSAUtil(){
try {
this.keyPair = this.generateKeyPair();
} catch (Exception e) {
e.printStackTrace();
}
}

/**
* 生成密鑰對
* @return KeyPair
* @throws Exception
*/
private KeyPair generateKeyPair() throws Exception {
try {
KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("RSA",new org.bouncycastle.jce.provider.BouncyCastleProvider());
//這個值關繫到塊加密的大小,可以更改,但是不要太大,否則效率會低
final int KEY_SIZE = 1024;
keyPairGen.initialize(KEY_SIZE, new SecureRandom());
KeyPair keyPair = keyPairGen.genKeyPair();
return keyPair;
} catch (Exception e) {
throw new Exception(e.getMessage());
}

}

/**
* 生成公鑰
* @param molus
* @param publicExponent
* @return RSAPublicKey
* @throws Exception
*/
private RSAPublicKey generateRSAPublicKey(byte[] molus, byte[] publicExponent) throws Exception {

KeyFactory keyFac = null;
try {
keyFac = KeyFactory.getInstance("RSA", new org.bouncycastle.jce.provider.BouncyCastleProvider());
} catch (NoSuchAlgorithmException ex) {
throw new Exception(ex.getMessage());
}
RSAPublicKeySpec pubKeySpec = new RSAPublicKeySpec(new BigInteger(molus), new BigInteger(publicExponent));
try {
return (RSAPublicKey) keyFac.generatePublic(pubKeySpec);
} catch (InvalidKeySpecException ex) {
throw new Exception(ex.getMessage());
}

}

/**
* 生成私鑰
* @param molus
* @param privateExponent
* @return RSAPrivateKey
* @throws Exception
*/
private RSAPrivateKey generateRSAPrivateKey(byte[] molus, byte[] privateExponent) throws Exception {
KeyFactory keyFac = null;
try {
keyFac = KeyFactory.getInstance("RSA", new org.bouncycastle.jce.provider.BouncyCastleProvider());
} catch (NoSuchAlgorithmException ex) {
throw new Exception(ex.getMessage());
}
RSAPrivateKeySpec priKeySpec = new RSAPrivateKeySpec(new BigInteger(molus), new BigInteger(privateExponent));
try {
return (RSAPrivateKey) keyFac.generatePrivate(priKeySpec);
} catch (InvalidKeySpecException ex) {
throw new Exception(ex.getMessage());
}
}

/**
* 加密
* @param key 加密的密鑰
* @param data 待加密的明文數據
* @return 加密後的數據
* @throws Exception
*/
public byte[] encrypt(Key key, byte[] data) throws Exception {
try {
Cipher cipher = Cipher.getInstance("RSA", new org.bouncycastle.jce.provider.BouncyCastleProvider());
cipher.init(Cipher.ENCRYPT_MODE, key);
// 獲得加密塊大小,如:加密前數據為128個byte,而key_size=1024 加密塊大小為127 byte,加密後為128個byte;
// 因此共有2個加密塊,第一個127 byte第二個為1個byte
int blockSize = cipher.getBlockSize();
// System.out.println("blockSize:"+blockSize);
int outputSize = cipher.getOutputSize(data.length);// 獲得加密塊加密後塊大小
// System.out.println("加密塊大小:"+outputSize);
int leavedSize = data.length % blockSize;
// System.out.println("leavedSize:"+leavedSize);
int blocksSize = leavedSize != 0 ? data.length / blockSize + 1 : data.length / blockSize;
byte[] raw = new byte[outputSize * blocksSize];
int i = 0;
while (data.length - i * blockSize > 0) {
if (data.length - i * blockSize > blockSize)
cipher.doFinal(data, i * blockSize, blockSize, raw, i * outputSize);
else
cipher.doFinal(data, i * blockSize, data.length - i * blockSize, raw, i * outputSize);
// 這裡面doUpdate方法不可用,查看源代碼後發現每次doUpdate後並沒有什麼實際動作除了把byte[]放到ByteArrayOutputStream中
// 而最後doFinal的時候才將所有的byte[]進行加密,可是到了此時加密塊大小很可能已經超出了OutputSize所以只好用dofinal方法。
i++;
}
return raw;
} catch (Exception e) {
throw new Exception(e.getMessage());
}
}

/**
* 解密
* @param key 解密的密鑰
* @param raw 已經加密的數據
* @return 解密後的明文
* @throws Exception
*/
@SuppressWarnings("static-access")
public byte[] decrypt(Key key, byte[] raw) throws Exception {
try {
Cipher cipher = Cipher.getInstance("RSA", new org.bouncycastle.jce.provider.BouncyCastleProvider());
cipher.init(cipher.DECRYPT_MODE, key);
int blockSize = cipher.getBlockSize();
ByteArrayOutputStream bout = new ByteArrayOutputStream(64);
int j = 0;
while (raw.length - j * blockSize > 0) {
bout.write(cipher.doFinal(raw, j * blockSize, blockSize));
j++;
}
return bout.toByteArray();
} catch (Exception e) {
throw new Exception(e.getMessage());
}
}

/**
* 返回公鑰
* @return
* @throws Exception
*/
public RSAPublicKey getRSAPublicKey() throws Exception{
//獲取公鑰
RSAPublicKey pubKey = (RSAPublicKey) keyPair.getPublic();
//獲取公鑰系數(位元組數組形式)
byte[] pubModBytes = pubKey.getMolus().toByteArray();
//返回公鑰公用指數(位元組數組形式)
byte[] pubPubExpBytes = pubKey.getPublicExponent().toByteArray();
//生成公鑰
RSAPublicKey recoveryPubKey = this.generateRSAPublicKey(pubModBytes,pubPubExpBytes);
return recoveryPubKey;
}

/**
* 獲取私鑰
* @return
* @throws Exception
*/
public RSAPrivateKey getRSAPrivateKey() throws Exception{
// 獲取私鑰
RSAPrivateKey priKey = (RSAPrivateKey) keyPair.getPrivate();
// 返回私鑰系數(位元組數組形式)
byte[] priModBytes = priKey.getMolus().toByteArray();
// 返回私鑰專用指數(位元組數組形式)
byte[] priPriExpBytes = priKey.getPrivateExponent().toByteArray();
// 生成私鑰
RSAPrivateKey recoveryPriKey = this.generateRSAPrivateKey(priModBytes,priPriExpBytes);
return recoveryPriKey;
}

/**
* 測試
* @param args
* @throws Exception
*/
public static void main(String[] args) throws Exception {
RSAUtil rsa = new RSAUtil();
String str = "天龍八部、神鵰俠侶、射鵰英雄傳白馬嘯西風";
RSAPublicKey pubKey = rsa.getRSAPublicKey();
RSAPrivateKey priKey = rsa.getRSAPrivateKey();
// System.out.println("加密後==" + new String(rsa.encrypt(pubKey,str.getBytes())));
String mw = new String(rsa.encrypt(pubKey, str.getBytes()));
System.out.println("加密後:"+mw);
// System.out.println("解密後:");
System.out.println("解密後==" + new String(rsa.decrypt(priKey,rsa.encrypt(pubKey,str.getBytes()))));
}
}

Ⅳ 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

熱點內容
動態規劃01背包演算法 發布:2024-11-05 22:17:40 瀏覽:849
nasm編譯器如何安裝 發布:2024-11-05 22:01:13 瀏覽:180
登錄密碼在微信的哪裡 發布:2024-11-05 22:00:29 瀏覽:739
c防止反編譯工具 發布:2024-11-05 21:56:14 瀏覽:247
安卓虛擬機怎麼用 發布:2024-11-05 21:52:48 瀏覽:344
php時間搜索 發布:2024-11-05 20:58:36 瀏覽:479
燕山大學編譯原理期末考試題 發布:2024-11-05 20:13:54 瀏覽:528
華為電腦出現臨時伺服器 發布:2024-11-05 20:05:08 瀏覽:408
斗戰神免費挖礦腳本 發布:2024-11-05 19:53:25 瀏覽:665
網吧伺服器分別是什麼 發布:2024-11-05 19:45:32 瀏覽:392