加密解密,密钥对象保存方式

以RSA为例

http://bbs.csdn.net/topics/290038859

public class RSATest {
  public static final int PRIVATE = 0;
  public static final int PUBLIC = 1;
 
  public static final String ALGORITHM = "RSA/ECB/OAEPPadding";
  private class FixedSecureRandom
      extends SecureRandom {
    byte[] seed = {
        (byte) 0xaa, (byte) 0xfd, (byte) 0x12, (byte) 0xf6, (byte) 0x59,
        (byte) 0xca, (byte) 0xe6, (byte) 0x34, (byte) 0x89, (byte) 0xb4,
        (byte) 0x79, (byte) 0xe5, (byte) 0x07, (byte) 0x6d, (byte) 0xde,
        (byte) 0xc2, (byte) 0xf0, (byte) 0x6c, (byte) 0xb5, (byte) 0x8f
    };
 
    public void nextBytes(
        byte[] bytes) {
      int offset = 0;
 
      while ( (offset + seed.length) < bytes.length) {
        System.arraycopy(seed, 0, bytes, offset, seed.length);
        offset += seed.length;
      }
 
      System.arraycopy(seed, 0, bytes, offset, bytes.length - offset);
    }
  }
 
  public RSATest() {
  }
 
  public void testRSA() {
    try {
      KeyPairGenerator kpg = null;
      kpg = KeyPairGenerator.getInstance("RSA", "BC");
      kpg.initialize(1024, new SecureRandom());
      KeyPair kp = kpg.generateKeyPair();
      PrivateKey priKey = kp.getPrivate();
      PublicKey pubKey = kp.getPublic();
      System.out.println("priKey format: " + priKey.getFormat());
      System.out.println("priKey algorithm: " + priKey.getAlgorithm());
 
      //以对象方式保存私钥
      ObjectOutputStream keyFile = new ObjectOutputStream(new FileOutputStream("私钥.rsa"));
      keyFile.writeObject(priKey);
      keyFile.close();
      //以对象方式保存公钥
      keyFile = new ObjectOutputStream(new FileOutputStream("公钥.rsa"));
      keyFile.writeObject(pubKey);
      keyFile.close();
 
      //以普通文件格式保存私钥
      FileOutputStream keyFile2 =new FileOutputStream("私钥.dat");
      keyFile2.write(priKey.getEncoded());
      keyFile2.close();
      //从普通文件格式读取私钥
      PrivateKey priKeyNew=(PrivateKey)getKeyFromFile("私钥.dat",PRIVATE);
      System.out.println("read priKey from file is "+priKeyNew.equals(priKey));
 
      Cipher cipher = Cipher.getInstance("RSA", "BC");
      System.out.println("Cipher provider: " + cipher.getProvider());
      System.out.println("Cipher algorithm: " + cipher.getAlgorithm());
 
      //公钥加密
      cipher.init(Cipher.ENCRYPT_MODE, pubKey, new FixedSecureRandom());
      System.out.println("Cipher BlockSize: " +cipher.getBlockSize());
      byte[] out = cipher.doFinal( "我ok".getBytes());
      System.out.println(out.length + ":" + new String(out));
      //私钥解密
      cipher.init(Cipher.DECRYPT_MODE, priKey);
      out = cipher.doFinal(out);
      System.out.println(new String(out));
 
      //私钥加密
      cipher.init(Cipher.ENCRYPT_MODE, priKey, new FixedSecureRandom());
      out = cipher.doFinal( "我ok".getBytes());
      System.out.println(out.length + ":" + new String(out));
      //公钥解密
      cipher.init(Cipher.DECRYPT_MODE, pubKey);
      out = cipher.doFinal(out);
      System.out.println(new String(out));
 
      //加密长字符串
      byte[] longStr=new byte[1024];
      for (int i=0;i<longStr.length;i++){
        longStr[i]='a';
      }
      System.out.println("原始longStr:"+new String(longStr));
      byte[] longStr2=crypt(cipher,priKey,longStr,Cipher.ENCRYPT_MODE);
//      System.out.println("加密longStr:"+new String(longStr2));
      byte[] longStr3=crypt(cipher,pubKey,longStr2,Cipher.DECRYPT_MODE);
      System.out.println("解密longStr:"+new String(longStr3));
 
    }
    catch (Exception e) {
      e.printStackTrace();
    }
  }
 
  private Key getKeyFromFile(String filename, int type) throws FileNotFoundException {
      FileInputStream fis = null;
      fis = new FileInputStream(filename);
      ByteArrayOutputStream baos = new ByteArrayOutputStream();
      int b;
      try {
          while ((b = fis.read()) != -1) {
              baos.write(b);
          }
      } catch (IOException e) {
          e.printStackTrace();
      }
      byte[] keydata = baos.toByteArray();
 
      Key key = null;
      try {
          KeyFactory kf = KeyFactory.getInstance("RSA", "BC");
          switch (type) {
              case PRIVATE:
                  PKCS8EncodedKeySpec encodedPrivateKey = new PKCS8EncodedKeySpec(keydata);
                  key = kf.generatePrivate(encodedPrivateKey);
                  return key;
              case PUBLIC:
                  X509EncodedKeySpec encodedPublicKey = new X509EncodedKeySpec(keydata);
                  key = kf.generatePublic(encodedPublicKey);
                  return key;
          }
      } catch (NoSuchAlgorithmException e) {
          e.printStackTrace();
      } catch (NoSuchProviderException e) {
          e.printStackTrace();
      } catch (InvalidKeySpecException e) {
          e.printStackTrace();
      }
 
      return key;
  }
 
  private byte[] crypt(Cipher cipher, Key key, byte[] text, int type) {
      ByteArrayOutputStream out = null;
      try {
          cipher.init(type, key);
          int bzise = cipher.getBlockSize();
          out = new ByteArrayOutputStream();
          int s = cipher.getBlockSize();
          int r = 0;
          for (int t = 0; t < text.length; t += s) {
              if (text.length - t <= s) {
                  r = text.length - t;
              } else {
                  r = s;
              }
              out.write(cipher.doFinal(text, t, r));
          }
          out.flush();
          out.close();
      } catch (InvalidKeyException e) {
          e.printStackTrace();
      } catch (IOException e) {
          e.printStackTrace();
      } catch (IllegalStateException e) {
          e.printStackTrace();
      } catch (IllegalBlockSizeException e) {
          e.printStackTrace();
      } catch (BadPaddingException e) {
          e.printStackTrace();
      }
      return out.toByteArray();
  }
 
  public static void main(String[] args) {
    Security.addProvider(new BouncyCastleProvider());
    RSATest d = new RSATest();
    d.testRSA();
  }
 
}

 

posted @ 2013-09-16 01:13  fenglie  阅读(747)  评论(0)    收藏  举报
版权所有,转载声明