日期:2014-05-20  浏览次数:20711 次

RSA的密文
请问Java中RSA加密时是怎么个过程?
我现在的问题是同样的密钥对,同样的明文,每次运行生成的密文都不一样,但是能解回正确的明文。

为什么每次加密后的密文不一样呢?


code:public class RSATest {

  public static void main(String[] args) {
  try {
  RSATest encrypt = new RSATest();

  RSAPublicKeySpec spec = new RSAPublicKeySpec(
  new BigInteger(
  "4cb6fbcec044da02069ebb78bc6b5cb29e395ac4116c37fd60eb7b05f1520ab232f2b999c3456c430dbd55bba4b064631a72239066f81fd430eb0ae603d2dd871558b473560d6186dfda6ff566c15b523a12a4b96fba39abc39c6fecbdf68a0da9f98ec3d5ece26f60d464729e9d4aa7ec579f4b965083712da9219ab449a4ed",
  16), new BigInteger("10001", 16));
  RSAPrivateKeySpec privateSpec = new RSAPrivateKeySpec(
  new BigInteger(
  "4cb6fbcec044da02069ebb78bc6b5cb29e395ac4116c37fd60eb7b05f1520ab232f2b999c3456c430dbd55bba4b064631a72239066f81fd430eb0ae603d2dd871558b473560d6186dfda6ff566c15b523a12a4b96fba39abc39c6fecbdf68a0da9f98ec3d5ece26f60d464729e9d4aa7ec579f4b965083712da9219ab449a4ed",
  16),
  new BigInteger(
  "17cbd6f63e2bdd582d87856da13cc8675baf3cd97ef20bb81c1d4f6efb79507a1055bc7ed6d4ad0d6bb0a46c6d5c8df733d7ddf2480e85890397952cde58c5806f89564049cecdbcf45ddf043cfd6fd4b8dea7f7b8d8f9ccbe1e0bc80b2d4141e7c974a3c5f2e3701b2b2159ce1c9ac513e27eb63b470f449f4d6cb391de3701",
  16));
  RSAPublicKey publicKey = null;
  RSAPrivateKey privateKey = null;
  try {
  publicKey = (RSAPublicKey) KeyFactory.getInstance("RSA").generatePublic(spec);
  privateKey = (RSAPrivateKey) KeyFactory.getInstance("RSA").generatePrivate(privateSpec);
  } catch (InvalidKeySpecException e) {
  e.printStackTrace();
  } catch (NoSuchAlgorithmException e) {
  e.printStackTrace();
  }
  System.out.println(publicKey);
  System.out.println(privateKey);
  // ////

  String str = "0.6008666527123822";
  System.out.println("String will be encrypted: " + str);
  byte[] e = encrypt.encrypt(publicKey, str.getBytes());
  String tmp1 = encrypt.bytesToString(e);
  System.out
  .println("encrypted String's bytes, use bytesToString() method convert bytes to string: " + tmp1);
  String[] strArr = tmp1.split(" ");
  int len = strArr.length;
  byte[] clone = new byte[len];
  for (int i = 0; i < len; i++) {
  clone[i] = Byte.parseByte(strArr[i]);
  }
  System.out.println("convert to String, then back to bytes again: " + encrypt.bytesToString(clone));
  byte[] d = encrypt.decrypt(privateKey, e);
  System.out.println("decrypted String's bytes, use bytesToString() method convert bytes to string:"
  + encrypt.bytesToString(d));
  System.out.println("construct a string by decrypted string's bytes: " + new String(d));
  } catch (Exception e) {
  e.printStackTrace();
  }
  }

  private String bytesToString(byte[] encrytpByte) {
  String result = "";
  for (Byte bytes : encrytpByte) {
  result += bytes.toString() + " ";