科技行者

行者学院 转型私董会 科技行者专题报道 网红大战科技行者

知识库

知识库 安全导航

至顶网软件频道Java非对称加密源代码(RSA)

Java非对称加密源代码(RSA)

  • 扫一扫
    分享文章到微信

  • 扫一扫
    关注官方公众号
    至顶头条

鉴于rsa加密的重要性和相关源代码的匮乏,整理出Java非对称加密源代码(RSA)。

来源:ccid 2008年2月15日

关键字:

  • 评论
  • 分享微博
  • 分享邮件

在本页阅读全文(共2页)

//这里面doUpdate方法不可用,查看源代码后发现每次doUpdate后并没有什么实际动作除了把byte[]放到ByteArrayOutputStream中,而最后doFinal的时候才将所有的byte[]进行加密,可是到了此时加密块大小很可能已经超出了OutputSize所以只好用dofinal方法。

  i++;

  }

  return raw;

  } catch (Exception e) {

  throw new EncryptException(e.getMessage());

  }

  }

  /**

  * 解密

  * @param key 解密的密钥

  * @param raw 已经加密的数据

  * @return 解密后的明文

  * @throws EncryptException

  */

  public static byte[] decrypt(Key key, byte[] raw) throws EncryptException {

  try {

  Cipher cipher = Cipher.getInstance("RSA", new org.bouncycastle.jce.provider.BouncyCastleProvider());

  cipher.init(cipher.DECRYPT_MODE, key);

  int blockSize = cipher.getBlockSize();

  ByteArrayOutputStream bout = new ByteArrayOutputStream(64);

  int j = 0;

  while (raw.length - j * blockSize > 0) {

  bout.write(cipher.doFinal(raw, j * blockSize, blockSize));

  j++;

  }

  return bout.toByteArray();

  } catch (Exception e) {

  throw new EncryptException(e.getMessage());

  }

  }

  /**

  *

  * @param args

  * @throws Exception

  */

  public static void main(String[] args) throws Exception {

  File file = new File("test.html");

  FileInputStream in = new FileInputStream(file);

  ByteArrayOutputStream bout = new ByteArrayOutputStream();

  byte[] tmpbuf = new byte[1024];

  int count = 0;

  while ((count = in.read(tmpbuf)) != -1) {

  bout.write(tmpbuf, 0, count);

  tmpbuf = new byte[1024];

  }

  in.close();

  byte[] orgData = bout.toByteArray();

  KeyPair keyPair = RSAUtil.generateKeyPair();

  RSAPublicKey pubKey = (RSAPublicKey) keyPair.getPublic();

  RSAPrivateKey priKey = (RSAPrivateKey) keyPair.getPrivate();

  byte[] pubModBytes = pubKey.getModulus().toByteArray();

  byte[] pubPubExpBytes = pubKey.getPublicExponent().toByteArray();

  byte[] priModBytes = priKey.getModulus().toByteArray();

  byte[] priPriExpBytes = priKey.getPrivateExponent().toByteArray();

  RSAPublicKey recoveryPubKey = RSAUtil.generateRSAPublicKey(pubModBytes,pubPubExpBytes);

  RSAPrivateKey recoveryPriKey = RSAUtil.generateRSAPrivateKey(priModBytes,priPriExpBytes);

  byte[] raw = RSAUtil.encrypt(priKey, orgData);

  file = new File("encrypt_result.dat");

  OutputStream out = new FileOutputStream(file);

  out.write(raw);

  out.close();

  byte[] data = RSAUtil.decrypt(recoveryPubKey, raw);

  file = new File("decrypt_result.html");

  out = new FileOutputStream(file);

  out.write(data);

  out.flush();

  out.close();

  }

  }

  加密可以用公钥,解密用私钥;或者加密用私钥。通常非对称加密是非常消耗资源的,因此可以对大数据用对称加密如:des(具体代码可以看我以前发的贴子),而对其对称密钥进行非对称加密,这样既保证了数据的安全,还能保证效率。
    • 评论
    • 分享微博
    • 分享邮件
    邮件订阅

    如果您非常迫切的想了解IT领域最新产品与技术信息,那么订阅至顶网技术邮件将是您的最佳途径之一。

    重磅专题
    往期文章
    最新文章