private AlgorithmIdentifier getPBES2AlgorithmIdentifier(ASN1Encodable parameters) {
    AlgorithmIdentifier alg = AlgorithmIdentifier.getInstance(parameters);

    if (!alg.getAlgorithm().equals(PKCSObjectIdentifiers.id_PBES2)) {
      throw new IllegalArgumentException(
          "Illegal algorithm identifier for PBES2: " + alg.getAlgorithm().getId());
    }
    return alg;
  }
  public String getSignatureName(AlgorithmIdentifier digestAlg, AlgorithmIdentifier encryptionAlg) {
    String digestName = getDigestAlgName(encryptionAlg.getAlgorithm());

    if (!digestName.equals(encryptionAlg.getAlgorithm().getId())) {
      return digestName + "with" + getEncryptionAlgName(encryptionAlg.getAlgorithm());
    }

    return getDigestAlgName(digestAlg.getAlgorithm())
        + "with"
        + getEncryptionAlgName(encryptionAlg.getAlgorithm());
  }
  private static String getSignatureName(AlgorithmIdentifier sigAlgId) {
    ASN1Encodable params = sigAlgId.getParameters();

    if (params != null && !DERNull.INSTANCE.equals(params)) {
      if (sigAlgId.getAlgorithm().equals(PKCSObjectIdentifiers.id_RSASSA_PSS)) {
        RSASSAPSSparams rsaParams = RSASSAPSSparams.getInstance(params);
        return getDigestAlgName(rsaParams.getHashAlgorithm().getAlgorithm()) + "WITHRSAANDMGF1";
      }
    }

    if (oids.containsKey(sigAlgId.getAlgorithm())) {
      return (String) oids.get(sigAlgId.getAlgorithm());
    }

    return sigAlgId.getAlgorithm().getId();
  }
Esempio n. 4
0
  @Override
  public boolean isSignedBy(final CertificateToken issuerToken) {

    if (this.issuerToken != null) {

      return this.issuerToken.equals(issuerToken);
    }
    final TimestampValidation timestampValidation = validateTimestampToken(timeStamp, issuerToken);
    final TimestampValidity timestampValidity = timestampValidation.getValidity();
    signatureInvalidityReason = timestampValidity.name();
    signatureValid = timestampValidation.isValid();
    if (signatureValid) {

      this.issuerToken = issuerToken;

      issuerX500Principal = issuerToken.getSubjectX500Principal();
      final String algorithm = issuerToken.getPublicKey().getAlgorithm();
      final EncryptionAlgorithm encryptionAlgorithm = EncryptionAlgorithm.forName(algorithm);
      final AlgorithmIdentifier hashAlgorithm = timeStamp.getTimeStampInfo().getHashAlgorithm();
      final DigestAlgorithm digestAlgorithm =
          DigestAlgorithm.forOID(hashAlgorithm.getAlgorithm().getId());
      signatureAlgorithm = SignatureAlgorithm.getAlgorithm(encryptionAlgorithm, digestAlgorithm);
    }
    return signatureValid;
  }
Esempio n. 5
0
 @Override
 public String toString() {
   return "#<EncContent contentType="
       + contentType
       + " algorithm="
       + (algorithm == null ? "null" : ASN1Registry.o2a(algorithm.getAlgorithm()))
       + " content="
       + encData
       + ">";
 }
  Signature createSignature(AlgorithmIdentifier sigAlgId) throws GeneralSecurityException {
    Signature sig;

    try {
      sig = helper.createSignature(getSignatureName(sigAlgId));
    } catch (NoSuchAlgorithmException e) {
      //
      // try an alternate
      //
      if (oids.get(sigAlgId.getAlgorithm()) != null) {
        String signatureAlgorithm = (String) oids.get(sigAlgId.getAlgorithm());

        sig = helper.createSignature(signatureAlgorithm);
      } else {
        throw e;
      }
    }

    return sig;
  }
  MessageDigest createDigest(AlgorithmIdentifier digAlgId) throws GeneralSecurityException {
    MessageDigest dig;

    try {
      dig = helper.createDigest(getDigestAlgName(digAlgId.getAlgorithm()));
    } catch (NoSuchAlgorithmException e) {
      //
      // try an alternate
      //
      if (oids.get(digAlgId.getAlgorithm()) != null) {
        String digestAlgorithm = (String) oids.get(digAlgId.getAlgorithm());

        dig = helper.createDigest(digestAlgorithm);
      } else {
        throw e;
      }
    }

    return dig;
  }
Esempio n. 8
0
 /** c: PEM_read_PrivateKey + PEM_read_bio_PrivateKey CAUTION: KeyPair#getPublic() may be null. */
 public static KeyPair readPrivateKey(Reader in, char[] password) throws IOException {
   BufferedReader _in = makeBuffered(in);
   String line;
   while ((line = _in.readLine()) != null) {
     if (line.indexOf(BEF_G + PEM_STRING_RSA) != -1) {
       try {
         return readKeyPair(_in, password, "RSA", BEF_E + PEM_STRING_RSA);
       } catch (Exception e) {
         throw new IOException("problem creating RSA private key: " + e.toString());
       }
     } else if (line.indexOf(BEF_G + PEM_STRING_DSA) != -1) {
       try {
         return readKeyPair(_in, password, "DSA", BEF_E + PEM_STRING_DSA);
       } catch (Exception e) {
         throw new IOException("problem creating DSA private key: " + e.toString());
       }
     } else if (line.indexOf(BEF_G + PEM_STRING_ECPRIVATEKEY) != -1) {
       throw new IOException("EC private key not supported");
     } else if (line.indexOf(BEF_G + PEM_STRING_PKCS8INF) != -1) {
       try {
         byte[] bytes = readBytes(_in, BEF_E + PEM_STRING_PKCS8INF);
         PrivateKeyInfo info =
             new PrivateKeyInfo((ASN1Sequence) new ASN1InputStream(bytes).readObject());
         String type = getPrivateKeyTypeFromObjectId(info.getAlgorithmId().getObjectId());
         return org.jruby.ext.openssl.impl.PKey.readPrivateKey(
             info.getPrivateKey().getDEREncoded(), type);
       } catch (Exception e) {
         throw new IOException("problem creating private key: " + e.toString());
       }
     } else if (line.indexOf(BEF_G + PEM_STRING_PKCS8) != -1) {
       try {
         byte[] bytes = readBytes(_in, BEF_E + PEM_STRING_PKCS8);
         org.bouncycastle.asn1.pkcs.EncryptedPrivateKeyInfo eIn =
             new org.bouncycastle.asn1.pkcs.EncryptedPrivateKeyInfo(
                 (ASN1Sequence) new ASN1InputStream(bytes).readObject());
         AlgorithmIdentifier algId = eIn.getEncryptionAlgorithm();
         PrivateKey privKey;
         if (algId.getAlgorithm().toString().equals("1.2.840.113549.1.5.13")) { // PBES2
           privKey = derivePrivateKeyPBES2(eIn, algId, password);
         } else {
           privKey = derivePrivateKeyPBES1(eIn, algId, password);
         }
         return new KeyPair(null, privKey);
       } catch (Exception e) {
         throw new IOException("problem creating private key: " + e.toString());
       }
     }
   }
   return null;
 }
  public GenericKey generateUnwrappedKey(
      AlgorithmIdentifier encryptedKeyAlgorithm, byte[] encryptedKey) throws OperatorException {
    try {
      Key sKey = null;

      Cipher keyCipher =
          helper.createAsymmetricWrapper(this.getAlgorithmIdentifier().getAlgorithm());

      try {
        keyCipher.init(Cipher.UNWRAP_MODE, privKey);
        sKey =
            keyCipher.unwrap(
                encryptedKey, encryptedKeyAlgorithm.getAlgorithm().getId(), Cipher.SECRET_KEY);
      } catch (GeneralSecurityException e) {
      } catch (IllegalStateException e) {
      } catch (UnsupportedOperationException e) {
      } catch (ProviderException e) {
      }

      // some providers do not support UNWRAP (this appears to be only for asymmetric algorithms)
      if (sKey == null) {
        keyCipher.init(Cipher.DECRYPT_MODE, privKey);
        sKey =
            new SecretKeySpec(
                keyCipher.doFinal(encryptedKey), encryptedKeyAlgorithm.getAlgorithm().getId());
      }

      return new GenericKey(sKey);
    } catch (InvalidKeyException e) {
      throw new OperatorException("key invalid: " + e.getMessage(), e);
    } catch (IllegalBlockSizeException e) {
      throw new OperatorException("illegal blocksize: " + e.getMessage(), e);
    } catch (BadPaddingException e) {
      throw new OperatorException("bad padding: " + e.getMessage(), e);
    }
  }
Esempio n. 10
0
  private static PrivateKey derivePrivateKeyPBES1(
      org.bouncycastle.asn1.pkcs.EncryptedPrivateKeyInfo eIn,
      AlgorithmIdentifier algId,
      char[] password)
      throws GeneralSecurityException {
    PKCS12PBEParams pkcs12Params = new PKCS12PBEParams((ASN1Sequence) algId.getParameters());
    PBEParameterSpec pbeParams =
        new PBEParameterSpec(pkcs12Params.getIV(), pkcs12Params.getIterations().intValue());

    String algorithm = ASN1Registry.o2a(algId.getAlgorithm());
    algorithm = (algorithm.split("-"))[0];
    Cipher cipher = OpenSSLReal.getCipherBC(algorithm); // need to use BC for PBEParameterSpec.

    SecretKeyFactory fact =
        OpenSSLReal.getSecretKeyFactoryBC(algorithm); // need to use BC for PKCS12PBEParams.
    SecretKey key = fact.generateSecret(new PBEKeySpec(password));

    cipher.init(Cipher.UNWRAP_MODE, key, pbeParams);
    // wrappedKeyAlgorithm is unknown ("")
    return (PrivateKey) cipher.unwrap(eIn.getEncryptedData(), "", Cipher.PRIVATE_KEY);
  }
  /**
   * Create a public key from the passed in SubjectPublicKeyInfo
   *
   * @param keyInfo the SubjectPublicKeyInfo containing the key data
   * @return the appropriate key parameter
   * @throws IOException on an error decoding the key
   */
  public static AsymmetricKeyParameter createKey(SubjectPublicKeyInfo keyInfo) throws IOException {
    AlgorithmIdentifier algId = keyInfo.getAlgorithm();

    if (algId.getAlgorithm().equals(PKCSObjectIdentifiers.rsaEncryption)
        || algId.getAlgorithm().equals(X509ObjectIdentifiers.id_ea_rsa)) {
      RSAPublicKey pubKey = RSAPublicKey.getInstance(keyInfo.parsePublicKey());

      return new RSAKeyParameters(false, pubKey.getModulus(), pubKey.getPublicExponent());
    } else if (algId.getAlgorithm().equals(X9ObjectIdentifiers.dhpublicnumber)) {
      DHPublicKey dhPublicKey = DHPublicKey.getInstance(keyInfo.parsePublicKey());

      BigInteger y = dhPublicKey.getY().getValue();

      DHDomainParameters dhParams = DHDomainParameters.getInstance(algId.getParameters());

      BigInteger p = dhParams.getP().getValue();
      BigInteger g = dhParams.getG().getValue();
      BigInteger q = dhParams.getQ().getValue();

      BigInteger j = null;
      if (dhParams.getJ() != null) {
        j = dhParams.getJ().getValue();
      }

      DHValidationParameters validation = null;
      DHValidationParms dhValidationParms = dhParams.getValidationParms();
      if (dhValidationParms != null) {
        byte[] seed = dhValidationParms.getSeed().getBytes();
        BigInteger pgenCounter = dhValidationParms.getPgenCounter().getValue();

        // TODO Check pgenCounter size?

        validation = new DHValidationParameters(seed, pgenCounter.intValue());
      }

      return new DHPublicKeyParameters(y, new DHParameters(p, g, q, j, validation));
    } else if (algId.getAlgorithm().equals(PKCSObjectIdentifiers.dhKeyAgreement)) {
      DHParameter params = DHParameter.getInstance(algId.getParameters());
      ASN1Integer derY = (ASN1Integer) keyInfo.parsePublicKey();

      BigInteger lVal = params.getL();
      int l = lVal == null ? 0 : lVal.intValue();
      DHParameters dhParams = new DHParameters(params.getP(), params.getG(), null, l);

      return new DHPublicKeyParameters(derY.getValue(), dhParams);
    }
    // BEGIN android-removed
    // else if (algId.getAlgorithm().equals(OIWObjectIdentifiers.elGamalAlgorithm))
    // {
    //     ElGamalParameter params = new ElGamalParameter((ASN1Sequence)algId.getParameters());
    //     ASN1Integer derY = (ASN1Integer)keyInfo.parsePublicKey();
    //
    //     return new ElGamalPublicKeyParameters(derY.getValue(), new ElGamalParameters(
    //         params.getP(), params.getG()));
    // }
    // END android-removed
    else if (algId.getAlgorithm().equals(X9ObjectIdentifiers.id_dsa)
        || algId.getAlgorithm().equals(OIWObjectIdentifiers.dsaWithSHA1)) {
      ASN1Integer derY = (ASN1Integer) keyInfo.parsePublicKey();
      ASN1Encodable de = algId.getParameters();

      DSAParameters parameters = null;
      if (de != null) {
        DSAParameter params = DSAParameter.getInstance(de.toASN1Primitive());
        parameters = new DSAParameters(params.getP(), params.getQ(), params.getG());
      }

      return new DSAPublicKeyParameters(derY.getValue(), parameters);
    } else if (algId.getAlgorithm().equals(X9ObjectIdentifiers.id_ecPublicKey)) {
      X962Parameters params = X962Parameters.getInstance(algId.getParameters());

      X9ECParameters x9;
      if (params.isNamedCurve()) {
        ASN1ObjectIdentifier oid = (ASN1ObjectIdentifier) params.getParameters();
        x9 = ECNamedCurveTable.getByOID(oid);
      } else {
        x9 = X9ECParameters.getInstance(params.getParameters());
      }

      ASN1OctetString key = new DEROctetString(keyInfo.getPublicKeyData().getBytes());
      X9ECPoint derQ = new X9ECPoint(x9.getCurve(), key);

      // TODO We lose any named parameters here

      ECDomainParameters dParams =
          new ECDomainParameters(x9.getCurve(), x9.getG(), x9.getN(), x9.getH(), x9.getSeed());

      return new ECPublicKeyParameters(derQ.getPoint(), dParams);
    } else {
      throw new RuntimeException("algorithm identifier in key not recognised");
    }
  }