Пример #1
0
  public PublicKey getPublicKey(PGPPublicKey publicKey) throws PGPException {
    KeyFactory fact;

    PublicKeyPacket publicPk = publicKey.getPublicKeyPacket();

    try {
      switch (publicPk.getAlgorithm()) {
        case PublicKeyAlgorithmTags.RSA_ENCRYPT:
        case PublicKeyAlgorithmTags.RSA_GENERAL:
        case PublicKeyAlgorithmTags.RSA_SIGN:
          RSAPublicBCPGKey rsaK = (RSAPublicBCPGKey) publicPk.getKey();
          RSAPublicKeySpec rsaSpec =
              new RSAPublicKeySpec(rsaK.getModulus(), rsaK.getPublicExponent());

          fact = helper.createKeyFactory("RSA");

          return fact.generatePublic(rsaSpec);
        case PublicKeyAlgorithmTags.DSA:
          DSAPublicBCPGKey dsaK = (DSAPublicBCPGKey) publicPk.getKey();
          DSAPublicKeySpec dsaSpec =
              new DSAPublicKeySpec(dsaK.getY(), dsaK.getP(), dsaK.getQ(), dsaK.getG());

          fact = helper.createKeyFactory("DSA");

          return fact.generatePublic(dsaSpec);
        case PublicKeyAlgorithmTags.ELGAMAL_ENCRYPT:
        case PublicKeyAlgorithmTags.ELGAMAL_GENERAL:
          ElGamalPublicBCPGKey elK = (ElGamalPublicBCPGKey) publicPk.getKey();
          ElGamalPublicKeySpec elSpec =
              new ElGamalPublicKeySpec(
                  elK.getY(), new ElGamalParameterSpec(elK.getP(), elK.getG()));

          fact = helper.createKeyFactory("ElGamal");

          return fact.generatePublic(elSpec);
        default:
          throw new PGPException("unknown public key algorithm encountered");
      }
    } catch (PGPException e) {
      throw e;
    } catch (Exception e) {
      throw new PGPException("exception constructing public key", e);
    }
  }
  public byte[] calculateFingerprint(PublicKeyPacket publicPk) throws PGPException {
    BCPGKey key = publicPk.getKey();
    Digest digest;

    if (publicPk.getVersion() <= 3) {
      RSAPublicBCPGKey rK = (RSAPublicBCPGKey) key;

      try {
        digest = new MD5Digest();

        byte[] bytes = new MPInteger(rK.getModulus()).getEncoded();
        digest.update(bytes, 2, bytes.length - 2);

        bytes = new MPInteger(rK.getPublicExponent()).getEncoded();
        digest.update(bytes, 2, bytes.length - 2);
      } catch (IOException e) {
        throw new PGPException("can't encode key components: " + e.getMessage(), e);
      }
    } else {
      try {
        byte[] kBytes = publicPk.getEncodedContents();

        digest = new SHA1Digest();

        digest.update((byte) 0x99);
        digest.update((byte) (kBytes.length >> 8));
        digest.update((byte) kBytes.length);
        digest.update(kBytes, 0, kBytes.length);
      } catch (IOException e) {
        throw new PGPException("can't encode key components: " + e.getMessage(), e);
      }
    }

    byte[] digBuf = new byte[digest.getDigestSize()];

    digest.doFinal(digBuf, 0);

    return digBuf;
  }