AES演算法和RSA演算法的JAVA實現

來源:互聯網
上載者:User

   沒什麼好說的,一切盡在代碼中。

  import java.io.*;
import java.security.*;

import javax.crypto.*;

/**
 * AES演算法產生密鑰和對檔案加解密的實現。
 * @author Li Xiaofeng
 * AES--DES演算法的後續版本,由於DES演算法可以通過窮舉法破譯,因此不推薦使用。
 */
public class AESImpl {
 //產生AES密鑰
 public void createKey() {
  try{
   KeyGenerator keygen = KeyGenerator.getInstance("AES");
   SecureRandom random = new SecureRandom();
   keygen.init(random);
   SecretKey key = keygen.generateKey();
   ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("aesKey.txt"));
   out.writeObject(key);
   out.close();
  }catch (NoSuchAlgorithmException e) {
   e.printStackTrace();
  }catch (IOException e) {
   e.printStackTrace();
  }
 }
 
 public void run(String code){
  int mode = Cipher.ENCRYPT_MODE;
  String inputFileName = "encode.txt";//要加密的檔案名稱
  String outputFileName = "aesDecode.txt";//加密後的檔案名稱
  if("DECODE".equals(code)){
   mode = Cipher.DECRYPT_MODE;
   inputFileName = "aesDecode.txt";//要解密的檔案名稱
   outputFileName = "encode.txt";//解密後的檔案名稱
  }
  try{
   //讀入AES密鑰檔案
   ObjectInputStream keyin = new ObjectInputStream(new FileInputStream("aesKey.txt"));
   Key key = (Key)keyin.readObject();
   keyin.close();
   
   InputStream in = new FileInputStream(inputFileName);
   OutputStream out = new FileOutputStream(outputFileName);
   Cipher cipher = Cipher.getInstance("AES");
   cipher.init(mode, key);
   
   //加解密
   crypt(in,out,cipher);
   in.close();
   out.close();
  }catch (Exception e) {
   e.printStackTrace();
  }
 }

 public static void crypt(InputStream in, OutputStream out, Cipher cipher) throws IOException, ShortBufferException, GeneralSecurityException {
  int blockSize = cipher.getBlockSize();
  int outputSize = cipher.getOutputSize(blockSize);
  byte[] inBytes = new byte[blockSize];
  byte[] outBytes = new byte[outputSize];
  
  int inLength = 0;
  boolean more = true;
  
  while(more){
   inLength = in.read(inBytes);
   if(inLength == blockSize){
    int outLength = cipher.update(inBytes, 0,blockSize,outBytes);
    out.write(outBytes,0,outLength);
   }
   else more = false;
  }
  if(inLength > 0){
   outBytes = cipher.doFinal(inBytes,0,inLength);
  }
  else{
   outBytes = cipher.doFinal();
  }
  out.write(outBytes);
 }
 
 public static void main(String[] args){
  AESImpl _aes = new AESImpl();
  //_aes.createKey();
  _aes.run("DECODE");
 }

}

 

import java.io.DataInputStream;
import java.io.DataOutputStream;
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;
import java.security.SecureRandom;

import javax.crypto.Cipher;

/**
 * 1、RSA演算法產生密鑰對。
 * 2、用產生的公用密鑰對AES密鑰加密,和用AES密鑰加密的內容放到一個檔案中。
 * 3、用產生的私人密鑰對檔案中的AES密鑰解密,並用解密的AES密鑰解密檔案的內容。
 * @author Li Xiaofeng
 *
 */
public class RSAImpl {
 private static final int KEYSIZE = 512;
 public void createKey(){
  try{
   KeyPairGenerator pairgen = KeyPairGenerator.getInstance("RSA");
   SecureRandom random = new SecureRandom();
   pairgen.initialize(KEYSIZE,random);
   KeyPair keypair = pairgen.generateKeyPair();
   //產生公用密鑰檔案
   ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("publicKey.txt"));
   out.writeObject(keypair.getPublic());
   out.close();
   //產生私人密鑰檔案
   out = new ObjectOutputStream(new FileOutputStream("privateKey.txt"));
   out.writeObject(keypair.getPrivate());
   out.close();
  }catch (Exception e) {
   e.printStackTrace();
  }
 }
 
 public void encode(){
  try{
   //讀進公用密鑰,用來加密AES密鑰
   ObjectInputStream in = new ObjectInputStream(new FileInputStream("publicKey.txt"));
   Key publicKey = (Key)in.readObject();
   in.close();
   
   //讀入AES密鑰
   in = new ObjectInputStream(new FileInputStream("aesKey.txt"));
   Key key = (Key)in.readObject();
   in.close();
   
   //加密AES密鑰
   Cipher cipher = Cipher.getInstance("RSA");
   cipher.init(Cipher.WRAP_MODE,publicKey);
   byte[] wrappedKey = cipher.wrap(key);
   //加密後的AES寫入檔案中
   DataOutputStream out = new DataOutputStream(new FileOutputStream("rasDecode.txt"));
   out.writeInt(wrappedKey.length);
   out.write(wrappedKey);
   
   //讀入要加密的檔案
   InputStream input = new FileInputStream("encode.txt");
   cipher = Cipher.getInstance("AES");
   cipher.init(Cipher.ENCRYPT_MODE, key);
   //用AES密鑰加密要加密的檔案
   AESImpl.crypt(input, out, cipher);
   input.close();
   out.close();
  }catch (Exception e) {
   e.printStackTrace();
  }
 }
 
 public void decode(){
  try{
   //讀入要解密的檔案,其中包括用RAS演算法加密AES的密鑰內容
   DataInputStream in = new DataInputStream(new FileInputStream("rasDecode.txt"));
   int length = in.readInt();
   byte[] wrappedKey = new byte[length];
   in.read(wrappedKey,0,length);
   
   //讀入RSA的私人密鑰檔案
   ObjectInputStream keyIn = new ObjectInputStream(new FileInputStream("privateKey.txt"));
   Key privateKey = (Key)keyIn.readObject();
   keyIn.close();
   
   //用RSA私人密鑰解密加密的AES密鑰
   Cipher cipher = Cipher.getInstance("RSA");
   cipher.init(Cipher.UNWRAP_MODE, privateKey);
   Key key = cipher.unwrap(wrappedKey, "AES", Cipher.SECRET_KEY);
   
   OutputStream out = new FileOutputStream("encode.txt");
   cipher = Cipher.getInstance("AES");
   cipher.init(Cipher.DECRYPT_MODE, key);
   //用解密的AES密鑰解密加密的檔案
   AESImpl.crypt(in, out, cipher);
   in.close();
   out.close();
  }catch (Exception e) {
   e.printStackTrace();
  }
 }
 
 public static void main(String[] args){
  RSAImpl _rsa = new RSAImpl();
  //_rsa.createKey();
  //_rsa.encode();
  _rsa.decode();
 }

}

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.