Ejemplo n.º 1
0
    private static byte[] convertPassword(int type, PBEKeySpec keySpec) {
      byte[] key;

      if (type == PKCS12) {
        key = PBEParametersGenerator.PKCS12PasswordToBytes(keySpec.getPassword());
      } else if (type == PKCS5S2_UTF8 || type == PKCS5S1_UTF8) {
        key = PBEParametersGenerator.PKCS5PasswordToUTF8Bytes(keySpec.getPassword());
      } else {
        key = PBEParametersGenerator.PKCS5PasswordToBytes(keySpec.getPassword());
      }
      return 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());
  }