Java安全(JCA/JSSE):非对称加密和数字摘要

Java安全(JCA/JSSE):非对称加密和数字摘要_第1张图片

读一个流这个buffer到底设置多大?你根本就不会知道

所以用下面的方法

privatestaticvoid copyStream(InputStream is,OutputStream os)throws Exception{

           byte[] buff=newbyte[1024];

           inttotal=0;

           int len=is.read(buff);

           while(len!=-1){

              os.write(buff, 0, len);

              len=is.read(buff);

    }

 

或者

 

byte[] src=newbyte[fisDat.available()];//对于文件流来说就是其长度,而对于像网络流就不是了

       int len=fisDat.read(src);

       int total=0;

       while(total<src.length){

           total+=len;

           len=fisDat.read(src, total, src.length-total);

       }

 

 

 

公钥加密私钥解密

package com.xiongshiyan.security;

 

importjava.io.ByteArrayOutputStream;

import java.io.FileInputStream;

import java.io.FileOutputStream;

import java.io.InputStream;

import java.io.ObjectInputStream;

import java.io.ObjectOutputStream;

import java.io.OutputStream;

import java.security.Key;

import java.security.KeyPair;

import java.security.KeyPairGenerator;

importjava.security.NoSuchAlgorithmException;

import java.security.PrivateKey;

import java.security.PublicKey;

 

import javax.crypto.Cipher;

importjavax.crypto.CipherInputStream;

import javax.crypto.CipherOutputStream;

importjavax.crypto.NoSuchPaddingException;

 

publicclass PublicSecretTest {

 

    /**

     * @param args

     * @throws Exception

     */

    publicstaticvoid main(String[] args)throws Exception {

       //TODO Auto-generatedmethod stub

 

       PublicSecretTest.publicEnrypt();

       PublicSecretTest.privateDerypt2();

    }

    privatestaticvoid publicEnrypt()throws Exception{

           Cipher cipher = Cipher.getInstance("RSA");

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

           KeyPair keyPair = keyPairGenerator.generateKeyPair();

           PublicKey publicKey=keyPair.getPublic();

           PrivateKey privateKey=keyPair.getPrivate();

           cipher.init(Cipher.ENCRYPT_MODE, publicKey);//使用公钥加密

           byte[] secResult = cipher.doFinal("熊诗言".getBytes());

           System.out.println(new String(secResult));

           //把加密后的数据和key一起给别人 别人拿到了之后进行恢复

           ObjectOutputStream oosKey=new ObjectOutputStream(new FileOutputStream("key2.key"));

           oosKey.writeObject(privateKey);//写入加密key

           oosKey.close();

          

           FileOutputStream oosDat=new FileOutputStream("dat2.dat");

           oosDat.write(secResult);//写入加密dat

           oosDat.close();

          

    }

    privatestaticvoidprivateDerypt() throws Exception{

       ObjectInputStream oisKey=new ObjectInputStream(new FileInputStream("key2.key"));

       Key key=(Key)oisKey.readObject();

       oisKey.close();

      

       Cipher cipher = Cipher.getInstance("RSA");

       cipher.init(Cipher.DECRYPT_MODE, key);

 

       FileInputStream fisDat=new FileInputStream("dat2.dat");

       /* ByteArrayOutputStream baos=new ByteArrayOutputStream();

           SecretKeyTest.copyStream(fisDat,baos);

           byte[] deSecResult=cipher.doFinal(baos.toByteArray());*/

          

       byte[] src=newbyte[fisDat.available()];//对于文件流来说就是其长度,而对于像网络流就不是了

       int len=fisDat.read(src);

       int total=0;

       while(total<src.length){

           total+=len;

           len=fisDat.read(src, total, src.length-total);

       }

      

       byte[] deSecResult=cipher.doFinal(src);

       System.out.println(new String(deSecResult));

      

    }

   

   

   

    privatestaticvoid privateDerypt2()throws Exception{

       ObjectInputStream oisKey=new ObjectInputStream(new FileInputStream("key2.key"));

       Key key=(Key)oisKey.readObject();

       oisKey.close();

      

       Cipher cipher = Cipher.getInstance("RSA");

       cipher.init(Cipher.DECRYPT_MODE, key);

 

       FileInputStream fisDat=new FileInputStream("dat2.dat");

       /* ByteArrayOutputStream baos=new ByteArrayOutputStream();

           SecretKeyTest.copyStream(fisDat,baos);

           byte[] deSecResult=cipher.doFinal(baos.toByteArray());*/

          

       /*byte[]src=newbyte[fisDat.available()];//对于文件流来说就是其长度,而对于像网络流就不是了

       int len=fisDat.read(src);

       int total=0;

       while(total<src.length){

           total+=len;

           len=fisDat.read(src, total,src.length-total);

       }

      

       byte[] deSecResult=cipher.doFinal(src);

       System.out.println(new String(deSecResult,"utf-8"));*/

      

      

      

       //使用CipherInputStream,在读的过程中解密

       /*CipherInputStreamcipherInputStream=new CipherInputStream(fisDat,cipher);

       ByteArrayOutputStream baos=new ByteArrayOutputStream();

       PublicSecretTest.copyStream(cipherInputStream,baos);

       baos.close();

       cipherInputStream.close();

       System.out.println(new String(baos.toByteArray(),"utf-8"));*/

      

       //使用CipherOutputStream//在写的时候解密

       CipherOutputStream cipherOutputStream=new CipherOutputStream(System.out,cipher);

       PublicSecretTest.copyStream(fisDat,cipherOutputStream);

       cipherOutputStream.close();

       fisDat.close();

      

      

    }

    privatestaticvoid copyStream(InputStream is,OutputStream os) throws Exception{

           byte[] buff=newbyte[1024];

           inttotal=0;

           int len=is.read(buff);

           while(len!=-1){

              os.write(buff, 0, len);

              len=is.read(buff);

    }

}

}

Java安全(JCA/JSSE):非对称加密和数字摘要_第2张图片

数字摘要:就是数据的指纹,任何两个数据的指纹都不一样,并且都是128位的

一般下载的文件使用一个工具算出它的md5码与给你的比较,如果一样表示没有被破坏

数据校验

数据库密码

public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
//数据库中存储md5,你给密码,算出md5,如果一样就能验证成功,防止内鬼
//md5();
mac();
}
private static void md5() throws NoSuchAlgorithmException {
MessageDigest digest = MessageDigest.getInstance("md5");
digest.update("xiongshiyan".getBytes());//这个得update就好使了
byte[] result=digest.digest();
System.out.println(result.length);//16个字节
System.out.println(new String(result));
System.out.println(toHex(result));
}
private static String toHex(byte[] buff){
StringBuilder stringBuilder = new StringBuilder();
for(int i=0;i<buff.length;i++){
int hi=(buff[i]>>4)&0x0f;
int lo=buff[i]&0x0f;
stringBuilder.append(hi>9?(char)((hi-10)+'A'):(char)(hi+'0'));
stringBuilder.append(lo>9?(char)((lo-10)+'A'):(char)(lo+'0'));
}
return stringBuilder.toString();
}


//这种算法使用原始数据和密码一起进行摘要,可以防止内容和摘要一同被篡改
private static void mac() throws Exception{
PBEKeySpec keySpec = new PBEKeySpec("abcdef".toCharArray());
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("PBEWithMD5AndDES");
SecretKey key = keyFactory.generateSecret(keySpec);

Mac mac = Mac.getInstance("HmacMD5");
mac.init(key);
byte[] src = "data".getBytes();
byte[] dest = mac.doFinal(src);
System.out.println(dest.length);
System.out.println(toHex(dest));
}







你可能感兴趣的:(Java安全(JCA/JSSE):非对称加密和数字摘要)