java 加密工具类(MD5、RSA、AES等加密方式)
1.加密工具類encryption
MD5加密
[java] view plain copy print?
importorg.apache.commons.codec.digest.DigestUtils;
/**
*MD5加密組件
*
*@authorwbw
*@version1.0
*@since1.0
*/
publicabstractclassMD5Util{
/**
*MD5加密
*
*@paramdata
*待加密數據
*@returnbyte[]消息摘要
*
*@throwsException
*/
publicstaticbyte[]encodeMD5(Stringdata)throwsException{
//執行消息摘要
returnDigestUtils.md5(data);
}
/**
*MD5加密
*
*@paramdata
*待加密數據
*@returnbyte[]消息摘要
*
*@throwsException
*/
publicstaticStringencodeMD5Hex(Stringdata){
//執行消息摘要
returnDigestUtils.md5Hex(data);
}
}
AES加密:
[java] view plain copy print?
importjavax.crypto.Cipher;
importjavax.crypto.spec.SecretKeySpec;
publicclassAESUtil{
privatestaticfinalStringKEY_AES="AES";
publicstaticStringencrypt(Stringsrc,Stringkey)throwsException{
if(key==null||key.length()!=16){
thrownewException("key不滿足條件");
}
byte[]raw=key.getBytes();
SecretKeySpecskeySpec=newSecretKeySpec(raw,KEY_AES);
Ciphercipher=Cipher.getInstance(KEY_AES);
cipher.init(Cipher.ENCRYPT_MODE,skeySpec);
byte[]encrypted=cipher.doFinal(src.getBytes());
returnbyte2hex(encrypted);
}
publicstaticStringdecrypt(Stringsrc,Stringkey)throwsException{
if(key==null||key.length()!=16){
thrownewException("key不滿足條件");
}
byte[]raw=key.getBytes();
SecretKeySpecskeySpec=newSecretKeySpec(raw,KEY_AES);
Ciphercipher=Cipher.getInstance(KEY_AES);
cipher.init(Cipher.DECRYPT_MODE,skeySpec);
byte[]encrypted1=hex2byte(src);
byte[]original=cipher.doFinal(encrypted1);
StringoriginalString=newString(original);
returnoriginalString;
}
publicstaticbyte[]hex2byte(Stringstrhex){
if(strhex==null){
returnnull;
}
intl=strhex.length();
if(l%2==1){
returnnull;
}
byte[]b=newbyte[l/2];
for(inti=0;i!=l/2;i++){
b[i]=(byte)Integer.parseInt(strhex.substring(i*2,i*2+2),
16);
}
returnb;
}
publicstaticStringbyte2hex(byte[]b){
Stringhs="";
Stringstmp="";
for(intn=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;
}
}
returnhs.toUpperCase();
}
}
Base64加密:
[java] view plain copy print?
importorg.apache.commons.codec.binary.Base64;
/**
*Base64組件
*
*@authorwbw
*@version1.0
*@since1.0
*/
publicabstractclassBase64Util{
/**
*字符編碼
*/
publicfinalstaticStringENCODING="UTF-8";
/**
*Base64編碼
*
*@paramdata待編碼數據
*@returnString編碼數據
*@throwsException
*/
publicstaticStringencode(Stringdata)throwsException{
//執行編碼
byte[]b=Base64.encodeBase64(data.getBytes(ENCODING));
returnnewString(b,ENCODING);
}
/**
*Base64安全編碼<br>
*遵循RFC2045實現
*
*@paramdata
*待編碼數據
*@returnString編碼數據
*
*@throwsException
*/
publicstaticStringencodeSafe(Stringdata)throwsException{
//執行編碼
byte[]b=Base64.encodeBase64(data.getBytes(ENCODING),true);
returnnewString(b,ENCODING);
}
/**
*Base64解碼
*
*@paramdata待解碼數據
*@returnString解碼數據
*@throwsException
*/
publicstaticStringdecode(Stringdata)throwsException{
//執行解碼
byte[]b=Base64.decodeBase64(data.getBytes(ENCODING));
returnnewString(b,ENCODING);
}
}
DES加密:
[java] view plain copy print?
importjava.security.Key;
importjava.security.SecureRandom;
importjava.security.Security;
importjavax.crypto.Cipher;
importjavax.crypto.KeyGenerator;
importjavax.crypto.SecretKey;
importjavax.crypto.SecretKeyFactory;
importjavax.crypto.spec.DESKeySpec;
importorg.apache.commons.codec.binary.Base64;
importorg.bouncycastle.jce.provider.BouncyCastleProvider;
/**
*DES安全編碼組件
*
*@authorwbw
*@version1.0
*/
publicabstractclassDESUtil{
static{
Security.insertProviderAt(newBouncyCastleProvider(),1);
}
/**
*密鑰算法<br>
*Java6只支持56bit密鑰<br>
*BouncyCastle支持64bit密鑰
*/
publicstaticfinalStringKEY_ALGORITHM="DES";
/**
*加密/解密算法/工作模式/填充方式
*/
publicstaticfinalStringCIPHER_ALGORITHM="DES/ECB/PKCS5PADDING";
/**
*轉換密鑰
*
*@paramkey
*二進制密鑰
*@returnKey密鑰
*@throwsException
*/
privatestaticKeytoKey(byte[]key)throwsException{
//實例化DES密鑰材料
DESKeySpecdks=newDESKeySpec(key);
//實例化秘密密鑰工廠
SecretKeyFactorykeyFactory=SecretKeyFactory
.getInstance(KEY_ALGORITHM);
//生成秘密密鑰
SecretKeysecretKey=keyFactory.generateSecret(dks);
returnsecretKey;
}
/**
*解密
*
*@paramdata
*待解密數據
*@paramkey
*密鑰
*@returnbyte[]解密數據
*@throwsException
*/
publicstaticbyte[]decrypt(byte[]data,byte[]key)throwsException{
//還原密鑰
Keyk=toKey(key);
//實例化
Ciphercipher=Cipher.getInstance(CIPHER_ALGORITHM);
//初始化,設置為解密模式
cipher.init(Cipher.DECRYPT_MODE,k);
//執行操作
returncipher.doFinal(data);
}
/**
*加密
*
*@paramdata
*待加密數據
*@paramkey
*密鑰
*@returnbyte[]加密數據
*@throwsException
*/
publicstaticbyte[]encrypt(byte[]data,byte[]key)throwsException{
//還原密鑰
Keyk=toKey(key);
//實例化
Ciphercipher=Cipher.getInstance(CIPHER_ALGORITHM);
//初始化,設置為加密模式
cipher.init(Cipher.ENCRYPT_MODE,k);
//執行操作
returncipher.doFinal(data);
}
/**
*生成密鑰<br>
*Java6只支持56bit密鑰<br>
*BouncyCastle支持64bit密鑰<br>
*
*@returnbyte[]二進制密鑰
*@throwsException
*/
publicstaticbyte[]initKey()throwsException{
/*
*實例化密鑰生成器
*
*若要使用64bit密鑰注意替換將下述代碼中的KeyGenerator.getInstance(CIPHER_ALGORITHM);
*替換為KeyGenerator.getInstance(CIPHER_ALGORITHM,"BC");
*/
KeyGeneratorkg=KeyGenerator.getInstance(KEY_ALGORITHM);
/*
*初始化密鑰生成器若要使用64bit密鑰注意替換將下述代碼kg.init(56);替換為kg.init(64);
*/
kg.init(56,newSecureRandom());
//生成秘密密鑰
SecretKeysecretKey=kg.generateKey();
//獲得密鑰的二進制編碼形式
returnsecretKey.getEncoded();
}
publicstaticbyte[]initKey(Stringseed)throwsException{
KeyGeneratorkg=KeyGenerator.getInstance(KEY_ALGORITHM);
SecureRandomsecureRandom=newSecureRandom(newBase64().decode(seed));
kg.init(secureRandom);
SecretKeysecretKey=kg.generateKey();
returnsecretKey.getEncoded();
}
}
RSA加密:
[java] view plain copy print?
importjava.io.ByteArrayOutputStream;
importjava.security.Key;
importjava.security.KeyFactory;
importjava.security.KeyPair;
importjava.security.KeyPairGenerator;
importjava.security.PrivateKey;
importjava.security.PublicKey;
importjava.security.SecureRandom;
importjava.security.Security;
importjava.security.interfaces.RSAPrivateKey;
importjava.security.interfaces.RSAPublicKey;
importjava.security.spec.PKCS8EncodedKeySpec;
importjava.security.spec.X509EncodedKeySpec;
importjava.util.HashMap;
importjava.util.Map;
importjava.util.UUID;
importjavax.crypto.Cipher;
importorg.bouncycastle.jce.provider.BouncyCastleProvider;
importorg.bouncycastle.util.encoders.Base64;
/**
*RSA安全編碼組件
*
*@authorwbw
*@version1.0
*/
publicclassRSAUtil{
/**
*非對稱加密密鑰算法
*/
publicstaticfinalStringKEY_ALGORITHM_RSA="RSA";
/**
*公鑰
*/
privatestaticfinalStringRSA_PUBLIC_KEY="RSAPublicKey";
/**
*私鑰
*/
privatestaticfinalStringRSA_PRIVATE_KEY="RSAPrivateKey";
/**
*RSA密鑰長度
*默認1024位,
*密鑰長度必須是64的倍數,
*范圍在512至65536位之間。
*/
privatestaticfinalintKEY_SIZE=1024;
static{
Security.insertProviderAt(newBouncyCastleProvider(),1);
}
/**
*私鑰解密
*
*@paramdata
*待解密數據
*@paramkey
*私鑰
*@returnbyte[]解密數據
*@throwsException
*/
publicstaticbyte[]decryptByPrivateKey(byte[]data,byte[]key)
throwsException{
//取得私鑰
PKCS8EncodedKeySpecpkcs8KeySpec=newPKCS8EncodedKeySpec(key);
KeyFactorykeyFactory=KeyFactory.getInstance(KEY_ALGORITHM_RSA);
//生成私鑰
PrivateKeyprivateKey=keyFactory.generatePrivate(pkcs8KeySpec);
//對數據解密
Ciphercipher=Cipher.getInstance(keyFactory.getAlgorithm());
cipher.init(Cipher.DECRYPT_MODE,privateKey);
intblockSize=cipher.getBlockSize();
if(blockSize>0){
ByteArrayOutputStreambout=newByteArrayOutputStream(64);
intj=0;
while(data.length-j*blockSize>0){
bout.write(cipher.doFinal(data,j*blockSize,blockSize));
j++;
}
returnbout.toByteArray();
}
returncipher.doFinal(data);
}
/**
*公鑰解密
*
*@paramdata
*待解密數據
*@paramkey
*公鑰
*@returnbyte[]解密數據
*@throwsException
*/
publicstaticbyte[]decryptByPublicKey(byte[]data,byte[]key)
throwsException{
//取得公鑰
X509EncodedKeySpecx509KeySpec=newX509EncodedKeySpec(key);
KeyFactorykeyFactory=KeyFactory.getInstance(KEY_ALGORITHM_RSA);
//生成公鑰
PublicKeypublicKey=keyFactory.generatePublic(x509KeySpec);
//對數據解密
Ciphercipher=Cipher.getInstance(keyFactory.getAlgorithm());
cipher.init(Cipher.DECRYPT_MODE,publicKey);
returncipher.doFinal(data);
}
/**
*公鑰加密
*
*@paramdata
*待加密數據
*@paramkey
*公鑰
*@returnbyte[]加密數據
*@throwsException
*/
publicstaticbyte[]encryptByPublicKey(byte[]data,byte[]key)
throwsException{
//取得公鑰
X509EncodedKeySpecx509KeySpec=newX509EncodedKeySpec(key);
KeyFactorykeyFactory=KeyFactory.getInstance(KEY_ALGORITHM_RSA);
PublicKeypublicKey=keyFactory.generatePublic(x509KeySpec);
//對數據加密
Ciphercipher=Cipher.getInstance(keyFactory.getAlgorithm());
cipher.init(Cipher.ENCRYPT_MODE,publicKey);
intblockSize=cipher.getBlockSize();
if(blockSize>0){
intoutputSize=cipher.getOutputSize(data.length);
intleavedSize=data.length%blockSize;
intblocksSize=leavedSize!=0?data.length/blockSize+1
:data.length/blockSize;
byte[]raw=newbyte[outputSize*blocksSize];
inti=0,remainSize=0;
while((remainSize=data.length-i*blockSize)>0){
intinputLen=remainSize>blockSize?blockSize:remainSize;
cipher.doFinal(data,i*blockSize,inputLen,raw,i*outputSize);
i++;
}
returnraw;
}
returncipher.doFinal(data);
}
/**
*私鑰加密
*
*@paramdata
*待加密數據
*@paramkey
*私鑰
*@returnbyte[]加密數據
*@throwsException
*/
publicstaticbyte[]encryptByPrivateKey(byte[]data,byte[]key)
throwsException{
//取得私鑰
PKCS8EncodedKeySpecpkcs8KeySpec=newPKCS8EncodedKeySpec(key);
KeyFactorykeyFactory=KeyFactory.getInstance(KEY_ALGORITHM_RSA);
//生成私鑰
PrivateKeyprivateKey=keyFactory.generatePrivate(pkcs8KeySpec);
//對數據加密
Ciphercipher=Cipher.getInstance(keyFactory.getAlgorithm());
cipher.init(Cipher.ENCRYPT_MODE,privateKey);
intblockSize=cipher.getBlockSize();
if(blockSize>0){
intoutputSize=cipher.getOutputSize(data.length);
intleavedSize=data.length%blockSize;
intblocksSize=leavedSize!=0?data.length/blockSize+1
:data.length/blockSize;
byte[]raw=newbyte[outputSize*blocksSize];
inti=0,remainSize=0;
while((remainSize=data.length-i*blockSize)>0){
intinputLen=remainSize>blockSize?blockSize:remainSize;
cipher.doFinal(data,i*blockSize,inputLen,raw,i*outputSize);
i++;
}
returnraw;
}
returncipher.doFinal(data);
}
/**
*取得私鑰
*
*@paramkeyMap
*密鑰Map
*@returnkey私鑰
*@throwsException
*/
publicstaticKeygetPrivateKey(Map<String,Key>keyMap)
throwsException{
returnkeyMap.get(RSA_PRIVATE_KEY);
}
/**
*取得私鑰
*
*@paramkeyMap
*密鑰Map
*@returnbyte[]私鑰
*@throwsException
*/
publicstaticbyte[]getPrivateKeyByte(Map<String,Key>keyMap)
throwsException{
returnkeyMap.get(RSA_PRIVATE_KEY).getEncoded();
}
/**
*取得公鑰
*
*@paramkeyMap
*密鑰Map
*@returnkey公鑰
*@throwsException
*/
publicstaticKeygetPublicKey(Map<String,Key>keyMap)
throwsException{
returnkeyMap.get(RSA_PUBLIC_KEY);
}
/**
*取得公鑰
*
*@paramkeyMap
*密鑰Map
*@returnbyte[]公鑰
*@throwsException
*/
publicstaticbyte[]getPublicKeyByte(Map<String,Key>keyMap)
throwsException{
returnkeyMap.get(RSA_PUBLIC_KEY).getEncoded();
}
/**
*初始化密鑰
*@parambyte[]seed種子
*@returnMap密鑰Map
*@throwsException
*/
publicstaticMap<String,Key>initKey(byte[]seed)throwsException{
//實例化密鑰對生成器
KeyPairGeneratorkeyPairGen=KeyPairGenerator
.getInstance(KEY_ALGORITHM_RSA);
//初始化密鑰對生成器
keyPairGen.initialize(KEY_SIZE,newSecureRandom(seed));
//生成密鑰對
KeyPairkeyPair=keyPairGen.generateKeyPair();
//公鑰
RSAPublicKeypublicKey=(RSAPublicKey)keyPair.getPublic();
//私鑰
RSAPrivateKeyprivateKey=(RSAPrivateKey)keyPair.getPrivate();
//封裝密鑰
Map<String,Key>keyMap=newHashMap<String,Key>(2);
keyMap.put(RSA_PUBLIC_KEY,publicKey);
keyMap.put(RSA_PRIVATE_KEY,privateKey);
returnkeyMap;
}
/**
*初始化密鑰
*@paramseed種子
*@returnMap密鑰Map
*@throwsException
*/
publicstaticMap<String,Key>initKey(Stringseed)throwsException{
returninitKey(seed.getBytes());
}
/**
*初始化密鑰
*
*@returnMap密鑰Map
*@throwsException
*/
publicstaticMap<String,Key>initKey()throwsException{
returninitKey(UUID.randomUUID().toString().getBytes());
}
publicstaticPublicKeygetPublicRSAKey(Stringkey)throwsException{
X509EncodedKeySpecx509=newX509EncodedKeySpec(Base64.decode(key));
KeyFactorykf=KeyFactory.getInstance(KEY_ALGORITHM_RSA);
returnkf.generatePublic(x509);
}
publicstaticPrivateKeygetPrivateRSAKey(Stringkey)throwsException{
PKCS8EncodedKeySpecpkgs8=newPKCS8EncodedKeySpec(Base64.decode(key));
KeyFactorykf=KeyFactory.getInstance(KEY_ALGORITHM_RSA);
returnkf.generatePrivate(pkgs8);
}
}
https://www.cnblogs.com/jpfss/p/8567001.html
總結
以上是生活随笔為你收集整理的java 加密工具类(MD5、RSA、AES等加密方式)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 魏300和坦克300区别?
- 下一篇: 大同云冈石窟(大同旅游景点有哪些景点推荐