Esempio n. 1
0
  public SignerInfo(ASN1Sequence seq) {
    Enumeration e = seq.getObjects();

    version = (DERInteger) e.nextElement();
    issuerAndSerialNumber = IssuerAndSerialNumber.getInstance(e.nextElement());
    digAlgorithm = AlgorithmIdentifier.getInstance(e.nextElement());

    Object obj = e.nextElement();

    if (obj instanceof ASN1TaggedObject) {
      authenticatedAttributes = ASN1Set.getInstance((ASN1TaggedObject) obj, false);

      digEncryptionAlgorithm = AlgorithmIdentifier.getInstance(e.nextElement());
    } else {
      authenticatedAttributes = null;
      digEncryptionAlgorithm = AlgorithmIdentifier.getInstance(obj);
    }

    encryptedDigest = DEROctetString.getInstance(e.nextElement());

    if (e.hasMoreElements()) {
      unauthenticatedAttributes = ASN1Set.getInstance((ASN1TaggedObject) e.nextElement(), false);
    } else {
      unauthenticatedAttributes = null;
    }
  }
  /**
   * decrypt the content and return an input stream.
   *
   * @deprecated use getContentStream(Recipient)
   */
  public CMSTypedStream getContentStream(Key key, Provider prov) throws CMSException {
    try {
      CMSEnvelopedHelper helper = CMSEnvelopedHelper.INSTANCE;
      AlgorithmIdentifier kekAlg =
          AlgorithmIdentifier.getInstance(info.getKeyEncryptionAlgorithm());
      ASN1Sequence kekAlgParams = (ASN1Sequence) kekAlg.getParameters();
      String kekAlgName = DERObjectIdentifier.getInstance(kekAlgParams.getObjectAt(0)).getId();
      String wrapAlgName = helper.getRFC3211WrapperName(kekAlgName);

      Cipher keyCipher = helper.createSymmetricCipher(wrapAlgName, prov);
      IvParameterSpec ivSpec =
          new IvParameterSpec(ASN1OctetString.getInstance(kekAlgParams.getObjectAt(1)).getOctets());
      keyCipher.init(
          Cipher.UNWRAP_MODE,
          new SecretKeySpec(((CMSPBEKey) key).getEncoded(kekAlgName), kekAlgName),
          ivSpec);

      Key sKey =
          keyCipher.unwrap(
              info.getEncryptedKey().getOctets(), getContentAlgorithmName(), Cipher.SECRET_KEY);

      return getContentFromSessionKey(sKey, prov);
    } catch (NoSuchAlgorithmException e) {
      throw new CMSException("can't find algorithm.", e);
    } catch (InvalidKeyException e) {
      throw new CMSException("key invalid in message.", e);
    } catch (NoSuchPaddingException e) {
      throw new CMSException("required padding not supported.", e);
    } catch (InvalidAlgorithmParameterException e) {
      throw new CMSException("invalid iv.", e);
    }
  }
Esempio n. 3
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;
  }
  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());
  }
  @Override
  public PasswordBasedCipher getInstance(boolean forEncryption, byte[] password, byte[] encoded) {
    ASN1Sequence seq = ASN1Sequence.getInstance(encoded);
    AlgorithmIdentifier alg = getPBES2AlgorithmIdentifier(seq);

    PBES2Parameters params = PBES2Parameters.getInstance(alg.getParameters());
    PasswordBasedCipherFactory pbecf = getPBES2CipherFactory(params.getEncryptionScheme());
    PasswordBasedCipher cipher = getBcPBES2PasswordBasedCipher(pbecf, forEncryption, password, seq);

    if (cipher != null) {
      return cipher;
    }
    return pbecf.getInstance(forEncryption, password, encoded);
  }
Esempio n. 7
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;
 }
 /** return the signature/encryption algorithm parameters, or null if there aren't any. */
 public byte[] getEncryptionAlgParams() {
   try {
     return encodeObj(encryptionAlgorithm.getParameters());
   } catch (Exception e) {
     throw new RuntimeException("exception getting encryption parameters " + e);
   }
 }
 /** return the signature parameters, or null if there aren't any. */
 public byte[] getDigestAlgParams() {
   try {
     return encodeObj(digestAlgorithm.getParameters());
   } catch (Exception e) {
     throw new RuntimeException("exception getting digest parameters " + e);
   }
 }
 public EncryptedContentInfo(ASN1Sequence seq) {
   contentType = (DERObjectIdentifier) seq.getObjectAt(0);
   contentEncryptionAlgorithm = AlgorithmIdentifier.getInstance(seq.getObjectAt(1));
   if (seq.size() > 2) {
     encryptedContent = ASN1OctetString.getInstance((ASN1TaggedObject) seq.getObjectAt(2), false);
   }
 }
Esempio n. 11
0
  private static PrivateKey derivePrivateKeyPBES2(
      org.bouncycastle.asn1.pkcs.EncryptedPrivateKeyInfo eIn,
      AlgorithmIdentifier algId,
      char[] password)
      throws GeneralSecurityException, InvalidCipherTextException {
    PBES2Parameters pbeParams = new PBES2Parameters((ASN1Sequence) algId.getParameters());
    CipherParameters cipherParams = extractPBES2CipherParams(password, pbeParams);

    EncryptionScheme scheme = pbeParams.getEncryptionScheme();
    BufferedBlockCipher cipher;
    if (scheme.getAlgorithm().equals(PKCSObjectIdentifiers.RC2_CBC)) {
      RC2CBCParameter rc2Params = new RC2CBCParameter((ASN1Sequence) scheme.getObject());
      byte[] iv = rc2Params.getIV();
      CipherParameters param = new ParametersWithIV(cipherParams, iv);
      cipher = new PaddedBufferedBlockCipher(new CBCBlockCipher(new RC2Engine()));
      cipher.init(false, param);
    } else {
      byte[] iv = ((ASN1OctetString) scheme.getObject()).getOctets();
      CipherParameters param = new ParametersWithIV(cipherParams, iv);
      cipher = new PaddedBufferedBlockCipher(new CBCBlockCipher(new DESedeEngine()));
      cipher.init(false, param);
    }

    byte[] data = eIn.getEncryptedData();
    byte[] out = new byte[cipher.getOutputSize(data.length)];
    int len = cipher.processBytes(data, 0, data.length, out, 0);
    len += cipher.doFinal(out, len);
    byte[] pkcs8 = new byte[len];
    System.arraycopy(out, 0, pkcs8, 0, len);
    KeyFactory fact = KeyFactory.getInstance("RSA"); // It seems to work for both RSA and DSA.
    return fact.generatePrivate(new PKCS8EncodedKeySpec(pkcs8));
  }
Esempio n. 12
0
  /**
   * EncryptedContentInfo ::= SEQUENCE { contentType ContentType, contentEncryptionAlgorithm
   * ContentEncryptionAlgorithmIdentifier, encryptedContent [0] IMPLICIT EncryptedContent OPTIONAL }
   *
   * <p>EncryptedContent ::= OCTET STRING
   */
  public static EncContent fromASN1(ASN1Encodable content) {
    ASN1Sequence sequence = (ASN1Sequence) content;
    ASN1ObjectIdentifier contentType = (ASN1ObjectIdentifier) (sequence.getObjectAt(0));
    int nid = ASN1Registry.obj2nid(contentType);

    EncContent ec = new EncContent();
    ec.setContentType(nid);
    ec.setAlgorithm(AlgorithmIdentifier.getInstance(sequence.getObjectAt(1)));
    if (sequence.size() > 2
        && sequence.getObjectAt(2) instanceof ASN1TaggedObject
        && ((ASN1TaggedObject) (sequence.getObjectAt(2))).getTagNo() == 0) {
      ASN1Encodable ee = ((ASN1TaggedObject) (sequence.getObjectAt(2))).getObject();
      if (ee instanceof ASN1Sequence && ((ASN1Sequence) ee).size() > 0) {
        ByteList combinedOctets = new ByteList();
        Enumeration enm = ((ASN1Sequence) ee).getObjects();
        while (enm.hasMoreElements()) {
          byte[] octets = ((ASN1OctetString) enm.nextElement()).getOctets();
          combinedOctets.append(octets);
        }
        ec.setEncData(new DEROctetString(combinedOctets.bytes()));
      } else {
        ec.setEncData((ASN1OctetString) ee);
      }
    }
    return ec;
  }
Esempio n. 13
0
  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. 14
0
  /**
   *
   *
   * <pre>
   *  RSAES-OAEP-params ::= SEQUENCE {
   *     hashAlgorithm      [0] OAEP-PSSDigestAlgorithms     DEFAULT sha1,
   *     maskGenAlgorithm   [1] PKCS1MGFAlgorithms  DEFAULT mgf1SHA1,
   *     pSourceAlgorithm   [2] PKCS1PSourceAlgorithms  DEFAULT pSpecifiedEmpty
   *   }
   *
   *   OAEP-PSSDigestAlgorithms    ALGORITHM-IDENTIFIER ::= {
   *     { OID id-sha1 PARAMETERS NULL   }|
   *     { OID id-sha256 PARAMETERS NULL }|
   *     { OID id-sha384 PARAMETERS NULL }|
   *     { OID id-sha512 PARAMETERS NULL },
   *     ...  -- Allows for future expansion --
   *   }
   *   PKCS1MGFAlgorithms    ALGORITHM-IDENTIFIER ::= {
   *     { OID id-mgf1 PARAMETERS OAEP-PSSDigestAlgorithms },
   *    ...  -- Allows for future expansion --
   *   }
   *   PKCS1PSourceAlgorithms    ALGORITHM-IDENTIFIER ::= {
   *     { OID id-pSpecified PARAMETERS OCTET STRING },
   *     ...  -- Allows for future expansion --
   *  }
   * </pre>
   *
   * @return the asn1 primitive representing the parameters.
   */
  public ASN1Primitive toASN1Primitive() {
    ASN1EncodableVector v = new ASN1EncodableVector();

    if (!hashAlgorithm.equals(DEFAULT_HASH_ALGORITHM)) {
      v.add(new DERTaggedObject(true, 0, hashAlgorithm));
    }

    if (!maskGenAlgorithm.equals(DEFAULT_MASK_GEN_FUNCTION)) {
      v.add(new DERTaggedObject(true, 1, maskGenAlgorithm));
    }

    if (!pSourceAlgorithm.equals(DEFAULT_P_SOURCE_ALGORITHM)) {
      v.add(new DERTaggedObject(true, 2, pSourceAlgorithm));
    }

    return new DERSequence(v);
  }
Esempio n. 15
0
  public static byte[] getEncoded(final AlgorithmIdentifier algorithmIdentifier)
      throws DSSException {

    try {
      return algorithmIdentifier.getEncoded(ASN1Encoding.DER);
    } catch (IOException e) {
      throw new DSSException(e);
    }
  }
Esempio n. 16
0
 public ASN1Encodable asASN1() {
   ASN1EncodableVector vector = new ASN1EncodableVector();
   vector.add(ASN1Registry.nid2obj(contentType).toASN1Primitive());
   vector.add(algorithm.toASN1Primitive());
   if (encData != null) {
     vector.add(new DERTaggedObject(false, 0, encData));
   }
   return new DLSequence(vector);
 }
 private KeyTransRecipientInfo computeRecipientInfo(X509Certificate x509certificate, byte[] abyte0)
     throws GeneralSecurityException, IOException {
   ASN1InputStream asn1inputstream =
       new ASN1InputStream(new ByteArrayInputStream(x509certificate.getTBSCertificate()));
   TBSCertificateStructure tbscertificatestructure =
       TBSCertificateStructure.getInstance(asn1inputstream.readObject());
   AlgorithmIdentifier algorithmidentifier =
       tbscertificatestructure.getSubjectPublicKeyInfo().getAlgorithmId();
   IssuerAndSerialNumber issuerandserialnumber =
       new IssuerAndSerialNumber(
           tbscertificatestructure.getIssuer(),
           tbscertificatestructure.getSerialNumber().getValue());
   Cipher cipher = Cipher.getInstance(algorithmidentifier.getObjectId().getId());
   cipher.init(1, x509certificate.getPublicKey());
   DEROctetString deroctetstring = new DEROctetString(cipher.doFinal(abyte0));
   RecipientIdentifier recipId = new RecipientIdentifier(issuerandserialnumber);
   return new KeyTransRecipientInfo(recipId, algorithmidentifier, deroctetstring);
 }
Esempio n. 18
0
 @Override
 public String toString() {
   return "#<EncContent contentType="
       + contentType
       + " algorithm="
       + (algorithm == null ? "null" : ASN1Registry.o2a(algorithm.getAlgorithm()))
       + " content="
       + encData
       + ">";
 }
Esempio n. 19
0
  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. 20
0
  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;
  }
Esempio n. 21
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);
  }
  protected RecipientOperator getRecipientOperator(Recipient recipient)
      throws CMSException, IOException {
    PasswordRecipient pbeRecipient = (PasswordRecipient) recipient;
    AlgorithmIdentifier kekAlg = AlgorithmIdentifier.getInstance(info.getKeyEncryptionAlgorithm());
    ASN1Sequence kekAlgParams = (ASN1Sequence) kekAlg.getParameters();
    DERObjectIdentifier kekAlgName = DERObjectIdentifier.getInstance(kekAlgParams.getObjectAt(0));
    PBKDF2Params params =
        PBKDF2Params.getInstance(info.getKeyDerivationAlgorithm().getParameters());

    byte[] derivedKey;
    int keySize = ((Integer) KEYSIZES.get(kekAlgName)).intValue();

    if (pbeRecipient.getPasswordConversionScheme() == PasswordRecipient.PKCS5_SCHEME2) {
      PKCS5S2ParametersGenerator gen = new PKCS5S2ParametersGenerator();

      gen.init(
          PBEParametersGenerator.PKCS5PasswordToBytes(pbeRecipient.getPassword()),
          params.getSalt(),
          params.getIterationCount().intValue());

      derivedKey = ((KeyParameter) gen.generateDerivedParameters(keySize)).getKey();
    } else {
      PKCS5S2ParametersGenerator gen = new PKCS5S2ParametersGenerator();

      gen.init(
          PBEParametersGenerator.PKCS5PasswordToUTF8Bytes(pbeRecipient.getPassword()),
          params.getSalt(),
          params.getIterationCount().intValue());

      derivedKey = ((KeyParameter) gen.generateDerivedParameters(keySize)).getKey();
    }

    return pbeRecipient.getRecipientOperator(
        AlgorithmIdentifier.getInstance(kekAlg.getParameters()),
        messageAlgorithm,
        derivedKey,
        info.getEncryptedKey().getOctets());
  }
Esempio n. 23
0
  private ECCCMSSharedInfo(ASN1Sequence seq) {
    this.keyInfo = AlgorithmIdentifier.getInstance(seq.getObjectAt(0));

    if (seq.size() == 2) {
      this.entityUInfo = null;
      this.suppPubInfo =
          ASN1OctetString.getInstance((ASN1TaggedObject) seq.getObjectAt(1), true).getOctets();
    } else {
      this.entityUInfo =
          ASN1OctetString.getInstance((ASN1TaggedObject) seq.getObjectAt(1), true).getOctets();
      this.suppPubInfo =
          ASN1OctetString.getInstance((ASN1TaggedObject) seq.getObjectAt(2), true).getOctets();
    }
  }
Esempio n. 24
0
  /**
   * @deprecated use getInstance()
   * @param seq
   */
  public RSAESOAEPparams(ASN1Sequence seq) {
    hashAlgorithm = DEFAULT_HASH_ALGORITHM;
    maskGenAlgorithm = DEFAULT_MASK_GEN_FUNCTION;
    pSourceAlgorithm = DEFAULT_P_SOURCE_ALGORITHM;

    for (int i = 0; i != seq.size(); i++) {
      ASN1TaggedObject o = (ASN1TaggedObject) seq.getObjectAt(i);

      switch (o.getTagNo()) {
        case 0:
          hashAlgorithm = AlgorithmIdentifier.getInstance(o, true);
          break;
        case 1:
          maskGenAlgorithm = AlgorithmIdentifier.getInstance(o, true);
          break;
        case 2:
          pSourceAlgorithm = AlgorithmIdentifier.getInstance(o, true);
          break;
        default:
          throw new IllegalArgumentException("unknown tag");
      }
    }
  }
  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. 26
0
  private PKIHeader(ASN1Sequence seq) {
    Enumeration en = seq.getObjects();

    pvno = DERInteger.getInstance(en.nextElement());
    sender = GeneralName.getInstance(en.nextElement());
    recipient = GeneralName.getInstance(en.nextElement());

    while (en.hasMoreElements()) {
      ASN1TaggedObject tObj = (ASN1TaggedObject) en.nextElement();

      switch (tObj.getTagNo()) {
        case 0:
          messageTime = DERGeneralizedTime.getInstance(tObj, true);
          break;
        case 1:
          protectionAlg = AlgorithmIdentifier.getInstance(tObj, true);
          break;
        case 2:
          senderKID = ASN1OctetString.getInstance(tObj, true);
          break;
        case 3:
          recipKID = ASN1OctetString.getInstance(tObj, true);
          break;
        case 4:
          transactionID = ASN1OctetString.getInstance(tObj, true);
          break;
        case 5:
          senderNonce = ASN1OctetString.getInstance(tObj, true);
          break;
        case 6:
          recipNonce = ASN1OctetString.getInstance(tObj, true);
          break;
        case 7:
          freeText = PKIFreeText.getInstance(tObj, true);
          break;
        case 8:
          generalInfo = ASN1Sequence.getInstance(tObj, true);
          break;
        default:
          throw new IllegalArgumentException("unknown tag number: " + tObj.getTagNo());
      }
    }
  }
Esempio n. 27
0
  /** @deprecated */
  private boolean verifyDigest(byte[] digest, PublicKey key, byte[] signature, Provider sigProvider)
      throws NoSuchAlgorithmException, CMSException {
    String encName = CMSSignedHelper.INSTANCE.getEncryptionAlgName(this.getEncryptionAlgOID());

    try {
      if (encName.equals("RSA")) {
        Cipher c =
            CMSEnvelopedHelper.INSTANCE.createAsymmetricCipher("RSA/ECB/PKCS1Padding", sigProvider);

        c.init(Cipher.DECRYPT_MODE, key);

        DigestInfo digInfo = derDecode(c.doFinal(signature));

        if (!digInfo.getAlgorithmId().getObjectId().equals(digestAlgorithm.getObjectId())) {
          return false;
        }

        if (!isNull(digInfo.getAlgorithmId().getParameters())) {
          return false;
        }

        byte[] sigHash = digInfo.getDigest();

        return Arrays.constantTimeAreEqual(digest, sigHash);
      } else if (encName.equals("DSA")) {
        Signature sig = CMSSignedHelper.INSTANCE.getSignatureInstance("NONEwithDSA", sigProvider);

        sig.initVerify(key);

        sig.update(digest);

        return sig.verify(signature);
      } else {
        throw new CMSException("algorithm: " + encName + " not supported in base signatures.");
      }
    } catch (GeneralSecurityException e) {
      throw new CMSException("Exception processing signature: " + e, e);
    } catch (IOException e) {
      throw new CMSException("Exception decoding signature: " + e, e);
    }
  }
Esempio n. 28
0
  public OOBCertHash(ASN1Sequence seq) {
    Enumeration e = seq.getObjects();

    while (e.hasMoreElements()) {
      Object obj = e.nextElement();

      if (obj instanceof ASN1TaggedObject) {
        ASN1TaggedObject tagObj = (ASN1TaggedObject) obj;

        switch (tagObj.getTagNo()) {
          case 0:
            hashAlg = AlgorithmIdentifier.getInstance(tagObj.getObject());
            break;
          case 1:
            certId = CertId.getInstance(tagObj.getObject());
            break;
        }
      } else {
        hashVal = DERBitString.getInstance(obj);

        break;
      }
    }
  }
Esempio n. 29
0
 /** return the object identifier for the signature. */
 public String getEncryptionAlgOID() {
   return encryptionAlgorithm.getObjectId().getId();
 }
  /**
   * 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");
    }
  }