예제 #1
0
파일: RSAUtils.java 프로젝트: whg333/iTool
 public static void printPrivateKeyInfo(PrivateKey privateKey) {
   RSAPrivateKey rsaPrivateKey = (RSAPrivateKey) privateKey;
   System.out.println("----------RSAPrivateKey ----------");
   System.out.println("Modulus.length=" + rsaPrivateKey.getModulus().bitLength());
   System.out.println("Modulus=" + rsaPrivateKey.getModulus().toString());
   System.out.println("PrivateExponent.length=" + rsaPrivateKey.getPrivateExponent().bitLength());
   System.out.println("PrivatecExponent=" + rsaPrivateKey.getPrivateExponent().toString());
 }
예제 #2
0
 /**
  * 这个方法用于生成密钥,如果已经有密钥了就不需要在调用方法生成了
  *
  * @return
  * @throws Exception
  */
 public static Map<String, String> initKey() throws Exception {
   KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance(KEY_ALGORITHM);
   keyPairGen.initialize(KEY_SIZE);
   KeyPair keyPair = keyPairGen.generateKeyPair();
   RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
   RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
   Map<String, String> keyMap = new HashMap<String, String>();
   keyMap.put(PRIVATE_KEY, Base64.encodeBase64String(privateKey.getEncoded()));
   keyMap.put(PUBLIC_KEY, Base64.encodeBase64String(publicKey.getEncoded()));
   return keyMap;
 }
예제 #3
0
 protected <T extends KeySpec> T engineGetKeySpec(Key key, Class<T> keySpec)
     throws InvalidKeySpecException {
   try {
     // convert key to one of our keys
     // this also verifies that the key is a valid RSA key and ensures
     // that the encoding is X.509/PKCS#8 for public/private keys
     key = engineTranslateKey(key);
   } catch (InvalidKeyException e) {
     throw new InvalidKeySpecException(e);
   }
   if (key instanceof RSAPublicKey) {
     RSAPublicKey rsaKey = (RSAPublicKey) key;
     if (rsaPublicKeySpecClass.isAssignableFrom(keySpec)) {
       return keySpec.cast(new RSAPublicKeySpec(rsaKey.getModulus(), rsaKey.getPublicExponent()));
     } else if (x509KeySpecClass.isAssignableFrom(keySpec)) {
       return keySpec.cast(new X509EncodedKeySpec(key.getEncoded()));
     } else {
       throw new InvalidKeySpecException(
           "KeySpec must be RSAPublicKeySpec or " + "X509EncodedKeySpec for RSA public keys");
     }
   } else if (key instanceof RSAPrivateKey) {
     if (pkcs8KeySpecClass.isAssignableFrom(keySpec)) {
       return keySpec.cast(new PKCS8EncodedKeySpec(key.getEncoded()));
     } else if (rsaPrivateCrtKeySpecClass.isAssignableFrom(keySpec)) {
       if (key instanceof RSAPrivateCrtKey) {
         RSAPrivateCrtKey crtKey = (RSAPrivateCrtKey) key;
         return keySpec.cast(
             new RSAPrivateCrtKeySpec(
                 crtKey.getModulus(),
                 crtKey.getPublicExponent(),
                 crtKey.getPrivateExponent(),
                 crtKey.getPrimeP(),
                 crtKey.getPrimeQ(),
                 crtKey.getPrimeExponentP(),
                 crtKey.getPrimeExponentQ(),
                 crtKey.getCrtCoefficient()));
       } else {
         throw new InvalidKeySpecException("RSAPrivateCrtKeySpec can only be used with CRT keys");
       }
     } else if (rsaPrivateKeySpecClass.isAssignableFrom(keySpec)) {
       RSAPrivateKey rsaKey = (RSAPrivateKey) key;
       return keySpec.cast(
           new RSAPrivateKeySpec(rsaKey.getModulus(), rsaKey.getPrivateExponent()));
     } else {
       throw new InvalidKeySpecException(
           "KeySpec must be RSAPrivate(Crt)KeySpec or "
               + "PKCS8EncodedKeySpec for RSA private keys");
     }
   } else {
     // should not occur, caught in engineTranslateKey()
     throw new InvalidKeySpecException("Neither public nor private key");
   }
 }
예제 #4
0
  protected int engineGetKeySize(Key key) {
    if (key instanceof RSAPrivateKey) {
      RSAPrivateKey k = (RSAPrivateKey) key;

      return k.getModulus().bitLength();
    } else if (key instanceof RSAPublicKey) {
      RSAPublicKey k = (RSAPublicKey) key;

      return k.getModulus().bitLength();
    }

    throw new IllegalArgumentException("not an RSA key!");
  }
  @Override
  public boolean equals(Object o) {
    if (o == this) {
      return true;
    }

    if (o instanceof OpenSSLRSAPrivateKey) {
      OpenSSLRSAPrivateKey other = (OpenSSLRSAPrivateKey) o;

      /*
       * We can shortcut the true case, but it still may be equivalent but
       * different copies.
       */
      if (getOpenSSLKey().equals(other.getOpenSSLKey())) {
        return true;
      }

      return NativeCrypto.EVP_PKEY_cmp(getPkeyContext(), other.getPkeyContext()) == 1;
    }

    if (o instanceof RSAPrivateCrtKey) {
      ensureReadParams();
      RSAPrivateCrtKey other = (RSAPrivateCrtKey) o;

      if (getOpenSSLKey().isEngineBased()) {
        return getModulus().equals(other.getModulus())
            && publicExponent.equals(other.getPublicExponent());
      } else {
        return getModulus().equals(other.getModulus())
            && publicExponent.equals(other.getPublicExponent())
            && getPrivateExponent().equals(other.getPrivateExponent())
            && primeP.equals(other.getPrimeP())
            && primeQ.equals(other.getPrimeQ())
            && primeExponentP.equals(other.getPrimeExponentP())
            && primeExponentQ.equals(other.getPrimeExponentQ())
            && crtCoefficient.equals(other.getCrtCoefficient());
      }
    } else if (o instanceof RSAPrivateKey) {
      ensureReadParams();
      RSAPrivateKey other = (RSAPrivateKey) o;

      if (getOpenSSLKey().isEngineBased()) {
        return getModulus().equals(other.getModulus());
      } else {
        return getModulus().equals(other.getModulus())
            && getPrivateExponent().equals(other.getPrivateExponent());
      }
    }

    return false;
  }
  /**
   * Client_Key_Exchangeを受け取ったときの動作をします。
   *
   * @param line クライアントから受信した文字列
   * @throws CertificateException
   * @throws IOException
   * @throws KeyStoreException
   * @throws NoSuchAlgorithmException
   * @throws UnrecoverableKeyException
   * @author kinbara
   */
  private void recieveClientKeyExchange(String line)
      throws CertificateException, IOException, KeyStoreException, NoSuchAlgorithmException,
          UnrecoverableKeyException {

    X509 x509 = new X509("src/sglserver/conf/key/ca", "CAKeyStore", this.storePasswd);
    RSAPrivateKey sk = x509.getRSAPrivateKey("server", this.keyPasswd);
    // 暗号化されたプリマスターシークレットの抽出
    line = line.substring(line.indexOf(":") + 1);
    BigInteger preCipher = new BigInteger(line, 16);
    // プリマスターシークレットを復号
    preMastarSecret = preCipher.modPow(sk.getPrivateExponent(), sk.getModulus());
    // (事前共有鍵)=(秘密鍵). modPow((s乗:すなわちaのs乗),(元:すなわちg))
    // b = a.modPow(s, n); a mod n のs乗がbに代入される
  }
예제 #7
0
  /**
   * 生成密钥对�?�注意这里是生成密钥对KeyPair,再由密钥对获取公私�?
   *
   * @return
   */
  public static Map<String, byte[]> generateKeyBytes() {

    try {
      KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(KEY_ALGORITHM);
      keyPairGenerator.initialize(KEY_SIZE);
      KeyPair keyPair = keyPairGenerator.generateKeyPair();
      RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
      RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();

      Map<String, byte[]> keyMap = new HashMap<String, byte[]>();
      keyMap.put(PUBLIC_KEY, publicKey.getEncoded());
      keyMap.put(PRIVATE_KEY, privateKey.getEncoded());
      return keyMap;
    } catch (NoSuchAlgorithmException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
    return null;
  }
예제 #8
0
  /**
   * @param kpair test key pair
   * @param pubExponent expected public exponent.
   * @return true if test passed. false if test failed.
   */
  private static boolean specTest(KeyPair kpair, BigInteger pubExponent) {
    boolean passed = true;
    RSAPrivateKey priv = (RSAPrivateKey) kpair.getPrivate();
    RSAPublicKey pub = (RSAPublicKey) kpair.getPublic();

    // test the getModulus method
    if ((priv instanceof RSAKey) && (pub instanceof RSAKey)) {
      if (!priv.getModulus().equals(pub.getModulus())) {
        System.err.println("priv.getModulus() = " + priv.getModulus());
        System.err.println("pub.getModulus() = " + pub.getModulus());
        passed = false;
      }

      if (!pubExponent.equals(pub.getPublicExponent())) {
        System.err.println("pubExponent = " + pubExponent);
        System.err.println("pub.getPublicExponent() = " + pub.getPublicExponent());
        passed = false;
      }
    }
    return passed;
  }
예제 #9
0
 // internal implementation of translateKey() for private keys. See JCA doc
 private PrivateKey translatePrivateKey(PrivateKey key) throws InvalidKeyException {
   if (key instanceof RSAPrivateCrtKey) {
     if (key instanceof RSAPrivateCrtKeyImpl) {
       return key;
     }
     RSAPrivateCrtKey rsaKey = (RSAPrivateCrtKey) key;
     try {
       return new RSAPrivateCrtKeyImpl(
           rsaKey.getModulus(),
           rsaKey.getPublicExponent(),
           rsaKey.getPrivateExponent(),
           rsaKey.getPrimeP(),
           rsaKey.getPrimeQ(),
           rsaKey.getPrimeExponentP(),
           rsaKey.getPrimeExponentQ(),
           rsaKey.getCrtCoefficient());
     } catch (RuntimeException e) {
       // catch providers that incorrectly implement RSAPrivateCrtKey
       throw new InvalidKeyException("Invalid key", e);
     }
   } else if (key instanceof RSAPrivateKey) {
     if (key instanceof RSAPrivateKeyImpl) {
       return key;
     }
     RSAPrivateKey rsaKey = (RSAPrivateKey) key;
     try {
       return new RSAPrivateKeyImpl(rsaKey.getModulus(), rsaKey.getPrivateExponent());
     } catch (RuntimeException e) {
       // catch providers that incorrectly implement RSAPrivateKey
       throw new InvalidKeyException("Invalid key", e);
     }
   } else if ("PKCS#8".equals(key.getFormat())) {
     byte[] encoded = key.getEncoded();
     return RSAPrivateCrtKeyImpl.newKey(encoded);
   } else {
     throw new InvalidKeyException(
         "Private keys must be instance " + "of RSAPrivate(Crt)Key or have PKCS#8 encoding");
   }
 }
예제 #10
0
  protected KeySpec engineGetKeySpec(Key key, Class spec) throws InvalidKeySpecException {
    if (spec.isAssignableFrom(PKCS8EncodedKeySpec.class) && key.getFormat().equals("PKCS#8")) {
      return new PKCS8EncodedKeySpec(key.getEncoded());
    } else if (spec.isAssignableFrom(X509EncodedKeySpec.class) && key.getFormat().equals("X.509")) {
      return new X509EncodedKeySpec(key.getEncoded());
    } else if (spec.isAssignableFrom(RSAPublicKeySpec.class) && key instanceof RSAPublicKey) {
      RSAPublicKey k = (RSAPublicKey) key;

      return new RSAPublicKeySpec(k.getModulus(), k.getPublicExponent());
    } else if (spec.isAssignableFrom(RSAPrivateKeySpec.class) && key instanceof RSAPrivateKey) {
      RSAPrivateKey k = (RSAPrivateKey) key;

      return new RSAPrivateKeySpec(k.getModulus(), k.getPrivateExponent());
    } else if (spec.isAssignableFrom(RSAPrivateCrtKeySpec.class)
        && key instanceof RSAPrivateCrtKey) {
      RSAPrivateCrtKey k = (RSAPrivateCrtKey) key;

      return new RSAPrivateCrtKeySpec(
          k.getModulus(),
          k.getPublicExponent(),
          k.getPrivateExponent(),
          k.getPrimeP(),
          k.getPrimeQ(),
          k.getPrimeExponentP(),
          k.getPrimeExponentQ(),
          k.getCrtCoefficient());
    } else if (spec.isAssignableFrom(DHPrivateKeySpec.class) && key instanceof DHPrivateKey) {
      DHPrivateKey k = (DHPrivateKey) key;

      return new DHPrivateKeySpec(k.getX(), k.getParams().getP(), k.getParams().getG());
    } else if (spec.isAssignableFrom(DHPublicKeySpec.class) && key instanceof DHPublicKey) {
      DHPublicKey k = (DHPublicKey) key;

      return new DHPublicKeySpec(k.getY(), k.getParams().getP(), k.getParams().getG());
    }

    throw new RuntimeException("not implemented yet " + key + " " + spec);
  }
예제 #11
0
  public static void main(String[] argv) throws Exception {
    String fileName = argv[0];
    File file = new File(fileName);
    if (!file.exists()) {
      System.out.println("File Not Found: " + fileName);
      return;
    }

    KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
    keyPairGenerator.initialize(512, new SecureRandom());
    KeyPair keyPair = keyPairGenerator.generateKeyPair();

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

    StringBuffer buf = new StringBuffer();
    BufferedReader reader =
        new BufferedReader(new InputStreamReader(new FileInputStream(file), "UTF-8"));
    Writer writer =
        new OutputStreamWriter(
            new FileOutputStream(new File(file.getAbsolutePath() + ".opt")), "UTF-8");
    try {
      String line = "";
      while ((line = reader.readLine()) != null) buf.append(line).append("\n");

      String str =
          buf.toString()
              .replaceAll("@keyManagerModulus@", privateKey.getModulus().toString(16))
              .replaceAll("@keyManagerExponent@", privateKey.getPrivateExponent().toString(16));

      writer.write(str);
    } catch (Exception ex) {
      System.out.println(ex.getMessage());
      ex.printStackTrace();
    } finally {
      reader.close();
      writer.close();
    }
  }
예제 #12
0
 private static String decryptByPrivateKey(final String mi, final RSAPrivateKey privateKey)
     throws Exception {
   final String data = bcd2Str(Base64.decodeBase64(mi.getBytes()));
   final Cipher cipher = Cipher.getInstance("RSA");
   cipher.init(Cipher.DECRYPT_MODE, privateKey);
   final int key_len = privateKey.getModulus().bitLength() / 8;
   final byte[] bytes = data.getBytes();
   final byte[] bcd = ASCII_To_BCD(bytes, bytes.length);
   String ming = "";
   final byte[][] arrays = splitArray(bcd, key_len);
   for (final byte[] arr : arrays) {
     ming += new String(cipher.doFinal(arr));
   }
   return ming;
 }
예제 #13
0
  protected static void test() throws Exception {
    final HashMap<String, Object> map = RSAUtils.generateKeys();
    final RSAPublicKey publicKey = (RSAPublicKey) map.get("public");
    final RSAPrivateKey privateKey = (RSAPrivateKey) map.get("private");

    final String modulus = publicKey.getModulus().toString();
    final String public_exponent = publicKey.getPublicExponent().toString();
    final String private_exponent = privateKey.getPrivateExponent().toString();
    final RSAPublicKey pubKey = RSAUtils.getPublicKey(modulus, public_exponent);
    final RSAPrivateKey priKey = RSAUtils.getPrivateKey(modulus, private_exponent);

    final String pubStr = new String(Base64.encodeBase64(pubKey.getEncoded()));
    System.err.println("Encoded 1: " + pubStr);
    final RSAPublicKey pk2 = RSAUtils.getPublicKey(pubStr);
    System.err.println("Encoded 2: " + new String(Base64.encodeBase64(pk2.getEncoded())));

    final String priStr = new String(Base64.encodeBase64(priKey.getEncoded()));
    System.err.println("Encoded 1: " + priStr);
    final RSAPrivateKey pi2 = RSAUtils.getPrivateKey(priStr);
    System.err.println("Encoded 2: " + new String(Base64.encodeBase64(pi2.getEncoded())));

    System.err.println("modulus: " + modulus);
    System.err.println("public_exponent: " + public_exponent);
    System.err.println("private_exponent: " + private_exponent);

    String ming = "123456789";
    for (int i = 0; i < 1; i++) {
      ming += "123456789";
    }
    final String mi = RSAUtils.encryptByPublicKey(ming, pubKey);
    System.err.println("mi: " + mi);
    ming = RSAUtils.decryptByPrivateKey(mi, priKey);
    System.err.println("ming: " + ming);

    final DynamicPasswordCipher cipher = new DynamicPasswordCipher();
    System.err.println("cipher: " + cipher.decrypt(cipher.encrypt(ming)));
  }