Java Code Examples for java.security.spec.PSSParameterSpec#getMGFParameters()

The following examples show how to use java.security.spec.PSSParameterSpec#getMGFParameters() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: PSSParameters.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
@Override
protected void engineInit(AlgorithmParameterSpec paramSpec)
        throws InvalidParameterSpecException {
    if (!(paramSpec instanceof PSSParameterSpec)) {
        throw new InvalidParameterSpecException
            ("Inappropriate parameter specification");
    }
    PSSParameterSpec spec = (PSSParameterSpec) paramSpec;

    String mgfName = spec.getMGFAlgorithm();
    if (!spec.getMGFAlgorithm().equalsIgnoreCase("MGF1")) {
        throw new InvalidParameterSpecException("Unsupported mgf " +
            mgfName + "; MGF1 only");
    }
    AlgorithmParameterSpec mgfSpec = spec.getMGFParameters();
    if (!(mgfSpec instanceof MGF1ParameterSpec)) {
        throw new InvalidParameterSpecException("Inappropriate mgf " +
            "parameters; non-null MGF1ParameterSpec only");
    }
    this.spec = spec;
}
 
Example 2
Source File: AlgorithmParametersSpi.java    From ripple-lib-java with ISC License 6 votes vote down vote up
/**
 * Return the PKCS#1 ASN.1 structure RSASSA-PSS-params.
 */
protected byte[] engineGetEncoded() 
    throws IOException
{
    PSSParameterSpec pssSpec = currentSpec;
    AlgorithmIdentifier hashAlgorithm = new AlgorithmIdentifier(
                                        DigestFactory.getOID(pssSpec.getDigestAlgorithm()),
                                        DERNull.INSTANCE);
    MGF1ParameterSpec mgfSpec = (MGF1ParameterSpec)pssSpec.getMGFParameters();
    AlgorithmIdentifier maskGenAlgorithm = new AlgorithmIdentifier(
                                        PKCSObjectIdentifiers.id_mgf1,
                                        new AlgorithmIdentifier(DigestFactory.getOID(mgfSpec.getDigestAlgorithm()), DERNull.INSTANCE));
    RSASSAPSSparams pssP = new RSASSAPSSparams(hashAlgorithm, maskGenAlgorithm, new ASN1Integer(pssSpec.getSaltLength()), new ASN1Integer(pssSpec.getTrailerField()));
    
    return pssP.getEncoded("DER");
}
 
Example 3
Source File: PSSParameters.java    From Bytecoder with Apache License 2.0 6 votes vote down vote up
@Override
protected void engineInit(AlgorithmParameterSpec paramSpec)
        throws InvalidParameterSpecException {
    if (!(paramSpec instanceof PSSParameterSpec)) {
        throw new InvalidParameterSpecException
            ("Inappropriate parameter specification");
    }
    PSSParameterSpec spec = (PSSParameterSpec) paramSpec;

    String mgfName = spec.getMGFAlgorithm();
    if (!spec.getMGFAlgorithm().equalsIgnoreCase("MGF1")) {
        throw new InvalidParameterSpecException("Unsupported mgf " +
            mgfName + "; MGF1 only");
    }
    AlgorithmParameterSpec mgfSpec = spec.getMGFParameters();
    if (!(mgfSpec instanceof MGF1ParameterSpec)) {
        throw new InvalidParameterSpecException("Inappropriate mgf " +
            "parameters; non-null MGF1ParameterSpec only");
    }
    this.spec = spec;
}
 
Example 4
Source File: AlgorithmParametersSpi.java    From RipplePower with Apache License 2.0 6 votes vote down vote up
/**
 * Return the PKCS#1 ASN.1 structure RSASSA-PSS-params.
 */
protected byte[] engineGetEncoded() 
    throws IOException
{
    PSSParameterSpec pssSpec = currentSpec;
    AlgorithmIdentifier hashAlgorithm = new AlgorithmIdentifier(
                                        DigestFactory.getOID(pssSpec.getDigestAlgorithm()),
                                        DERNull.INSTANCE);
    MGF1ParameterSpec mgfSpec = (MGF1ParameterSpec)pssSpec.getMGFParameters();
    AlgorithmIdentifier maskGenAlgorithm = new AlgorithmIdentifier(
                                        PKCSObjectIdentifiers.id_mgf1,
                                        new AlgorithmIdentifier(DigestFactory.getOID(mgfSpec.getDigestAlgorithm()), DERNull.INSTANCE));
    RSASSAPSSparams pssP = new RSASSAPSSparams(hashAlgorithm, maskGenAlgorithm, new ASN1Integer(pssSpec.getSaltLength()), new ASN1Integer(pssSpec.getTrailerField()));
    
    return pssP.getEncoded("DER");
}
 
Example 5
Source File: PSSParameters.java    From jdk8u_jdk with GNU General Public License v2.0 6 votes vote down vote up
@Override
protected void engineInit(AlgorithmParameterSpec paramSpec)
        throws InvalidParameterSpecException {
    if (!(paramSpec instanceof PSSParameterSpec)) {
        throw new InvalidParameterSpecException
            ("Inappropriate parameter specification");
    }
    PSSParameterSpec spec = (PSSParameterSpec) paramSpec;

    String mgfName = spec.getMGFAlgorithm();
    if (!spec.getMGFAlgorithm().equalsIgnoreCase("MGF1")) {
        throw new InvalidParameterSpecException("Unsupported mgf " +
            mgfName + "; MGF1 only");
    }
    AlgorithmParameterSpec mgfSpec = spec.getMGFParameters();
    if (!(mgfSpec instanceof MGF1ParameterSpec)) {
        throw new InvalidParameterSpecException("Inappropriate mgf " +
            "parameters; non-null MGF1ParameterSpec only");
    }
    this.spec = spec;
}
 
Example 6
Source File: PSSSignatureSpi.java    From ripple-lib-java with ISC License 4 votes vote down vote up
protected void engineSetParameter(
    AlgorithmParameterSpec params)
    throws InvalidParameterException
{
    if (params instanceof PSSParameterSpec)
    {
        PSSParameterSpec newParamSpec = (PSSParameterSpec)params;
        
        if (originalSpec != null)
        {
            if (!DigestFactory.isSameDigest(originalSpec.getDigestAlgorithm(), newParamSpec.getDigestAlgorithm()))
            {
                throw new InvalidParameterException("parameter must be using " + originalSpec.getDigestAlgorithm());
            }
        }
        if (!newParamSpec.getMGFAlgorithm().equalsIgnoreCase("MGF1") && !newParamSpec.getMGFAlgorithm().equals(PKCSObjectIdentifiers.id_mgf1.getId()))
        {
            throw new InvalidParameterException("unknown mask generation function specified");
        }
        
        if (!(newParamSpec.getMGFParameters() instanceof MGF1ParameterSpec))
        {
            throw new InvalidParameterException("unkown MGF parameters");
        }
        
        MGF1ParameterSpec mgfParams = (MGF1ParameterSpec)newParamSpec.getMGFParameters();
        
        if (!DigestFactory.isSameDigest(mgfParams.getDigestAlgorithm(), newParamSpec.getDigestAlgorithm()))
        {
            throw new InvalidParameterException("digest algorithm for MGF should be the same as for PSS parameters.");
        }
        
        Digest newDigest = DigestFactory.getDigest(mgfParams.getDigestAlgorithm());
        
        if (newDigest == null)
        {
            throw new InvalidParameterException("no match on MGF digest algorithm: "+ mgfParams.getDigestAlgorithm());
        }

        this.engineParams = null;
        this.paramSpec = newParamSpec;
        this.mgfDigest = newDigest;
        this.saltLength = paramSpec.getSaltLength();
        this.trailer = getTrailer(paramSpec.getTrailerField());

        setupContentDigest();
    }
    else
    {
        throw new InvalidParameterException("Only PSSParameterSpec supported");
    }
}
 
Example 7
Source File: RSAPSSSignature.java    From openjdk-jdk8u with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Utility method for checking the key PSS parameters against signature
 * PSS parameters.
 * Returns false if any of the digest/MGF algorithms and trailerField
 * values does not match or if the salt length in key parameters is
 * larger than the value in signature parameters.
 */
private static boolean isCompatible(AlgorithmParameterSpec keyParams,
        PSSParameterSpec sigParams) {
    if (keyParams == null) {
        // key with null PSS parameters means no restriction
        return true;
    }
    if (!(keyParams instanceof PSSParameterSpec)) {
        return false;
    }
    // nothing to compare yet, defer the check to when sigParams is set
    if (sigParams == null) {
        return true;
    }
    PSSParameterSpec pssKeyParams = (PSSParameterSpec) keyParams;
    // first check the salt length requirement
    if (pssKeyParams.getSaltLength() > sigParams.getSaltLength()) {
        return false;
    }

    // compare equality of the rest of fields based on DER encoding
    PSSParameterSpec keyParams2 =
        new PSSParameterSpec(pssKeyParams.getDigestAlgorithm(),
                pssKeyParams.getMGFAlgorithm(),
                pssKeyParams.getMGFParameters(),
                sigParams.getSaltLength(),
                pssKeyParams.getTrailerField());
    PSSParameters ap = new PSSParameters();
    // skip the JCA overhead
    try {
        ap.engineInit(keyParams2);
        byte[] encoded = ap.engineGetEncoded();
        ap.engineInit(sigParams);
        byte[] encoded2 = ap.engineGetEncoded();
        return Arrays.equals(encoded, encoded2);
    } catch (Exception e) {
        if (DEBUG) {
            e.printStackTrace();
        }
        return false;
    }
}
 
Example 8
Source File: P11RSAPSSSignatureSpi.java    From xipki with Apache License 2.0 4 votes vote down vote up
@Override
protected void engineSetParameter(AlgorithmParameterSpec params)
    throws InvalidParameterException {
  if (params instanceof PSSParameterSpec) {
    PSSParameterSpec newParamSpec = (PSSParameterSpec) params;

    if (originalSpec != null) {
      if (!DigestFactory.isSameDigest(originalSpec.getDigestAlgorithm(),
          newParamSpec.getDigestAlgorithm())) {
        throw new InvalidParameterException("parameter must be using "
            + originalSpec.getDigestAlgorithm());
      }
    }
    if (!newParamSpec.getMGFAlgorithm().equalsIgnoreCase("MGF1")
        && !newParamSpec.getMGFAlgorithm().equals(PKCSObjectIdentifiers.id_mgf1.getId())) {
      throw new InvalidParameterException("unknown mask generation function specified");
    }

    if (!(newParamSpec.getMGFParameters() instanceof MGF1ParameterSpec)) {
      throw new InvalidParameterException("unkown MGF parameters");
    }

    MGF1ParameterSpec mgfParams = (MGF1ParameterSpec) newParamSpec.getMGFParameters();

    if (!DigestFactory.isSameDigest(mgfParams.getDigestAlgorithm(),
        newParamSpec.getDigestAlgorithm())) {
      throw new InvalidParameterException(
          "digest algorithm for MGF should be the same as for PSS parameters.");
    }

    Digest newDigest = DigestFactory.getDigest(mgfParams.getDigestAlgorithm());

    if (newDigest == null) {
      throw new InvalidParameterException(
          "no match on MGF digest algorithm: " + mgfParams.getDigestAlgorithm());
    }

    this.engineParams = null;
    this.paramSpec = newParamSpec;
    this.mgfDigest = newDigest;
    this.saltLength = paramSpec.getSaltLength();
    this.trailer = getTrailer(paramSpec.getTrailerField());

    setupContentDigest();
  } else {
    throw new InvalidParameterException("only PSSParameterSpec supported");
  }
}
 
Example 9
Source File: PSSSignatureSpi.java    From RipplePower with Apache License 2.0 4 votes vote down vote up
protected void engineSetParameter(
    AlgorithmParameterSpec params)
    throws InvalidParameterException
{
    if (params instanceof PSSParameterSpec)
    {
        PSSParameterSpec newParamSpec = (PSSParameterSpec)params;
        
        if (originalSpec != null)
        {
            if (!DigestFactory.isSameDigest(originalSpec.getDigestAlgorithm(), newParamSpec.getDigestAlgorithm()))
            {
                throw new InvalidParameterException("parameter must be using " + originalSpec.getDigestAlgorithm());
            }
        }
        if (!newParamSpec.getMGFAlgorithm().equalsIgnoreCase("MGF1") && !newParamSpec.getMGFAlgorithm().equals(PKCSObjectIdentifiers.id_mgf1.getId()))
        {
            throw new InvalidParameterException("unknown mask generation function specified");
        }
        
        if (!(newParamSpec.getMGFParameters() instanceof MGF1ParameterSpec))
        {
            throw new InvalidParameterException("unkown MGF parameters");
        }
        
        MGF1ParameterSpec mgfParams = (MGF1ParameterSpec)newParamSpec.getMGFParameters();
        
        if (!DigestFactory.isSameDigest(mgfParams.getDigestAlgorithm(), newParamSpec.getDigestAlgorithm()))
        {
            throw new InvalidParameterException("digest algorithm for MGF should be the same as for PSS parameters.");
        }
        
        Digest newDigest = DigestFactory.getDigest(mgfParams.getDigestAlgorithm());
        
        if (newDigest == null)
        {
            throw new InvalidParameterException("no match on MGF digest algorithm: "+ mgfParams.getDigestAlgorithm());
        }

        this.engineParams = null;
        this.paramSpec = newParamSpec;
        this.mgfDigest = newDigest;
        this.saltLength = paramSpec.getSaltLength();
        this.trailer = getTrailer(paramSpec.getTrailerField());

        setupContentDigest();
    }
    else
    {
        throw new InvalidParameterException("Only PSSParameterSpec supported");
    }
}
 
Example 10
Source File: CSignature.java    From jdk8u_jdk with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Validate the specified Signature PSS parameters.
 */
private PSSParameterSpec validateSigParams(AlgorithmParameterSpec p)
        throws InvalidAlgorithmParameterException {

    if (p == null) {
        throw new InvalidAlgorithmParameterException
                ("Parameters cannot be null");
    }

    if (!(p instanceof PSSParameterSpec)) {
        throw new InvalidAlgorithmParameterException
                ("parameters must be type PSSParameterSpec");
    }

    // no need to validate again if same as current signature parameters
    PSSParameterSpec params = (PSSParameterSpec) p;
    if (params == this.pssParams) return params;

    // now sanity check the parameter values
    if (!(params.getMGFAlgorithm().equalsIgnoreCase("MGF1"))) {
        throw new InvalidAlgorithmParameterException("Only supports MGF1");

    }

    if (params.getTrailerField() != PSSParameterSpec.TRAILER_FIELD_BC) {
        throw new InvalidAlgorithmParameterException
                ("Only supports TrailerFieldBC(1)");
    }

    AlgorithmParameterSpec algSpec = params.getMGFParameters();
    if (!(algSpec instanceof MGF1ParameterSpec)) {
        throw new InvalidAlgorithmParameterException
                ("Only support MGF1ParameterSpec");
    }

    MGF1ParameterSpec mgfSpec = (MGF1ParameterSpec)algSpec;

    String msgHashAlg = params.getDigestAlgorithm()
            .toLowerCase(Locale.ROOT).replaceAll("-", "");
    if (msgHashAlg.equals("sha")) {
        msgHashAlg = "sha1";
    }
    String mgf1HashAlg = mgfSpec.getDigestAlgorithm()
            .toLowerCase(Locale.ROOT).replaceAll("-", "");
    if (mgf1HashAlg.equals("sha")) {
        mgf1HashAlg = "sha1";
    }

    if (!mgf1HashAlg.equals(msgHashAlg)) {
        throw new InvalidAlgorithmParameterException
                ("MGF1 hash must be the same as message hash");
    }

    return params;
}
 
Example 11
Source File: PSSParameters.java    From jdk8u_jdk with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Returns the encoding of a {@link PSSParameterSpec} object. This method
 * is used in this class and {@link AlgorithmId}.
 *
 * @param spec a {@code PSSParameterSpec} object
 * @return its DER encoding
 * @throws IOException if the name of a MessageDigest or MaskGenAlgorithm
 *          is unsupported
 */
public static byte[] getEncoded(PSSParameterSpec spec) throws IOException {

    AlgorithmParameterSpec mgfSpec = spec.getMGFParameters();
    if (!(mgfSpec instanceof MGF1ParameterSpec)) {
        throw new IOException("Cannot encode " + mgfSpec);
    }

    MGF1ParameterSpec mgf1Spec = (MGF1ParameterSpec)mgfSpec;

    DerOutputStream tmp = new DerOutputStream();
    DerOutputStream tmp2, tmp3;

    // MD
    AlgorithmId mdAlgId;
    try {
        mdAlgId = AlgorithmId.get(spec.getDigestAlgorithm());
    } catch (NoSuchAlgorithmException nsae) {
        throw new IOException("AlgorithmId " + spec.getDigestAlgorithm() +
                " impl not found");
    }
    if (!mdAlgId.getOID().equals(AlgorithmId.SHA_oid)) {
        tmp2 = new DerOutputStream();
        mdAlgId.derEncode(tmp2);
        tmp.write(DerValue.createTag(DerValue.TAG_CONTEXT, true, (byte) 0),
                tmp2);
    }

    // MGF
    AlgorithmId mgfDigestId;
    try {
        mgfDigestId = AlgorithmId.get(mgf1Spec.getDigestAlgorithm());
    } catch (NoSuchAlgorithmException nase) {
        throw new IOException("AlgorithmId " +
                mgf1Spec.getDigestAlgorithm() + " impl not found");
    }

    if (!mgfDigestId.getOID().equals(AlgorithmId.SHA_oid)) {
        tmp2 = new DerOutputStream();
        tmp2.putOID(AlgorithmId.mgf1_oid);
        mgfDigestId.encode(tmp2);
        tmp3 = new DerOutputStream();
        tmp3.write(DerValue.tag_Sequence, tmp2);
        tmp.write(DerValue.createTag(DerValue.TAG_CONTEXT, true, (byte) 1),
                tmp3);
    }

    // SaltLength
    if (spec.getSaltLength() != 20) {
        tmp2 = new DerOutputStream();
        tmp2.putInteger(spec.getSaltLength());
        tmp.write(DerValue.createTag(DerValue.TAG_CONTEXT, true, (byte) 2),
                tmp2);
    }

    // TrailerField
    if (spec.getTrailerField() != PSSParameterSpec.TRAILER_FIELD_BC) {
        tmp2 = new DerOutputStream();
        tmp2.putInteger(spec.getTrailerField());
        tmp.write(DerValue.createTag(DerValue.TAG_CONTEXT, true, (byte) 3),
                tmp2);
    }

    // Put all together under a SEQUENCE tag
    DerOutputStream out = new DerOutputStream();
    out.write(DerValue.tag_Sequence, tmp);
    return out.toByteArray();
}
 
Example 12
Source File: RSAPSSSignature.java    From jdk8u_jdk with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Utility method for checking the key PSS parameters against signature
 * PSS parameters.
 * Returns false if any of the digest/MGF algorithms and trailerField
 * values does not match or if the salt length in key parameters is
 * larger than the value in signature parameters.
 */
private static boolean isCompatible(AlgorithmParameterSpec keyParams,
        PSSParameterSpec sigParams) {
    if (keyParams == null) {
        // key with null PSS parameters means no restriction
        return true;
    }
    if (!(keyParams instanceof PSSParameterSpec)) {
        return false;
    }
    // nothing to compare yet, defer the check to when sigParams is set
    if (sigParams == null) {
        return true;
    }
    PSSParameterSpec pssKeyParams = (PSSParameterSpec) keyParams;
    // first check the salt length requirement
    if (pssKeyParams.getSaltLength() > sigParams.getSaltLength()) {
        return false;
    }

    // compare equality of the rest of fields based on DER encoding
    PSSParameterSpec keyParams2 =
        new PSSParameterSpec(pssKeyParams.getDigestAlgorithm(),
                pssKeyParams.getMGFAlgorithm(),
                pssKeyParams.getMGFParameters(),
                sigParams.getSaltLength(),
                pssKeyParams.getTrailerField());
    PSSParameters ap = new PSSParameters();
    // skip the JCA overhead
    try {
        ap.engineInit(keyParams2);
        byte[] encoded = ap.engineGetEncoded();
        ap.engineInit(sigParams);
        byte[] encoded2 = ap.engineGetEncoded();
        return Arrays.equals(encoded, encoded2);
    } catch (Exception e) {
        if (DEBUG) {
            e.printStackTrace();
        }
        return false;
    }
}
 
Example 13
Source File: RsaPssTest.java    From wycheproof with Apache License 2.0 4 votes vote down vote up
/**
 * Tests the default parameters used for a given algorithm name.
 *
 * @param algorithm the algorithm name for an RSA-PSS instance. (e.g. "SHA256WithRSAandMGF1")
 * @param expectedHash the hash algorithm expected for the given algorithm
 * @param expectedMgf the mask generation function expected for the given algorithm (e.g. "MGF1")
 * @param expectedMgfHash the hash algorithm exptected for the mask generation function
 * @param expectedSaltLength the expected salt length in bytes for the given algorithm
 * @param expectedTrailerField the expected value for the tailer field (e.g. 1 for 0xbc).
 */
protected void testDefaultForAlgorithm(
    String algorithm,
    String expectedHash,
    String expectedMgf,
    String expectedMgfHash,
    int expectedSaltLength,
    int expectedTrailerField) throws Exception {
  // An X509 encoded 2048-bit RSA public key.
  String pubKey =
      "30820122300d06092a864886f70d01010105000382010f003082010a02820101"
          + "00bdf90898577911c71c4d9520c5f75108548e8dfd389afdbf9c997769b8594e"
          + "7dc51c6a1b88d1670ec4bb03fa550ba6a13d02c430bfe88ae4e2075163017f4d"
          + "8926ce2e46e068e88962f38112fc2dbd033e84e648d4a816c0f5bd89cadba0b4"
          + "d6cac01832103061cbb704ebacd895def6cff9d988c5395f2169a6807207333d"
          + "569150d7f569f7ebf4718ddbfa2cdbde4d82a9d5d8caeb467f71bfc0099b0625"
          + "a59d2bad12e3ff48f2fd50867b89f5f876ce6c126ced25f28b1996ee21142235"
          + "fb3aef9fe58d9e4ef6e4922711a3bbcd8adcfe868481fd1aa9c13e5c658f5172"
          + "617204314665092b4d8dca1b05dc7f4ecd7578b61edeb949275be8751a5a1fab"
          + "c30203010001";
  KeyFactory kf;
  kf = KeyFactory.getInstance("RSA");
  X509EncodedKeySpec x509keySpec = new X509EncodedKeySpec(TestUtil.hexToBytes(pubKey));
  PublicKey key = kf.generatePublic(x509keySpec);
  Signature verifier;
  try {
    verifier = Signature.getInstance(algorithm);
    verifier.initVerify(key);
  } catch (NoSuchAlgorithmException ex) {
    System.out.println("Unsupported algorithm:" + algorithm);
    return;
  }
  AlgorithmParameters params = verifier.getParameters();
  if (params == null) {
    // No defaults are specified. This is a good choice since this avoid
    // incompatible implementations.
    return;
  }
  PSSParameterSpec pssParams = params.getParameterSpec(PSSParameterSpec.class);
  assertEquals("digestAlgorithm", expectedHash, pssParams.getDigestAlgorithm());
  assertEquals("mgfAlgorithm", expectedMgf, pssParams.getMGFAlgorithm());
  assertEquals("saltLength", expectedSaltLength, pssParams.getSaltLength());
  assertEquals("trailerField", expectedTrailerField, pssParams.getTrailerField());
  if (expectedMgf.equals("MGF1")) {
    MGF1ParameterSpec mgf1Params = (MGF1ParameterSpec) pssParams.getMGFParameters();
    assertEquals("mgf1 digestAlgorithm", expectedMgfHash, mgf1Params.getDigestAlgorithm());
  }
}
 
Example 14
Source File: PSSParameters.java    From Bytecoder with Apache License 2.0 4 votes vote down vote up
/**
 * Returns the encoding of a {@link PSSParameterSpec} object. This method
 * is used in this class and {@link AlgorithmId}.
 *
 * @param spec a {@code PSSParameterSpec} object
 * @return its DER encoding
 * @throws IOException if the name of a MessageDigest or MaskGenAlgorithm
 *          is unsupported
 */
public static byte[] getEncoded(PSSParameterSpec spec) throws IOException {

    AlgorithmParameterSpec mgfSpec = spec.getMGFParameters();
    if (!(mgfSpec instanceof MGF1ParameterSpec)) {
        throw new IOException("Cannot encode " + mgfSpec);
    }

    MGF1ParameterSpec mgf1Spec = (MGF1ParameterSpec)mgfSpec;

    DerOutputStream tmp = new DerOutputStream();
    DerOutputStream tmp2, tmp3;

    // MD
    AlgorithmId mdAlgId;
    try {
        mdAlgId = AlgorithmId.get(spec.getDigestAlgorithm());
    } catch (NoSuchAlgorithmException nsae) {
        throw new IOException("AlgorithmId " + spec.getDigestAlgorithm() +
                " impl not found");
    }
    if (!mdAlgId.getOID().equals(AlgorithmId.SHA_oid)) {
        tmp2 = new DerOutputStream();
        mdAlgId.derEncode(tmp2);
        tmp.write(DerValue.createTag(DerValue.TAG_CONTEXT, true, (byte) 0),
                tmp2);
    }

    // MGF
    AlgorithmId mgfDigestId;
    try {
        mgfDigestId = AlgorithmId.get(mgf1Spec.getDigestAlgorithm());
    } catch (NoSuchAlgorithmException nase) {
        throw new IOException("AlgorithmId " +
                mgf1Spec.getDigestAlgorithm() + " impl not found");
    }

    if (!mgfDigestId.getOID().equals(AlgorithmId.SHA_oid)) {
        tmp2 = new DerOutputStream();
        tmp2.putOID(AlgorithmId.mgf1_oid);
        mgfDigestId.encode(tmp2);
        tmp3 = new DerOutputStream();
        tmp3.write(DerValue.tag_Sequence, tmp2);
        tmp.write(DerValue.createTag(DerValue.TAG_CONTEXT, true, (byte) 1),
                tmp3);
    }

    // SaltLength
    if (spec.getSaltLength() != 20) {
        tmp2 = new DerOutputStream();
        tmp2.putInteger(spec.getSaltLength());
        tmp.write(DerValue.createTag(DerValue.TAG_CONTEXT, true, (byte) 2),
                tmp2);
    }

    // TrailerField
    if (spec.getTrailerField() != PSSParameterSpec.TRAILER_FIELD_BC) {
        tmp2 = new DerOutputStream();
        tmp2.putInteger(spec.getTrailerField());
        tmp.write(DerValue.createTag(DerValue.TAG_CONTEXT, true, (byte) 3),
                tmp2);
    }

    // Put all together under a SEQUENCE tag
    DerOutputStream out = new DerOutputStream();
    out.write(DerValue.tag_Sequence, tmp);
    return out.toByteArray();
}
 
Example 15
Source File: RSAPSSSignature.java    From Bytecoder with Apache License 2.0 4 votes vote down vote up
/**
 * Utility method for checking the key PSS parameters against signature
 * PSS parameters.
 * Returns false if any of the digest/MGF algorithms and trailerField
 * values does not match or if the salt length in key parameters is
 * larger than the value in signature parameters.
 */
private static boolean isCompatible(AlgorithmParameterSpec keyParams,
        PSSParameterSpec sigParams) {
    if (keyParams == null) {
        // key with null PSS parameters means no restriction
        return true;
    }
    if (!(keyParams instanceof PSSParameterSpec)) {
        return false;
    }
    // nothing to compare yet, defer the check to when sigParams is set
    if (sigParams == null) {
        return true;
    }
    PSSParameterSpec pssKeyParams = (PSSParameterSpec) keyParams;
    // first check the salt length requirement
    if (pssKeyParams.getSaltLength() > sigParams.getSaltLength()) {
        return false;
    }

    // compare equality of the rest of fields based on DER encoding
    PSSParameterSpec keyParams2 =
        new PSSParameterSpec(pssKeyParams.getDigestAlgorithm(),
                pssKeyParams.getMGFAlgorithm(),
                pssKeyParams.getMGFParameters(),
                sigParams.getSaltLength(),
                pssKeyParams.getTrailerField());
    PSSParameters ap = new PSSParameters();
    // skip the JCA overhead
    try {
        ap.engineInit(keyParams2);
        byte[] encoded = ap.engineGetEncoded();
        ap.engineInit(sigParams);
        byte[] encoded2 = ap.engineGetEncoded();
        return Arrays.equals(encoded, encoded2);
    } catch (Exception e) {
        if (DEBUG) {
            e.printStackTrace();
        }
        return false;
    }
}
 
Example 16
Source File: CSignature.java    From openjdk-jdk8u with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Validate the specified Signature PSS parameters.
 */
private PSSParameterSpec validateSigParams(AlgorithmParameterSpec p)
        throws InvalidAlgorithmParameterException {

    if (p == null) {
        throw new InvalidAlgorithmParameterException
                ("Parameters cannot be null");
    }

    if (!(p instanceof PSSParameterSpec)) {
        throw new InvalidAlgorithmParameterException
                ("parameters must be type PSSParameterSpec");
    }

    // no need to validate again if same as current signature parameters
    PSSParameterSpec params = (PSSParameterSpec) p;
    if (params == this.pssParams) return params;

    // now sanity check the parameter values
    if (!(params.getMGFAlgorithm().equalsIgnoreCase("MGF1"))) {
        throw new InvalidAlgorithmParameterException("Only supports MGF1");

    }

    if (params.getTrailerField() != PSSParameterSpec.TRAILER_FIELD_BC) {
        throw new InvalidAlgorithmParameterException
                ("Only supports TrailerFieldBC(1)");
    }

    AlgorithmParameterSpec algSpec = params.getMGFParameters();
    if (!(algSpec instanceof MGF1ParameterSpec)) {
        throw new InvalidAlgorithmParameterException
                ("Only support MGF1ParameterSpec");
    }

    MGF1ParameterSpec mgfSpec = (MGF1ParameterSpec)algSpec;

    String msgHashAlg = params.getDigestAlgorithm()
            .toLowerCase(Locale.ROOT).replaceAll("-", "");
    if (msgHashAlg.equals("sha")) {
        msgHashAlg = "sha1";
    }
    String mgf1HashAlg = mgfSpec.getDigestAlgorithm()
            .toLowerCase(Locale.ROOT).replaceAll("-", "");
    if (mgf1HashAlg.equals("sha")) {
        mgf1HashAlg = "sha1";
    }

    if (!mgf1HashAlg.equals(msgHashAlg)) {
        throw new InvalidAlgorithmParameterException
                ("MGF1 hash must be the same as message hash");
    }

    return params;
}
 
Example 17
Source File: PSSParameters.java    From openjdk-jdk8u with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Returns the encoding of a {@link PSSParameterSpec} object. This method
 * is used in this class and {@link AlgorithmId}.
 *
 * @param spec a {@code PSSParameterSpec} object
 * @return its DER encoding
 * @throws IOException if the name of a MessageDigest or MaskGenAlgorithm
 *          is unsupported
 */
public static byte[] getEncoded(PSSParameterSpec spec) throws IOException {

    AlgorithmParameterSpec mgfSpec = spec.getMGFParameters();
    if (!(mgfSpec instanceof MGF1ParameterSpec)) {
        throw new IOException("Cannot encode " + mgfSpec);
    }

    MGF1ParameterSpec mgf1Spec = (MGF1ParameterSpec)mgfSpec;

    DerOutputStream tmp = new DerOutputStream();
    DerOutputStream tmp2, tmp3;

    // MD
    AlgorithmId mdAlgId;
    try {
        mdAlgId = AlgorithmId.get(spec.getDigestAlgorithm());
    } catch (NoSuchAlgorithmException nsae) {
        throw new IOException("AlgorithmId " + spec.getDigestAlgorithm() +
                " impl not found");
    }
    if (!mdAlgId.getOID().equals(AlgorithmId.SHA_oid)) {
        tmp2 = new DerOutputStream();
        mdAlgId.derEncode(tmp2);
        tmp.write(DerValue.createTag(DerValue.TAG_CONTEXT, true, (byte) 0),
                tmp2);
    }

    // MGF
    AlgorithmId mgfDigestId;
    try {
        mgfDigestId = AlgorithmId.get(mgf1Spec.getDigestAlgorithm());
    } catch (NoSuchAlgorithmException nase) {
        throw new IOException("AlgorithmId " +
                mgf1Spec.getDigestAlgorithm() + " impl not found");
    }

    if (!mgfDigestId.getOID().equals(AlgorithmId.SHA_oid)) {
        tmp2 = new DerOutputStream();
        tmp2.putOID(AlgorithmId.mgf1_oid);
        mgfDigestId.encode(tmp2);
        tmp3 = new DerOutputStream();
        tmp3.write(DerValue.tag_Sequence, tmp2);
        tmp.write(DerValue.createTag(DerValue.TAG_CONTEXT, true, (byte) 1),
                tmp3);
    }

    // SaltLength
    if (spec.getSaltLength() != 20) {
        tmp2 = new DerOutputStream();
        tmp2.putInteger(spec.getSaltLength());
        tmp.write(DerValue.createTag(DerValue.TAG_CONTEXT, true, (byte) 2),
                tmp2);
    }

    // TrailerField
    if (spec.getTrailerField() != PSSParameterSpec.TRAILER_FIELD_BC) {
        tmp2 = new DerOutputStream();
        tmp2.putInteger(spec.getTrailerField());
        tmp.write(DerValue.createTag(DerValue.TAG_CONTEXT, true, (byte) 3),
                tmp2);
    }

    // Put all together under a SEQUENCE tag
    DerOutputStream out = new DerOutputStream();
    out.write(DerValue.tag_Sequence, tmp);
    return out.toByteArray();
}