获取摘要、加密、解密

[color=red][b]生成SHA或MD5摘要[/b][/color]
	MessageDigest sha = MessageDigest.getInstance("SHA");//字符串参数可以为:"SHA"或"MD5"
sha.update("luoxun".getBytes());
byte[] digest = sha.digest();
StringBuilder sb = new StringBuilder();
for(int i= 0;i<digest.length;i++){
int v = digest[i]&0XFF;
if(v<16) sb.append("0");
sb.append(Integer.toString(v,16)).append(" ");
}
print(sb.toString().toUpperCase());

[b][color=red]AES加密解密文件demo[/color][/b]
	
//生成密钥
private static SecretKey generatorKey() throws NoSuchAlgorithmException {
KeyGenerator generator = KeyGenerator.getInstance("AES");
SecureRandom rand = new SecureRandom();
generator.init(rand);
SecretKey secretKey = generator.generateKey();
return secretKey;
}
private static void cipherFile(SecretKey secretKey,int mode,String inFile,String outFile)throws Exception{
Cipher cipher = Cipher.getInstance("AES");
cipher.init(mode, secretKey);

int blockSize = cipher.getBlockSize();
byte[] inbuff = new byte[blockSize];

String source = ClassLoader.getSystemResource(inFile).getFile();
String chiper = ClassLoader.getSystemResource(outFile).getFile();
FileInputStream in = new FileInputStream(source);
FileOutputStream out = new FileOutputStream(chiper);

while(true){
int inlen = in.read(inbuff);
System.out.println(inlen);
if(inlen == blockSize){
out.write(cipher.update(inbuff));
}else if(inlen > 0){
out.write(cipher.doFinal(inbuff,0,inlen));//如果在读取中出现字节数小于bolckSize 这样它会生成如下填充:inlen=1 xx 01;inlen=2 xx 02 02;inlen=3 xx 03 03 03
break;
}else{
out.write(cipher.doFinal());//如果读取的所有字节数刚好被blockSize整除执行cipher.doFinal()产生如下填充:blockSize个[0blocakSize]
break;
}
}
out.flush();
out.close();
in.close();
}

AES是一种对称密码,所以加密和解密的时候要用要同一个密钥。
		SecretKey secretKey = generatorKey();
//Cipher.ENCRYPT_MODE加密
cipherFile(secretKey,Cipher.ENCRYPT_MODE,"source.text","cipher.text");
//Cipher.DECRYPT_MODE解密
cipherFile(secretKey,Cipher.DECRYPT_MODE,"cipher.text","sourcecopy.text");

[color=red][b]密码流:CipherInputStream和CipherOutputStream他们提供了可以传入Cipher对象的构造函数,可方便的对流中的信息加密解密[/b][/color]

//下面为解决AES密钥的发布 解决方案,AES密钥为对称密钥,每次产生的密钥都需要在双方之间发送这显然是不安全的
KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA");
int keysize = 512;
SecureRandom rand = new SecureRandom();
generator.initialize(keysize, rand);
KeyPair keyPair = generator.generateKeyPair();
PrivateKey privateKey = keyPair.getPrivate();
PublicKey publicKey = keyPair.getPublic();

Key key = null;//这是一个AES的密钥
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.WRAP_MODE, publicKey);//用RSA公钥加密AES密钥
byte[] wrappedKey = cipher.wrap(key);

cipher.init(Cipher.UNWRAP_MODE, privateKey);//用RSA私钥解密AES密钥
cipher.unwrap(wrappedKey, "AES", Cipher.SECRET_KEY);


[color=red]一下是对加密解密的简单封装,可以当作工具类使用:[/color]
package Crypto;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.security.Key;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.SecureRandom;
import java.util.Arrays;

import javax.crypto.Cipher;
import javax.crypto.CipherOutputStream;
import javax.crypto.KeyGenerator;

public class Crypto {
private static final String AES = "AES";
private static final String RSA = "RSA";

public static Key genAndSaveKey( String filename )throws Exception{
Key key = Crypto.genKey();
Crypto.saveKey(filename, key);
return key;
}

public static Key genKey() throws NoSuchAlgorithmException{
KeyGenerator keygen = KeyGenerator.getInstance(AES);
SecureRandom random = new SecureRandom();
keygen.init(random);
return keygen.generateKey();
}

public static boolean saveKey( String filename , Key key )throws IOException{
File file = new File(filename);
if( file.exists() ){
ObjectOutputStream out = null;
try{
out = new ObjectOutputStream(new FileOutputStream(file));
out.writeObject(key);
out.flush();
return true;
}finally{
if( out != null ) out.close();
}
}
return false;
}

public static Key readKey( String filename )throws IOException, ClassNotFoundException{
File file = new File(filename);
if( file.exists() ){
ObjectInputStream out = null;
try{
out = new ObjectInputStream(new FileInputStream(file));
return (Key) out.readObject();
}finally{
if( out != null ) out.close();
}
}
return null;
}

public static byte[] encrypt( byte[] buf , Key key ) throws Exception{
return crypt(buf, key, Cipher.ENCRYPT_MODE);
}

public static byte[] decrypt( byte[] buf , Key key ) throws Exception{
return crypt(buf, key, Cipher.DECRYPT_MODE);
}

public static byte[] crypt0( byte[] buf , Key key , int mode) throws Exception{
Cipher cipher = Cipher.getInstance(AES);
cipher.init(mode, key);
int blockSize = cipher.getBlockSize();
int outSize = cipher.getOutputSize(blockSize);

byte[] inbytes = new byte[blockSize];
byte[] outbytes = new byte[outSize];

ByteArrayInputStream inStream = new ByteArrayInputStream(buf);
ByteArrayOutputStream outStream = new ByteArrayOutputStream();

int inLength = 0;
while( (inLength = inStream.read(inbytes)) == inbytes.length ){
int outLength = cipher.update( inbytes , 0 , inbytes.length , outbytes );
outStream.write( outbytes , 0 , outLength );
}

if( inLength > 0 ){
outbytes = cipher.doFinal(inbytes, 0, inLength);
}else{
outbytes = cipher.doFinal();
}
outStream.write(outbytes);

return outStream.toByteArray();
}

public static byte[] crypt( byte[] buf , Key key , int mode) throws Exception{
Cipher cipher = Cipher.getInstance(AES);
cipher.init(mode, key);
CipherOutputStream cipoStream = null;
ByteArrayOutputStream buffStream = new ByteArrayOutputStream();
try {
cipoStream = new CipherOutputStream(buffStream, cipher);
cipoStream.write(buf);
}finally{
if( cipoStream != null ) cipoStream.close();
}
return buffStream.toByteArray();
}

public static KeyPair genKeyPair() throws NoSuchAlgorithmException{
KeyPairGenerator genkey = KeyPairGenerator.getInstance(RSA);
SecureRandom random = new SecureRandom();
genkey.initialize(512, random);
return genkey.generateKeyPair();
}

public static byte[] encryptKey(Key key , PublicKey publicKey) throws Exception{
Cipher cipher = Cipher.getInstance(RSA);
cipher.init(Cipher.WRAP_MODE, publicKey);
return cipher.wrap(key);
}

public static Key decryptKey(byte[] wrappedKey, PrivateKey privateKey) throws Exception{
Cipher cipher = Cipher.getInstance(RSA);
cipher.init(Cipher.UNWRAP_MODE, privateKey);
return cipher.unwrap(wrappedKey, AES, Cipher.SECRET_KEY);
}

public static void main(String[] args) throws Exception {
String filename = ClassLoader.getSystemClassLoader().getResource("resource/key").getFile();
Key key = Crypto.readKey(filename);

KeyPair keyPair = genKeyPair();
PublicKey publicKey = keyPair.getPublic();
PrivateKey privateKey = keyPair.getPrivate();

byte[] wrappedKey = encryptKey(key, publicKey);
key = decryptKey(wrappedKey, privateKey);

byte[] bytes = encrypt("luoxun".getBytes(), key);
System.out.println(Arrays.toString(bytes));
byte[] decode = decrypt(bytes, key);
System.out.println(new String(decode));

}

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值