private Map<String, Object> createRSAJWK(RSAPublicKey key, KeyUse use, String alg)
     throws ServerException {
   String alias = null;
   try {
     alias = getStringSetting(realm, OAuth2Constants.OAuth2ProviderService.KEYSTORE_ALIAS);
   } catch (SSOException | SMSException e) {
     logger.error(e.getMessage());
     throw new ServerException(e);
   }
   if (StringUtils.isBlank(alias)) {
     logger.error("Alias of ID Token Signing Key not set.");
     throw new ServerException("Alias of ID Token Signing Key not set.");
   } else if ("test".equals(alias)) {
     logger.warning("Alias of ID Token Signing Key should be changed from default, 'test'.");
   }
   String kid =
       Hash.hash(alias + key.getModulus().toString() + key.getPublicExponent().toString());
   return json(object(
           field("kty", "RSA"),
           field(OAuth2Constants.JWTTokenParams.KEY_ID, kid),
           field("use", use.toString()),
           field("alg", alg),
           field("n", Base64url.encode(key.getModulus().toByteArray())),
           field("e", Base64url.encode(key.getPublicExponent().toByteArray()))))
       .asMap();
 }
Exemplo n.º 2
0
 /**
  * 打印公钥信息
  *
  * @param publicKey
  */
 public static void printPublicKeyInfo(PublicKey publicKey) {
   RSAPublicKey rsaPublicKey = (RSAPublicKey) publicKey;
   System.out.println("----------RSAPublicKey----------");
   System.out.println("Modulus.length=" + rsaPublicKey.getModulus().bitLength());
   System.out.println("Modulus=" + rsaPublicKey.getModulus().toString());
   System.out.println("PublicExponent.length=" + rsaPublicKey.getPublicExponent().bitLength());
   System.out.println("PublicExponent=" + rsaPublicKey.getPublicExponent().toString());
 }
Exemplo n.º 3
0
  /**
   * Convert a public key to the SSH format.
   *
   * <p>Note that only RSA keys are supported at the moment.
   *
   * @param key the public key to convert
   * @return an array of bytes that can with the representation of the public key
   */
  public static byte[] getKeyBytes(final PublicKey key) {
    // We only support RSA at the moment:
    if (!(key instanceof RSAPublicKey)) {
      log.error(
          "The key algorithm \"" + key.getAlgorithm() + "\" is not supported, will return null.");
      return null;
    }

    // Extract the bytes of the exponent and the modulus
    // of the key:
    final RSAPublicKey rsaKey = (RSAPublicKey) key;
    final byte[] exponentBytes = rsaKey.getPublicExponent().toByteArray();
    final byte[] modulusBytes = rsaKey.getModulus().toByteArray();
    if (log.isDebugEnabled()) {
      log.debug(
          "Exponent is "
              + rsaKey.getPublicExponent()
              + " ("
              + Hex.encodeHexString(exponentBytes)
              + ").");
      log.debug(
          "Modulus is " + rsaKey.getModulus() + " (" + Hex.encodeHexString(exponentBytes) + ").");
    }

    try {
      // Prepare the stream to write the binary SSH key:
      final ByteArrayOutputStream binaryOut = new ByteArrayOutputStream();
      final DataOutputStream dataOut = new DataOutputStream(binaryOut);

      // Write the SSH header (4 bytes for the length of the algorithm
      // name and then the algorithm name):
      dataOut.writeInt(SSH_RSA.length());
      dataOut.writeBytes(SSH_RSA);

      // Write the exponent and modulus bytes (note that it is not
      // necessary to check if the most significative bit is one, as
      // that will never happen with byte arrays created from big
      // integers, unless they are negative, which is not the case
      // for RSA modulus or exponents):
      dataOut.writeInt(exponentBytes.length);
      dataOut.write(exponentBytes);
      dataOut.writeInt(modulusBytes.length);
      dataOut.write(modulusBytes);

      // Done, extract the bytes:
      binaryOut.close();
      final byte[] keyBytes = binaryOut.toByteArray();
      if (log.isDebugEnabled()) {
        log.debug("Key bytes are " + Hex.encodeHexString(keyBytes) + ".");
      }

      return keyBytes;
    } catch (IOException exception) {
      log.error("Error while serializing public key, will return null.", exception);
      return null;
    }
  }
Exemplo n.º 4
0
 private String getString(PublicKey key) throws FailedLoginException {
   try {
     if (key instanceof DSAPublicKey) {
       DSAPublicKey dsa = (DSAPublicKey) key;
       ByteArrayOutputStream baos = new ByteArrayOutputStream();
       DataOutputStream dos = new DataOutputStream(baos);
       write(dos, "ssh-dss");
       write(dos, dsa.getParams().getP());
       write(dos, dsa.getParams().getQ());
       write(dos, dsa.getParams().getG());
       write(dos, dsa.getY());
       dos.close();
       return base64Encode(baos.toByteArray());
     } else if (key instanceof RSAKey) {
       RSAPublicKey rsa = (RSAPublicKey) key;
       ByteArrayOutputStream baos = new ByteArrayOutputStream();
       DataOutputStream dos = new DataOutputStream(baos);
       write(dos, "ssh-rsa");
       write(dos, rsa.getPublicExponent());
       write(dos, rsa.getModulus());
       dos.close();
       return base64Encode(baos.toByteArray());
     } else {
       throw new FailedLoginException("Unsupported key type " + key.getClass().toString());
     }
   } catch (IOException e) {
     throw new FailedLoginException("Unable to check public key");
   }
 }
  /**
   * Certificate_Verify(証明書)を受け取ったときの動作をします。
   *
   * @param line クライアントから受信した文字列
   * @return クライアントの証明書の真偽
   * @author kinbara
   */
  private boolean recieveCertificateVerify(String line) {
    boolean cert_verify = false;
    // サーバー側のダイジェストのハッシュ値
    ListIterator listIte = netDigest.listIterator();
    String digest = "";
    while (listIte.hasNext()) {
      digest += listIte.next().toString();
    }
    digest = digest.substring(0, digest.indexOf("Certificate_Verify"));
    BigInteger digest1 = new BigInteger(this.getHash(digest), 16);
    // クライアントの公開鍵で復号
    BigInteger digest2 = new BigInteger(line.substring(line.indexOf(":") + 1), 16);
    try {
      X509 x509 = new X509("src/sglserver/conf/key/ca", "CAKeyStore", this.storePasswd);
      // TODO:(注意)ユーザーの公開鍵をpeerNameでCAKeyStoreに登録している場合のみ有効
      RSAPublicKey pk = x509.getRSAPublicKey(peerName);
      digest2 = digest2.modPow(pk.getPublicExponent(), pk.getModulus()); // 復号
      // b = a.modPow(s, n); → a mod n のs乗がbに代入される
      // pk.getPublicExponent()→公開指数
      // pk.getModulus()→pkのmod値
    } catch (Exception e) {

      e.printStackTrace();
    }
    if (digest1.compareTo(digest2) == 0) {
      System.out.println(socket.getRemoteSocketAddress() + "は、信頼できます。");
      cert_verify = true;
    } else {
      System.out.println(socket.getRemoteSocketAddress() + "は、危険です。");
    }
    return (cert_verify);
  }
Exemplo n.º 6
0
  @Override
  public boolean equals(Object o) {
    if (o == this) {
      return true;
    }

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

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

    if (!(o instanceof RSAPublicKey)) {
      return false;
    }

    ensureReadParams();

    RSAPublicKey other = (RSAPublicKey) o;
    return modulus.equals(other.getModulus()) && publicExponent.equals(other.getPublicExponent());
  }
Exemplo n.º 7
0
  /**
   * Creates a {@code KeyValueType} that wraps the specified public key. This method supports DSA
   * and RSA keys.
   *
   * @param key the {@code PublicKey} that will be represented as a {@code KeyValueType}.
   * @return the constructed {@code KeyValueType} or {@code null} if the specified key is neither a
   *     DSA nor a RSA key.
   */
  public static KeyValueType createKeyValue(PublicKey key) {
    if (key instanceof RSAPublicKey) {
      RSAPublicKey pubKey = (RSAPublicKey) key;
      byte[] modulus = pubKey.getModulus().toByteArray();
      byte[] exponent = pubKey.getPublicExponent().toByteArray();

      RSAKeyValueType rsaKeyValue = new RSAKeyValueType();
      rsaKeyValue.setModulus(Base64.encodeBytes(modulus).getBytes());
      rsaKeyValue.setExponent(Base64.encodeBytes(exponent).getBytes());
      return rsaKeyValue;
    } else if (key instanceof DSAPublicKey) {
      DSAPublicKey pubKey = (DSAPublicKey) key;
      byte[] P = pubKey.getParams().getP().toByteArray();
      byte[] Q = pubKey.getParams().getQ().toByteArray();
      byte[] G = pubKey.getParams().getG().toByteArray();
      byte[] Y = pubKey.getY().toByteArray();

      DSAKeyValueType dsaKeyValue = new DSAKeyValueType();
      dsaKeyValue.setP(Base64.encodeBytes(P).getBytes());
      dsaKeyValue.setQ(Base64.encodeBytes(Q).getBytes());
      dsaKeyValue.setG(Base64.encodeBytes(G).getBytes());
      dsaKeyValue.setY(Base64.encodeBytes(Y).getBytes());
      return dsaKeyValue;
    }
    throw logger.unsupportedType(key.toString());
  }
Exemplo n.º 8
0
 private static RsaPublicKey readRsaX509Certificate(PublicKey publicKey, Padding padding)
     throws KeyczarException {
   RSAPublicKey jceKey = (RSAPublicKey) publicKey;
   RsaPublicKey key = new RsaPublicKey();
   key.set(jceKey.getModulus().bitLength(), jceKey.getModulus(), jceKey.getPublicExponent());
   key.setPadding(padding == null ? Padding.OAEP : padding);
   return key;
 }
Exemplo n.º 9
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");
   }
 }
Exemplo n.º 10
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;
  }
Exemplo n.º 11
0
  protected void assertsRsaKey(RSAPublicKey pubKey) {
    Assert.assertEquals(new BigInteger("65537"), pubKey.getPublicExponent());

    final String modulus =
        "22840028388110743583131987675136887114153126223124011317437832666"
            + "25854781992306722377061897219550740787245366580892823047038154958086308817575397"
            + "86207323511183698710582016112357060923053840856777454937186677760616034425665662"
            + "82261472797239839649294119764258671908502475664743909024714305171394796349355615"
            + "01410512875834037603865586850446929492793894140130256172372280205701912961974382"
            + "44718040286649900869581969011709834002741504113088991590355018061303753262915348"
            + "56911333402703872012358714368938812147820774134682975669390306870781321673316754"
            + "378035200080485404740444851779733064858474545694849794752210968120764651";
    Assert.assertEquals(new BigInteger(modulus), pubKey.getModulus());
  }
Exemplo n.º 12
0
 @Override
 protected SignerWithRecovery getRSASigner() {
   SignerWithRecovery signer = null;
   try {
     RSAEngine rsa = new RSAEngine();
     RSAPublicKey pub = (RSAPublicKey) getPublicKey(aaFile);
     RSAKeyParameters pubParameters =
         new RSAKeyParameters(false, pub.getModulus(), pub.getPublicExponent());
     signer = new ISO9796d2Signer(rsa, new SHA256Digest(), false);
     signer.init(false, pubParameters);
   } catch (Exception e) {
     e.printStackTrace();
   }
   return signer;
 }
Exemplo n.º 13
0
  static byte[] buildRSA(RSAPublicKey key) {
    DataByteOutputStream out = new DataByteOutputStream();
    BigInteger exponent = key.getPublicExponent();
    BigInteger modulus = key.getModulus();
    int exponentLength = BigIntegerLength(exponent);

    if (exponentLength < 256) out.writeByte(exponentLength);
    else {
      out.writeByte(0);
      out.writeShort(exponentLength);
    }
    out.writeBigInteger(exponent);
    out.writeBigInteger(modulus);

    return out.toByteArray();
  }
Exemplo n.º 14
0
 static OpenSSLKey getInstance(RSAPublicKey rsaPublicKey) throws InvalidKeyException {
   try {
     return new OpenSSLKey(
         NativeCrypto.EVP_PKEY_new_RSA(
             rsaPublicKey.getModulus().toByteArray(),
             rsaPublicKey.getPublicExponent().toByteArray(),
             null,
             null,
             null,
             null,
             null,
             null));
   } catch (Exception e) {
     throw new InvalidKeyException(e);
   }
 }
  @Test
  public void test() {
    ServerCACR serverCACR = new ServerCACR();
    CA_CR_keys cacr_keys = new CA_CR_keys();
    Random rand = new Random();
    BigInteger cegado_cliente = new BigInteger(4, rand);
    System.out.println("antes de encriptar con privKey de la CA ------> " + cegado_cliente);

    BigInteger certificado = serverCACR.certificate(cegado_cliente);
    System.out.println("certificado----------------------------------->" + certificado);

    RSAPublicKey pubKey = CA_CR_keys.getPubKey();
    BigInteger e = pubKey.getPublicExponent();
    BigInteger n = pubKey.getModulus();
    System.out.println(
        "despues de desencriptar con la pública ------->" + certificado.modPow(e, n));
  }
Exemplo n.º 16
0
 // internal implementation of translateKey() for public keys. See JCA doc
 private PublicKey translatePublicKey(PublicKey key) throws InvalidKeyException {
   if (key instanceof RSAPublicKey) {
     if (key instanceof RSAPublicKeyImpl) {
       return key;
     }
     RSAPublicKey rsaKey = (RSAPublicKey) key;
     try {
       return new RSAPublicKeyImpl(rsaKey.getModulus(), rsaKey.getPublicExponent());
     } catch (RuntimeException e) {
       // catch providers that incorrectly implement RSAPublicKey
       throw new InvalidKeyException("Invalid key", e);
     }
   } else if ("X.509".equals(key.getFormat())) {
     byte[] encoded = key.getEncoded();
     return new RSAPublicKeyImpl(encoded);
   } else {
     throw new InvalidKeyException(
         "Public keys must be instance " + "of RSAPublicKey or have X.509 encoding");
   }
 }
  public PublicKeyDataObject getPublicKeyDataObject(
      ASN1ObjectIdentifier usage, PublicKey publicKey) {
    if (publicKey instanceof java.security.interfaces.RSAPublicKey) {
      java.security.interfaces.RSAPublicKey pubKey =
          (java.security.interfaces.RSAPublicKey) publicKey;

      return new RSAPublicKey(usage, pubKey.getModulus(), pubKey.getPublicExponent());
    } else {
      ECPublicKey pubKey = (ECPublicKey) publicKey;
      java.security.spec.ECParameterSpec params = pubKey.getParams();

      return new ECDSAPublicKey(
          usage,
          ((ECFieldFp) params.getCurve().getField()).getP(),
          params.getCurve().getA(),
          params.getCurve().getB(),
          convertPoint(convertCurve(params.getCurve()), params.getGenerator()).getEncoded(),
          params.getOrder(),
          convertPoint(convertCurve(params.getCurve()), pubKey.getW()).getEncoded(),
          params.getCofactor());
    }
  }
Exemplo n.º 18
0
  protected byte[] getHash(RSAPublicKey publicKey) throws EbicsException {
    String modulus;
    String exponent;
    String hash;
    byte[] digest;

    exponent = Hex.encodeHexString(publicKey.getPublicExponent().toByteArray());
    modulus = Hex.encodeHexString(removeFirstByte(publicKey.getModulus().toByteArray()));
    hash = exponent + " " + modulus;

    if (hash.charAt(0) == '0') {
      hash = hash.substring(1);
    }

    try {
      digest = MessageDigest.getInstance("SHA-256", "BC").digest(hash.getBytes("US-ASCII"));
    } catch (GeneralSecurityException | UnsupportedEncodingException e) {
      throw new EbicsException(e.getMessage());
    }

    return format(new String(Hex.encodeHex(digest, false))).getBytes();
  }
Exemplo n.º 19
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);
  }
Exemplo n.º 20
0
  /**
   * @param args
   * @throws Exception
   */
  public static void main(String[] args) throws Exception {

    File file = new File("c:/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("c:/encrypt_result.dat");
    OutputStream out = new FileOutputStream(file);
    out.write(raw);
    out.close();
    byte[] data = RSAUtil.decrypt(recoveryPubKey, raw);
    file = new File("c:/decrypt_result.html");
    out = new FileOutputStream(file);
    out.write(data);
    out.flush();
    out.close();
  }
Exemplo n.º 21
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)));
  }
Exemplo n.º 22
0
  /**
   * Create a PGPPublicKey from the passed in JCA one.
   *
   * <p>Note: the time passed in affects the value of the key's keyID, so you probably only want to
   * do this once for a JCA key, or make sure you keep track of the time you used.
   *
   * @param algorithm asymmetric algorithm type representing the public key.
   * @param pubKey actual public key to associate.
   * @param time date of creation.
   * @throws PGPException on key creation problem.
   */
  public PGPPublicKey getPGPPublicKey(int algorithm, PublicKey pubKey, Date time)
      throws PGPException {
    BCPGKey bcpgKey;

    if (pubKey instanceof RSAPublicKey) {
      RSAPublicKey rK = (RSAPublicKey) pubKey;

      bcpgKey = new RSAPublicBCPGKey(rK.getModulus(), rK.getPublicExponent());
    } else if (pubKey instanceof DSAPublicKey) {
      DSAPublicKey dK = (DSAPublicKey) pubKey;
      DSAParams dP = dK.getParams();

      bcpgKey = new DSAPublicBCPGKey(dP.getP(), dP.getQ(), dP.getG(), dK.getY());
    } else if (pubKey instanceof ElGamalPublicKey) {
      ElGamalPublicKey eK = (ElGamalPublicKey) pubKey;
      ElGamalParameterSpec eS = eK.getParameters();

      bcpgKey = new ElGamalPublicBCPGKey(eS.getP(), eS.getG(), eK.getY());
    } else {
      throw new PGPException("unknown key class");
    }

    return new PGPPublicKey(new PublicKeyPacket(algorithm, time, bcpgKey), fingerPrintCalculator);
  }
Exemplo n.º 23
0
 public PKIObject(String requestType, String serverId, RSAPublicKey pubKey) {
   this.requestType = requestType;
   this.serverId = serverId;
   this.modulus = pubKey.getModulus();
   this.exponent = pubKey.getPublicExponent();
 }
Exemplo n.º 24
0
 /**
  * 公钥 指数
  *
  * @param publicKey
  * @return
  */
 public static String getPublicExponent(RSAPublicKey publicKey) {
   return publicKey.getPublicExponent().toString(16);
 }
Exemplo n.º 25
0
 /** Perform an RSA public key operation. */
 public static byte[] rsa(byte[] msg, RSAPublicKey key) throws BadPaddingException {
   return crypt(msg, key.getModulus(), key.getPublicExponent());
 }
  /**
   * Appends an HTML representation of the given X509Certificate.
   *
   * @param sb StringBuilder to append to
   * @param certificate to print
   */
  private void renderX509(StringBuilder sb, X509Certificate certificate) {
    X500Principal issuer = certificate.getIssuerX500Principal();
    X500Principal subject = certificate.getSubjectX500Principal();

    sb.append("<table cellspacing='1' cellpadding='1'>\n");

    // subject
    addTitle(sb, R.getI18NString("service.gui.CERT_INFO_ISSUED_TO"));
    try {
      for (Rdn name : new LdapName(subject.getName()).getRdns()) {
        String nameType = name.getType();
        String lblKey = "service.gui.CERT_INFO_" + nameType;
        String lbl = R.getI18NString(lblKey);

        if ((lbl == null) || ("!" + lblKey + "!").equals(lbl)) lbl = nameType;

        final String value;
        Object nameValue = name.getValue();

        if (nameValue instanceof byte[]) {
          byte[] nameValueAsByteArray = (byte[]) nameValue;

          value = getHex(nameValueAsByteArray) + " (" + new String(nameValueAsByteArray) + ")";
        } else value = nameValue.toString();

        addField(sb, lbl, value);
      }
    } catch (InvalidNameException ine) {
      addField(sb, R.getI18NString("service.gui.CERT_INFO_CN"), subject.getName());
    }

    // issuer
    addTitle(sb, R.getI18NString("service.gui.CERT_INFO_ISSUED_BY"));
    try {
      for (Rdn name : new LdapName(issuer.getName()).getRdns()) {
        String nameType = name.getType();
        String lblKey = "service.gui.CERT_INFO_" + nameType;
        String lbl = R.getI18NString(lblKey);

        if ((lbl == null) || ("!" + lblKey + "!").equals(lbl)) lbl = nameType;

        final String value;
        Object nameValue = name.getValue();

        if (nameValue instanceof byte[]) {
          byte[] nameValueAsByteArray = (byte[]) nameValue;

          value = getHex(nameValueAsByteArray) + " (" + new String(nameValueAsByteArray) + ")";
        } else value = nameValue.toString();

        addField(sb, lbl, value);
      }
    } catch (InvalidNameException ine) {
      addField(sb, R.getI18NString("service.gui.CERT_INFO_CN"), issuer.getName());
    }

    // validity
    addTitle(sb, R.getI18NString("service.gui.CERT_INFO_VALIDITY"));
    addField(
        sb,
        R.getI18NString("service.gui.CERT_INFO_ISSUED_ON"),
        certificate.getNotBefore().toString());
    addField(
        sb,
        R.getI18NString("service.gui.CERT_INFO_EXPIRES_ON"),
        certificate.getNotAfter().toString());

    addTitle(sb, R.getI18NString("service.gui.CERT_INFO_FINGERPRINTS"));
    try {
      String sha1String = getThumbprint(certificate, "SHA1");
      String md5String = getThumbprint(certificate, "MD5");

      addField(sb, "SHA1:", sha1String);
      addField(sb, "MD5:", md5String);
    } catch (CertificateException e) {
      // do nothing as we cannot show this value
    }

    addTitle(sb, R.getI18NString("service.gui.CERT_INFO_CERT_DETAILS"));

    addField(
        sb,
        R.getI18NString("service.gui.CERT_INFO_SER_NUM"),
        certificate.getSerialNumber().toString());

    addField(
        sb, R.getI18NString("service.gui.CERT_INFO_VER"), String.valueOf(certificate.getVersion()));

    addField(
        sb,
        R.getI18NString("service.gui.CERT_INFO_SIGN_ALG"),
        String.valueOf(certificate.getSigAlgName()));

    addTitle(sb, R.getI18NString("service.gui.CERT_INFO_PUB_KEY_INFO"));

    addField(
        sb,
        R.getI18NString("service.gui.CERT_INFO_ALG"),
        certificate.getPublicKey().getAlgorithm());

    if (certificate.getPublicKey().getAlgorithm().equals("RSA")) {
      RSAPublicKey key = (RSAPublicKey) certificate.getPublicKey();

      addField(
          sb,
          R.getI18NString("service.gui.CERT_INFO_PUB_KEY"),
          R.getI18NString(
              "service.gui.CERT_INFO_KEY_BYTES_PRINT",
              new String[] {
                String.valueOf(key.getModulus().toByteArray().length - 1),
                key.getModulus().toString(16)
              }));

      addField(
          sb, R.getI18NString("service.gui.CERT_INFO_EXP"), key.getPublicExponent().toString());

      addField(
          sb,
          R.getI18NString("service.gui.CERT_INFO_KEY_SIZE"),
          R.getI18NString(
              "service.gui.CERT_INFO_KEY_BITS_PRINT",
              new String[] {String.valueOf(key.getModulus().bitLength())}));
    } else if (certificate.getPublicKey().getAlgorithm().equals("DSA")) {
      DSAPublicKey key = (DSAPublicKey) certificate.getPublicKey();

      addField(sb, "Y:", key.getY().toString(16));
    }

    addField(
        sb,
        R.getI18NString("service.gui.CERT_INFO_SIGN"),
        R.getI18NString(
            "service.gui.CERT_INFO_KEY_BYTES_PRINT",
            new String[] {
              String.valueOf(certificate.getSignature().length), getHex(certificate.getSignature())
            }));

    sb.append("</table>\n");
  }