org.bouncycastle.asn1.x509.AlgorithmIdentifier Java Examples

The following examples show how to use org.bouncycastle.asn1.x509.AlgorithmIdentifier. 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: AlgorithmUtil.java    From xipki with Apache License 2.0 6 votes vote down vote up
public static AlgorithmIdentifier getSigAlgId(PublicKey pubKey, HashAlgo hashAlgo,
    SignatureAlgoControl algoControl) throws NoSuchAlgorithmException {
  Args.notNull(hashAlgo, "hashAlgo");

  if (pubKey instanceof RSAPublicKey) {
    boolean rsaMgf1 = (algoControl == null) ? false : algoControl.isRsaMgf1();
    return getRSASigAlgId(hashAlgo, rsaMgf1);
  } else if (pubKey instanceof ECPublicKey) {
    boolean dsaPlain = (algoControl == null) ? false : algoControl.isDsaPlain();
    boolean gm =  (algoControl == null) ? false : algoControl.isGm();
    return getECSigAlgId(hashAlgo, dsaPlain, gm);
  } else if (pubKey instanceof DSAPublicKey) {
    return getDSASigAlgId(hashAlgo);
  } else {
    throw new NoSuchAlgorithmException("Unknown public key '" + pubKey.getClass().getName());
  }
}
 
Example #2
Source File: P11ContentSigner.java    From xipki with Apache License 2.0 6 votes vote down vote up
ECDSA(P11CryptService cryptService, P11IdentityId identityId,
    AlgorithmIdentifier signatureAlgId, boolean plain)
    throws XiSecurityException, P11TokenException {
  super(cryptService, identityId, signatureAlgId);

  this.plain = plain;

  String algOid = signatureAlgId.getAlgorithm().getId();
  HashAlgo hashAlgo = sigAlgHashMap.get(algOid);
  if (hashAlgo == null) {
    throw new XiSecurityException("unsupported signature algorithm " + algOid);
  }

  P11Slot slot = cryptService.getSlot(identityId.getSlotId());

  long mech = hashMechMap.get(hashAlgo).longValue();
  if (slot.supportsMechanism(mech)) {
    mechanism = mech;
    this.outputStream = new ByteArrayOutputStream();
  } else if (slot.supportsMechanism(PKCS11Constants.CKM_ECDSA)) {
    mechanism = PKCS11Constants.CKM_ECDSA;
    this.outputStream = new DigestOutputStream(hashAlgo.createDigest());
  } else {
    throw new XiSecurityException("unsupported signature algorithm " + algOid);
  }
}
 
Example #3
Source File: AlgorithmUtil.java    From xipki with Apache License 2.0 6 votes vote down vote up
public static AlgorithmCode getSigOrMacAlgoCode(AlgorithmIdentifier algId)
    throws NoSuchAlgorithmException {
  ASN1ObjectIdentifier oid = algId.getAlgorithm();
  AlgorithmCode code = algOidToCodeMap.get(oid);
  if (code != null) {
    return code;
  }

  if (PKCSObjectIdentifiers.id_RSASSA_PSS.equals(oid)) {
    RSASSAPSSparams param = RSASSAPSSparams.getInstance(algId.getParameters());
    ASN1ObjectIdentifier digestAlgOid = param.getHashAlgorithm().getAlgorithm();
    code = digestToMgf1AlgCodeMap.get(digestAlgOid);
    if (code == null) {
      throw new NoSuchAlgorithmException("unsupported digest algorithm " + digestAlgOid);
    }
    return code;
  } else {
    throw new NoSuchAlgorithmException("unsupported signature algorithm " + oid.getId());
  }
}
 
Example #4
Source File: DSSASN1Utils.java    From dss with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * Gets the ASN.1 algorithm identifier structure corresponding to the algorithm 
 * found in the provided Timestamp Hash Index Table, if such algorithm is present
 *
 * @param atsHashIndexValue
 *            ats-hash-index table from a timestamp
 * @return the ASN.1 algorithm identifier structure
 */
public static AlgorithmIdentifier getAlgorithmIdentifier(final ASN1Sequence atsHashIndexValue) {
	if (atsHashIndexValue != null && atsHashIndexValue.size() > 3) {
		final int algorithmIndex = 0;
		final ASN1Encodable asn1Encodable = atsHashIndexValue.getObjectAt(algorithmIndex);
		
		if (asn1Encodable instanceof ASN1Sequence) {
			final ASN1Sequence asn1Sequence = (ASN1Sequence) asn1Encodable;
			return AlgorithmIdentifier.getInstance(asn1Sequence);
		} else if (asn1Encodable instanceof ASN1ObjectIdentifier) {
			// TODO (16/11/2014): The relevance and usefulness of the test case must be checked (do the signatures
			// like this exist?)
			ASN1ObjectIdentifier derObjectIdentifier = ASN1ObjectIdentifier.getInstance(asn1Encodable);
			return new AlgorithmIdentifier(derObjectIdentifier);
		}
	}
	return null;
}
 
Example #5
Source File: AlgorithmUtil.java    From xipki with Apache License 2.0 6 votes vote down vote up
public static AlgorithmIdentifier extractDigesetAlgFromSigAlg(AlgorithmIdentifier sigAlgId)
    throws NoSuchAlgorithmException {
  ASN1ObjectIdentifier algOid = sigAlgId.getAlgorithm();

  ASN1ObjectIdentifier digestAlgOid;
  if (PKCSObjectIdentifiers.id_RSASSA_PSS.equals(algOid)) {
    ASN1Encodable asn1Encodable = sigAlgId.getParameters();
    RSASSAPSSparams param = RSASSAPSSparams.getInstance(asn1Encodable);
    digestAlgOid = param.getHashAlgorithm().getAlgorithm();
  } else {
    HashAlgo digestAlg = sigAlgOidToDigestMap.get(algOid);
    if (digestAlg == null) {
      throw new NoSuchAlgorithmException("unknown signature algorithm " + algOid.getId());
    }
    digestAlgOid = digestAlg.getOid();
  }

  return new AlgorithmIdentifier(digestAlgOid, DERNull.INSTANCE);
}
 
Example #6
Source File: AlgorithmUtil.java    From xipki with Apache License 2.0 6 votes vote down vote up
public static boolean isRSASigAlgId(AlgorithmIdentifier algId) {
  ASN1ObjectIdentifier oid = Args.notNull(algId, "algId").getAlgorithm();
  if (PKCSObjectIdentifiers.sha1WithRSAEncryption.equals(oid)
      || PKCSObjectIdentifiers.sha224WithRSAEncryption.equals(oid)
      || PKCSObjectIdentifiers.sha256WithRSAEncryption.equals(oid)
      || PKCSObjectIdentifiers.sha384WithRSAEncryption.equals(oid)
      || PKCSObjectIdentifiers.sha512WithRSAEncryption.equals(oid)
      || NISTObjectIdentifiers.id_rsassa_pkcs1_v1_5_with_sha3_224.equals(oid)
      || NISTObjectIdentifiers.id_rsassa_pkcs1_v1_5_with_sha3_256.equals(oid)
      || NISTObjectIdentifiers.id_rsassa_pkcs1_v1_5_with_sha3_384.equals(oid)
      || NISTObjectIdentifiers.id_rsassa_pkcs1_v1_5_with_sha3_512.equals(oid)
      || PKCSObjectIdentifiers.id_RSASSA_PSS.equals(oid)) {
    return true;
  }

  return false;
}
 
Example #7
Source File: CadesLevelBaselineLTATimestampExtractor.java    From dss with GNU Lesser General Public License v2.1 6 votes vote down vote up
private Attribute getComposedAtsHashIndex(AlgorithmIdentifier algorithmIdentifiers, ASN1Sequence certificatesHashIndex, ASN1Sequence crLsHashIndex,
		ASN1Sequence unsignedAttributesHashIndex, ASN1ObjectIdentifier atsHashIndexVersionIdentifier) {
	final ASN1EncodableVector vector = new ASN1EncodableVector();
	if (algorithmIdentifiers != null) {
		vector.add(algorithmIdentifiers);
	} else if (id_aa_ATSHashIndexV2.equals(atsHashIndexVersionIdentifier) || id_aa_ATSHashIndexV3.equals(atsHashIndexVersionIdentifier)) {
		// for id_aa_ATSHashIndexV2 and id_aa_ATSHashIndexV3, the algorithmIdentifier is required
		AlgorithmIdentifier sha256AlgorithmIdentifier = new AlgorithmIdentifier(new ASN1ObjectIdentifier(DigestAlgorithm.SHA256.getOid()));
		vector.add(sha256AlgorithmIdentifier);
	}
	if (certificatesHashIndex != null) {
		vector.add(certificatesHashIndex);
	}
	if (crLsHashIndex != null) {
		vector.add(crLsHashIndex);
	}
	if (unsignedAttributesHashIndex != null) {
		vector.add(unsignedAttributesHashIndex);
	}
	final ASN1Sequence derSequence = new DERSequence(vector);
	return new Attribute(atsHashIndexVersionIdentifier, new DERSet(derSequence));
}
 
Example #8
Source File: RsaCertificateAuthorityClient.java    From protect with MIT License 6 votes vote down vote up
/*** Static Methods ***/

	private static BigInteger EMSA_PKCS1_V1_5_ENCODE(byte[] input, final BigInteger modulus)
			throws NoSuchAlgorithmException, IOException {

		// Digest the input
		final MessageDigest md = MessageDigest.getInstance(HASH_ALGORITHM);
		final byte[] digest = md.digest(input);

		// Create a digest info consisting of the algorithm id and the hash
		final AlgorithmIdentifier algId = new AlgorithmIdentifier(NISTObjectIdentifiers.id_sha512, DERNull.INSTANCE);
		final DigestInfo digestInfo = new DigestInfo(algId, digest);
		final byte[] message = digestInfo.getEncoded(ASN1Encoding.DER);

		// Do PKCS1 padding
		final byte[] block = new byte[((modulus.bitLength() + 7) / 8) - 1];
		System.arraycopy(message, 0, block, block.length - message.length, message.length);
		block[0] = 0x01; // type code 1
		for (int i = 1; i != block.length - message.length - 1; i++) {
			block[i] = (byte) 0xFF;
		}

		return new BigInteger(1, block);
	}
 
Example #9
Source File: HmacContentSigner.java    From xipki with Apache License 2.0 6 votes vote down vote up
public HmacContentSigner(HashAlgo hashAlgo, AlgorithmIdentifier algorithmIdentifier,
    SecretKey signingKey) throws XiSecurityException {
  this.algorithmIdentifier = Args.notNull(algorithmIdentifier, "algorithmIdentifier");
  Args.notNull(signingKey, "signingKey");
  try {
    this.encodedAlgorithmIdentifier = algorithmIdentifier.getEncoded();
  } catch (IOException ex) {
    throw new XiSecurityException("could not encode AlgorithmIdentifier", ex);
  }
  if (hashAlgo == null) {
    hashAlgo = AlgorithmUtil.extractHashAlgoFromMacAlg(algorithmIdentifier);
  }

  this.hmac = new HMac(hashAlgo.createDigest());
  byte[] keyBytes = signingKey.getEncoded();
  this.hmac.init(new KeyParameter(keyBytes, 0, keyBytes.length));
  this.outLen = hmac.getMacSize();
  this.outputStream = new HmacOutputStream();
}
 
Example #10
Source File: SignatureVerificationService.java    From guardedbox with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * This method gets called after the bean is created.
 */
@PostConstruct
private void postConstruct() {

    // Set signatureAlgorithmId.
    try {

        signatureAlgorithmId = new AlgorithmIdentifier((ASN1ObjectIdentifier) EdECObjectIdentifiers.class
                .getDeclaredField("id_" + cryptographyProperties.getSignatureAlgorithm()).get(null));

    } catch (IllegalArgumentException | IllegalAccessException | NoSuchFieldException | SecurityException e) {
        throw new RuntimeException(String.format(
                "Error creating the AlgorithmIdentifier corresponding to the signature algorithm %s",
                cryptographyProperties.getSignatureAlgorithm()));
    }

}
 
Example #11
Source File: KeypairGenControl.java    From xipki with Apache License 2.0 6 votes vote down vote up
public DSAKeypairGenControl(int pLength, int qLength, ASN1ObjectIdentifier keyAlgorithmOid) {
  if (pLength < 1024 | pLength % 1024 != 0) {
    throw new IllegalArgumentException("invalid pLength " + pLength);
  }

  if (qLength == 0) {
    if (pLength < 2048) {
      qLength = 160;
    } else if (pLength < 3072) {
      qLength = 224;
    } else {
      qLength = 256;
    }
  }

  this.parameterSpec = DSAParameterCache.getDSAParameterSpec(pLength, qLength, null);
  this.keyAlgorithm = new AlgorithmIdentifier(
      (keyAlgorithmOid != null) ? keyAlgorithmOid : X9ObjectIdentifiers.id_dsa,
      new DSAParameter(parameterSpec.getP(), parameterSpec.getQ(), parameterSpec.getG()));
}
 
Example #12
Source File: PdfPublicKeySecurityHandler.java    From itext2 with GNU Lesser General Public License v3.0 6 votes vote down vote up
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().getAlgorithm();
    IssuerAndSerialNumber issuerandserialnumber = 
        new IssuerAndSerialNumber(
            tbscertificatestructure.getIssuer(), 
            tbscertificatestructure.getSerialNumber().getValue());
    Cipher cipher = Cipher.getInstance(algorithmidentifier.getAlgorithm().getId());        
    cipher.init(1, x509certificate);
    DEROctetString deroctetstring = new DEROctetString(cipher.doFinal(abyte0));
    RecipientIdentifier recipId = new RecipientIdentifier(issuerandserialnumber);
    return new KeyTransRecipientInfo( recipId, algorithmidentifier, deroctetstring);
}
 
Example #13
Source File: AlgorithmUtil.java    From xipki with Apache License 2.0 6 votes vote down vote up
public static String getSignatureAlgoName(AlgorithmIdentifier sigAlgId)
    throws NoSuchAlgorithmException {
  ASN1ObjectIdentifier algOid = Args.notNull(sigAlgId, "sigAlgId").getAlgorithm();
  String name = null;
  if (PKCSObjectIdentifiers.id_RSASSA_PSS.equals(algOid)) {
    RSASSAPSSparams param = RSASSAPSSparams.getInstance(sigAlgId.getParameters());
    ASN1ObjectIdentifier digestAlgOid = param.getHashAlgorithm().getAlgorithm();
    name = digestOidToMgf1SigNameMap.get(digestAlgOid);
    if (name == null) {
      throw new NoSuchAlgorithmException("unsupported digest algorithm " + digestAlgOid);
    }
  } else {
    name = sigAlgOidToNameMap.get(algOid);
  }

  if (name == null) {
    throw new NoSuchAlgorithmException("unsupported signature algorithm " + algOid.getId());
  }
  return name;
}
 
Example #14
Source File: CaClientExample.java    From xipki with Apache License 2.0 6 votes vote down vote up
protected static MyKeypair generateDsaKeypair() throws Exception {
  // plen: 2048, qlen: 256
  DSAParameterSpec spec = new DSAParameterSpec(P2048_Q256_P, P2048_Q256_Q, P2048_Q256_G);
  KeyPairGenerator kpGen = KeyPairGenerator.getInstance("DSA");
  kpGen.initialize(spec);
  KeyPair kp = kpGen.generateKeyPair();

  DSAPublicKey dsaPubKey = (DSAPublicKey) kp.getPublic();
  ASN1EncodableVector vec = new ASN1EncodableVector();
  vec.add(new ASN1Integer(dsaPubKey.getParams().getP()));
  vec.add(new ASN1Integer(dsaPubKey.getParams().getQ()));
  vec.add(new ASN1Integer(dsaPubKey.getParams().getG()));
  ASN1Sequence dssParams = new DERSequence(vec);

  SubjectPublicKeyInfo subjectPublicKeyInfo = new SubjectPublicKeyInfo(
      new AlgorithmIdentifier(X9ObjectIdentifiers.id_dsa, dssParams),
      new ASN1Integer(dsaPubKey.getY()));

  return new MyKeypair(kp.getPrivate(), subjectPublicKeyInfo);
}
 
Example #15
Source File: AlgorithmUtil.java    From xipki with Apache License 2.0 6 votes vote down vote up
public static boolean isDSASigAlg(AlgorithmIdentifier algId) {
  ASN1ObjectIdentifier oid = Args.notNull(algId, "algId").getAlgorithm();
  if (X9ObjectIdentifiers.id_dsa_with_sha1.equals(oid)
      || NISTObjectIdentifiers.dsa_with_sha224.equals(oid)
      || NISTObjectIdentifiers.dsa_with_sha256.equals(oid)
      || NISTObjectIdentifiers.dsa_with_sha384.equals(oid)
      || NISTObjectIdentifiers.dsa_with_sha512.equals(oid)
      || NISTObjectIdentifiers.id_dsa_with_sha3_224.equals(oid)
      || NISTObjectIdentifiers.id_dsa_with_sha3_256.equals(oid)
      || NISTObjectIdentifiers.id_dsa_with_sha3_384.equals(oid)
      || NISTObjectIdentifiers.id_dsa_with_sha3_512.equals(oid)) {
    return true;
  }

  return false;
}
 
Example #16
Source File: RequestOptions.java    From xipki with Apache License 2.0 6 votes vote down vote up
public static RSASSAPSSparams createPSSRSAParams(ASN1ObjectIdentifier digestAlgOid) {
  int saltSize;
  if (X509ObjectIdentifiers.id_SHA1.equals(digestAlgOid)) {
    saltSize = 20;
  } else if (NISTObjectIdentifiers.id_sha224.equals(digestAlgOid)) {
    saltSize = 28;
  } else if (NISTObjectIdentifiers.id_sha256.equals(digestAlgOid)) {
    saltSize = 32;
  } else if (NISTObjectIdentifiers.id_sha384.equals(digestAlgOid)) {
    saltSize = 48;
  } else if (NISTObjectIdentifiers.id_sha512.equals(digestAlgOid)) {
    saltSize = 64;
  } else {
    throw new IllegalStateException("unknown digest algorithm " + digestAlgOid);
  }

  AlgorithmIdentifier digAlgId = new AlgorithmIdentifier(digestAlgOid, DERNull.INSTANCE);
  return new RSASSAPSSparams(digAlgId,
      new AlgorithmIdentifier(PKCSObjectIdentifiers.id_mgf1, digAlgId),
      new ASN1Integer(saltSize), RSASSAPSSparams.DEFAULT_TRAILER_FIELD);
}
 
Example #17
Source File: AlgorithmUtil.java    From xipki with Apache License 2.0 6 votes vote down vote up
private static boolean isECDSASigAlg(AlgorithmIdentifier algId) {
  ASN1ObjectIdentifier oid = Args.notNull(algId, "algId").getAlgorithm();
  if (X9ObjectIdentifiers.ecdsa_with_SHA1.equals(oid)
      || X9ObjectIdentifiers.ecdsa_with_SHA224.equals(oid)
      || X9ObjectIdentifiers.ecdsa_with_SHA256.equals(oid)
      || X9ObjectIdentifiers.ecdsa_with_SHA384.equals(oid)
      || X9ObjectIdentifiers.ecdsa_with_SHA512.equals(oid)
      || NISTObjectIdentifiers.id_ecdsa_with_sha3_224.equals(oid)
      || NISTObjectIdentifiers.id_ecdsa_with_sha3_256.equals(oid)
      || NISTObjectIdentifiers.id_ecdsa_with_sha3_384.equals(oid)
      || NISTObjectIdentifiers.id_ecdsa_with_sha3_512.equals(oid)) {
    return true;
  }

  return false;
}
 
Example #18
Source File: SFTrustManager.java    From snowflake-jdbc with Apache License 2.0 5 votes vote down vote up
/**
 * Encode OCSP Response Cache to JSON
 *
 * @return JSON object
 */
private static ObjectNode encodeCacheToJSON()
{
  try
  {
    ObjectNode out = OBJECT_MAPPER.createObjectNode();
    for (Map.Entry<OcspResponseCacheKey, SFPair<Long, String>> elem :
        OCSP_RESPONSE_CACHE.entrySet())
    {
      OcspResponseCacheKey key = elem.getKey();
      SFPair<Long, String> value0 = elem.getValue();
      long currentTimeSecond = value0.left;

      DigestCalculator digest = new SHA1DigestCalculator();
      AlgorithmIdentifier algo = digest.getAlgorithmIdentifier();
      ASN1OctetString nameHash = ASN1OctetString.getInstance(key.nameHash);
      ASN1OctetString keyHash = ASN1OctetString.getInstance(key.keyHash);
      ASN1Integer serialNumber = new ASN1Integer(key.serialNumber);
      CertID cid = new CertID(algo, nameHash, keyHash, serialNumber);
      ArrayNode vout = OBJECT_MAPPER.createArrayNode();
      vout.add(currentTimeSecond);
      vout.add(value0.right);
      out.set(
          Base64.encodeBase64String(cid.toASN1Primitive().getEncoded()),
          vout);
    }
    return out;
  }
  catch (IOException ex)
  {
    LOGGER.debug("Failed to encode ASN1 object.");
  }
  return null;
}
 
Example #19
Source File: AlgorithmUtil.java    From xipki with Apache License 2.0 5 votes vote down vote up
private static RSASSAPSSparams createPSSRSAParams(HashAlgo digestAlg)
    throws NoSuchAlgorithmException {
  int saltSize = Args.notNull(digestAlg, "digestAlg").getLength();
  AlgorithmIdentifier digAlgId = new AlgorithmIdentifier(digestAlg.getOid(), DERNull.INSTANCE);
  return new RSASSAPSSparams(digAlgId,
      new AlgorithmIdentifier(PKCSObjectIdentifiers.id_mgf1, digAlgId),
      new ASN1Integer(saltSize), RSASSAPSSparams.DEFAULT_TRAILER_FIELD);
}
 
Example #20
Source File: PkiUtil.java    From cloudbreak with Apache License 2.0 5 votes vote down vote up
private static X509Certificate selfsign(PKCS10CertificationRequest inputCSR, String publicAddress, KeyPair signKey)
        throws Exception {

    AlgorithmIdentifier sigAlgId = new DefaultSignatureAlgorithmIdentifierFinder()
            .find("SHA256withRSA");
    AlgorithmIdentifier digAlgId = new DefaultDigestAlgorithmIdentifierFinder()
            .find(sigAlgId);

    AsymmetricKeyParameter akp = PrivateKeyFactory.createKey(signKey.getPrivate()
            .getEncoded());

    Calendar cal = Calendar.getInstance();
    Date currentTime = cal.getTime();
    cal.add(Calendar.YEAR, CERT_VALIDITY_YEAR);
    Date expiryTime = cal.getTime();

    X509v3CertificateBuilder myCertificateGenerator = new X509v3CertificateBuilder(
            new X500Name(String.format("cn=%s", publicAddress)), new BigInteger("1"), currentTime, expiryTime, inputCSR.getSubject(),
            inputCSR.getSubjectPublicKeyInfo());

    ContentSigner sigGen = new BcRSAContentSignerBuilder(sigAlgId, digAlgId)
            .build(akp);

    X509CertificateHolder holder = myCertificateGenerator.build(sigGen);

    CertificateFactory cf = CertificateFactory.getInstance("X.509");

    return (X509Certificate) cf.generateCertificate(new ByteArrayInputStream(holder.toASN1Structure().getEncoded()));
}
 
Example #21
Source File: Certificates.java    From vertx-config with Apache License 2.0 5 votes vote down vote up
/**
 * See http://www.programcreek.com/java-api-examples/index.php?api=org.bouncycastle.operator.DefaultSignatureAlgorithmIdentifierFinder
 *
 * @param keyPair The RSA keypair with which to generate the certificate
 * @param issuer  The issuer (and subject) to use for the certificate
 * @return An X509 certificate
 * @throws IOException
 * @throws OperatorCreationException
 * @throws CertificateException
 * @throws NoSuchProviderException
 * @throws NoSuchAlgorithmException
 * @throws InvalidKeyException
 * @throws SignatureException
 */
private static X509Certificate generateCert(final KeyPair keyPair, final String issuer) throws IOException, OperatorCreationException,
  CertificateException, NoSuchProviderException, NoSuchAlgorithmException, InvalidKeyException,
  SignatureException {
  final String subject = issuer;
  final X509v3CertificateBuilder certificateBuilder = new X509v3CertificateBuilder(
    new X500Name(issuer),
    BigInteger.ONE,
    new Date(System.currentTimeMillis() - 1000L * 60 * 60 * 24 * 30),
    new Date(System.currentTimeMillis() + (1000L * 60 * 60 * 24 * 30)),
    new X500Name(subject),
    SubjectPublicKeyInfo.getInstance(keyPair.getPublic().getEncoded())
  );

  final GeneralNames subjectAltNames = new GeneralNames(new GeneralName(GeneralName.iPAddress, "127.0.0.1"));
  certificateBuilder.addExtension(org.bouncycastle.asn1.x509.Extension.subjectAlternativeName, false, subjectAltNames);

  final AlgorithmIdentifier sigAlgId = new DefaultSignatureAlgorithmIdentifierFinder().find("SHA1WithRSAEncryption");
  final AlgorithmIdentifier digAlgId = new DefaultDigestAlgorithmIdentifierFinder().find(sigAlgId);
  final BcContentSignerBuilder signerBuilder = new BcRSAContentSignerBuilder(sigAlgId, digAlgId);
  final AsymmetricKeyParameter keyp = PrivateKeyFactory.createKey(keyPair.getPrivate().getEncoded());
  final ContentSigner signer = signerBuilder.build(keyp);
  final X509CertificateHolder x509CertificateHolder = certificateBuilder.build(signer);

  final X509Certificate certificate = new JcaX509CertificateConverter()
    .getCertificate(x509CertificateHolder);
  certificate.checkValidity(new Date());
  certificate.verify(keyPair.getPublic());
  return certificate;
}
 
Example #22
Source File: BCECUtil.java    From jiguang-java-client-common with MIT License 5 votes vote down vote up
/**
 * 将SEC1标准的私钥字节流恢复为PKCS8标准的字节流
 *
 * @param sec1Key
 * @return
 * @throws IOException
 */
public static byte[] convertECPrivateKeySEC1ToPKCS8(byte[] sec1Key) throws IOException {
    /**
     * 参考org.bouncycastle.asn1.pkcs.PrivateKeyInfo和
     * org.bouncycastle.jcajce.provider.asymmetric.ec.BCECPrivateKey,逆向拼装
     */
    X962Parameters params = getDomainParametersFromName(SM2Util.JDK_EC_SPEC, false);
    ASN1OctetString privKey = new DEROctetString(sec1Key);
    ASN1EncodableVector v = new ASN1EncodableVector();
    v.add(new ASN1Integer(0)); //版本号
    v.add(new AlgorithmIdentifier(X9ObjectIdentifiers.id_ecPublicKey, params)); //算法标识
    v.add(privKey);
    DERSequence ds = new DERSequence(v);
    return ds.getEncoded(ASN1Encoding.DER);
}
 
Example #23
Source File: Digester.java    From netty-4.1.22 with Apache License 2.0 5 votes vote down vote up
public static DigestCalculator sha1() {
    Digest digest = new SHA1Digest();
    AlgorithmIdentifier algId = new AlgorithmIdentifier(
            OIWObjectIdentifiers.idSHA1);

    return new Digester(digest, algId);
}
 
Example #24
Source File: PolicyInfo.java    From signer with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
public void parse(ASN1Primitive primitive) {
    ASN1Sequence sequence1 = ASN1Object.getDERSequence(primitive);
    this.signingPeriod = new SigningPeriod();
    this.signingPeriod.parse(sequence1.getObjectAt(0).toASN1Primitive());
    int indice = 2;

    ASN1Primitive secondObject = sequence1.getObjectAt(1).toASN1Primitive();
    if (secondObject instanceof ASN1ObjectIdentifier) {
        indice = 1;
    }
    if (indice == 2) {
        this.revocationDate = new GeneralizedTime();
        this.revocationDate.parse(secondObject);
    }
    this.policyOID = new ObjectIdentifier();
    this.policyOID.parse(sequence1.getObjectAt(indice).toASN1Primitive());
    DERIA5String policyURI = (DERIA5String) sequence1.getObjectAt(indice + 1);
    this.policyURI = policyURI.getString();

    ASN1Primitive policyDigest = sequence1.getObjectAt(indice + 2).toASN1Primitive();
    ASN1Sequence sequence2 = ASN1Sequence.getInstance(policyDigest);

    DEROctetString derOctetString = (DEROctetString) sequence2.getObjectAt(1).toASN1Primitive();
    ASN1Sequence sequence3 = ASN1Object.getDERSequence(sequence2.getObjectAt(0).toASN1Primitive());
    ASN1ObjectIdentifier objectIdentifier = (ASN1ObjectIdentifier) sequence3.getObjectAt(0).toASN1Primitive();
    AlgorithmIdentifier algorithmIdentifier = new AlgorithmIdentifier(objectIdentifier);
    this.policyDigest = new OtherHashAlgAndValue(algorithmIdentifier, derOctetString);
}
 
Example #25
Source File: KeypairGenControl.java    From xipki with Apache License 2.0 5 votes vote down vote up
public DSAKeypairGenControl(BigInteger p, BigInteger q, BigInteger g,
    ASN1ObjectIdentifier keyAlgorithmOid) {
  this.parameterSpec = new DSAParameterSpec(p, q, g);

  this.keyAlgorithm = new AlgorithmIdentifier(
      (keyAlgorithmOid != null) ? keyAlgorithmOid : X9ObjectIdentifiers.id_dsa,
      new DSAParameter(p, q, g));
}
 
Example #26
Source File: IdSigningPolicy.java    From signer with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * org.bouncycastle.asn1.ASN1ObjectIdentifier sigPolicyId
 * org.bouncycastle.asn1.esf.OtherHashAlgAndValue sigPolicyHash
 * List&lt;org.bouncycastle.asn1.esf.SigPolicyQualifierInfo&gt; sigPolicyQualifierInfos
 */
@Override
public Attribute getValue() {

  //Atributo 1
    ASN1ObjectIdentifier sigPolicyId = new ASN1ObjectIdentifier(signaturePolicy.getSignPolicyInfo().getSignPolicyIdentifier().getValue());

    //Atributo 2
    OtherHashAlgAndValue sigPolicyHash = new OtherHashAlgAndValue(new AlgorithmIdentifier(
    		new ASN1ObjectIdentifier(signaturePolicy.getSignPolicyHashAlg().getAlgorithm().getValue())), 
    		signaturePolicy.getSignPolicyHash().getDerOctetString());

    //Atributo 3
    List<SigPolicyQualifierInfo> sigPolicyQualifierInfos = new ArrayList<SigPolicyQualifierInfo>();

    ASN1ObjectIdentifier sigPolicyQualifierId = new ASN1ObjectIdentifier("1.2.840.113549.1.9.16.5.1");
    DERIA5String sigQualifier = new DERIA5String(signaturePolicy.getSignPolicyURI());
    SigPolicyQualifierInfo bcSigPolicyQualifierInfo = new SigPolicyQualifierInfo(sigPolicyQualifierId, sigQualifier);
    sigPolicyQualifierInfos.add(bcSigPolicyQualifierInfo);

    SigPolicyQualifiers sigPolicyQualifiers = new SigPolicyQualifiers(sigPolicyQualifierInfos.toArray(new SigPolicyQualifierInfo[]{}));

    SignaturePolicyId signaturePolicyId = new SignaturePolicyId(sigPolicyId, sigPolicyHash, sigPolicyQualifiers);
    return new Attribute(new ASN1ObjectIdentifier(oid), new DERSet(signaturePolicyId));
    
    
}
 
Example #27
Source File: P12ContentSignerBuilder.java    From xipki with Apache License 2.0 5 votes vote down vote up
protected Signer createSigner(AlgorithmIdentifier sigAlgId, AlgorithmIdentifier digAlgId)
    throws OperatorCreationException {
  if (!AlgorithmUtil.isDSASigAlg(sigAlgId)) {
    throw new OperatorCreationException("the given algorithm is not a valid DSA signature "
        + "algirthm '" + sigAlgId.getAlgorithm().getId() + "'");
  }

  Digest dig = digestProvider.get(digAlgId);
  DSASigner dsaSigner = new DSASigner();
  return plain ? new DSAPlainDigestSigner(dsaSigner, dig) : new DSADigestSigner(dsaSigner, dig);
}
 
Example #28
Source File: Digester.java    From netty-4.1.22 with Apache License 2.0 5 votes vote down vote up
public static DigestCalculator sha256() {
    Digest digest = new SHA256Digest();

    // The OID for SHA-256: http://www.oid-info.com/get/2.16.840.1.101.3.4.2.1
    ASN1ObjectIdentifier oid = new ASN1ObjectIdentifier(
            "2.16.840.1.101.3.4.2.1").intern();
    AlgorithmIdentifier algId = new AlgorithmIdentifier(oid);

    return new Digester(digest, algId);
}
 
Example #29
Source File: PdfPublicKeySecurityHandler.java    From itext2 with GNU Lesser General Public License v3.0 5 votes vote down vote up
private ASN1Primitive createDERForRecipient(byte[] in, X509Certificate cert) 
    throws IOException,  
           GeneralSecurityException 
{
    
    String s = "1.2.840.113549.3.2";
    
    AlgorithmParameterGenerator algorithmparametergenerator = AlgorithmParameterGenerator.getInstance(s);
    AlgorithmParameters algorithmparameters = algorithmparametergenerator.generateParameters();
    ByteArrayInputStream bytearrayinputstream = new ByteArrayInputStream(algorithmparameters.getEncoded("ASN.1"));
    ASN1InputStream asn1inputstream = new ASN1InputStream(bytearrayinputstream);
    ASN1Primitive derobject = asn1inputstream.readObject();
    KeyGenerator keygenerator = KeyGenerator.getInstance(s);
    keygenerator.init(128);
    SecretKey secretkey = keygenerator.generateKey();
    Cipher cipher = Cipher.getInstance(s);
    cipher.init(1, secretkey, algorithmparameters);
    byte[] abyte1 = cipher.doFinal(in);
    DEROctetString deroctetstring = new DEROctetString(abyte1);
    KeyTransRecipientInfo keytransrecipientinfo = computeRecipientInfo(cert, secretkey.getEncoded());
    DERSet derset = new DERSet(new RecipientInfo(keytransrecipientinfo));
    AlgorithmIdentifier algorithmidentifier = new AlgorithmIdentifier(new ASN1ObjectIdentifier(s), derobject);
    EncryptedContentInfo encryptedcontentinfo = 
        new EncryptedContentInfo(PKCSObjectIdentifiers.data, algorithmidentifier, deroctetstring);
    EnvelopedData env = new EnvelopedData(null, derset, encryptedcontentinfo, (org.bouncycastle.asn1.ASN1Set) null);
    ContentInfo contentinfo = 
        new ContentInfo(PKCSObjectIdentifiers.envelopedData, env);
    return contentinfo.toASN1Primitive();        
}
 
Example #30
Source File: DSSASN1Utils.java    From dss with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Gets the ASN.1 algorithm identifier structure corresponding to a digest algorithm
 *
 * @param digestAlgorithm
 *            the digest algorithm to encode
 * @return the ASN.1 algorithm identifier structure
 */
public static AlgorithmIdentifier getAlgorithmIdentifier(DigestAlgorithm digestAlgorithm) {

	/*
	 * The recommendation (cf. RFC 3380 section 2.1) is to omit the parameter for SHA-1, but some implementations
	 * still expect a
	 * NULL there. Therefore we always include a NULL parameter even with SHA-1, despite the recommendation, because
	 * the RFC
	 * states that implementations SHOULD support it as well anyway
	 */
	final ASN1ObjectIdentifier asn1ObjectIdentifier = new ASN1ObjectIdentifier(digestAlgorithm.getOid());
	return new AlgorithmIdentifier(asn1ObjectIdentifier, DERNull.INSTANCE);
}