org.bouncycastle.asn1.DERNull Java Examples

The following examples show how to use org.bouncycastle.asn1.DERNull. 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: 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 #2
Source File: TlsHelper.java    From nifi with Apache License 2.0 6 votes vote down vote up
/**
 * Returns a {@link PEMKeyPair} object with direct access to the public and private keys given a PKCS #8 private key.
 *
 * @param privateKeyInfo the PKCS #8 private key info
 * @return the PKCS #1 public and private key pair
 * @throws IOException if there is an error converting the key pair
 */
private static PEMKeyPair convertPrivateKeyFromPKCS8ToPKCS1(PrivateKeyInfo privateKeyInfo) throws IOException {
    // Parse the key wrapping to determine the internal key structure
    ASN1Encodable asn1PrivateKey = privateKeyInfo.parsePrivateKey();

    // Convert the parsed key to an RSA private key
    RSAPrivateKey keyStruct = RSAPrivateKey.getInstance(asn1PrivateKey);

    // Create the RSA public key from the modulus and exponent
    RSAPublicKey pubSpec = new RSAPublicKey(
        keyStruct.getModulus(), keyStruct.getPublicExponent());

    // Create an algorithm identifier for forming the key pair
    AlgorithmIdentifier algId = new AlgorithmIdentifier(PKCSObjectIdentifiers.rsaEncryption, DERNull.INSTANCE);
    if (isVerbose()) {
        logger.info("Converted private key from PKCS #8 to PKCS #1 RSA private key");
    }

    // Create the key pair container
    return new PEMKeyPair(new SubjectPublicKeyInfo(algId, pubSpec), new PrivateKeyInfo(algId, keyStruct));
}
 
Example #3
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 #4
Source File: CmpCaClient.java    From xipki with Apache License 2.0 6 votes vote down vote up
public X509Certificate enrollCertViaCsr(String certprofile, CertificationRequest csr,
    boolean profileInUri) throws Exception {
  ProtectedPKIMessageBuilder builder = new ProtectedPKIMessageBuilder(
      PKIHeader.CMP_2000, requestorSubject, responderSubject);
  builder.setMessageTime(new Date());
  builder.setTransactionID(randomTransactionId());
  builder.setSenderNonce(randomSenderNonce());

  builder.addGeneralInfo(
      new InfoTypeAndValue(CMPObjectIdentifiers.it_implicitConfirm, DERNull.INSTANCE));
  String uri = null;
  if (profileInUri) {
    uri = caUri + "?certprofile=" + certprofile.toLowerCase();
  } else {
    builder.addGeneralInfo(
        new InfoTypeAndValue(CMPObjectIdentifiers.regInfo_utf8Pairs,
            new DERUTF8String("certprofile?" + certprofile + "%")));
  }
  builder.setBody(new PKIBody(PKIBody.TYPE_P10_CERT_REQ, csr));
  ProtectedPKIMessage request = build(builder);

  PKIMessage response = transmit(request, uri);
  return parseEnrollCertResult(response, PKIBody.TYPE_CERT_REP, 1)
          .values().iterator().next().getCert();
}
 
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 AlgorithmIdentifier getSigAlgId(String sigAlgName) throws NoSuchAlgorithmException {
  String algoS = Args.notNull(sigAlgName, "sigAlgName").toUpperCase();
  algoS = canonicalizeAlgoText(algoS);

  AlgorithmIdentifier signatureAlgId;
  if (algoS.contains("MGF1")) {
    HashAlgo ha = mgf1SigNameToDigestOidMap.get(algoS);
    if (ha == null) {
      throw new NoSuchAlgorithmException("unknown algorithm " + algoS);
    }

    signatureAlgId = buildRSAPSSAlgId(ha);
  } else {
    ASN1ObjectIdentifier algOid = sigAlgNameToOidMap.get(algoS);
    if (algOid == null) {
      throw new NoSuchAlgorithmException("unknown algorithm " + algoS);
    }
    boolean withNullParam = algoS.contains("RSA");
    signatureAlgId = withNullParam ? new AlgorithmIdentifier(algOid, DERNull.INSTANCE)
        : new AlgorithmIdentifier(algOid);
  }

  return signatureAlgId;
}
 
Example #7
Source File: CAdESSignature.java    From dss with GNU Lesser General Public License v2.1 6 votes vote down vote up
@Override
public MaskGenerationFunction getMaskGenerationFunction() {
	try {
		final SignatureAlgorithm signatureAlgorithm = getEncryptedDigestAlgo();
		if (signatureAlgorithm != null) {
			if (SignatureAlgorithm.RSA_SSA_PSS_SHA1_MGF1.equals(signatureAlgorithm)) {

				byte[] encryptionAlgParams = signerInformation.getEncryptionAlgParams();
				if (Utils.isArrayNotEmpty(encryptionAlgParams) && !Arrays.equals(DERNull.INSTANCE.getEncoded(), encryptionAlgParams)) {
					RSASSAPSSparams param = RSASSAPSSparams.getInstance(encryptionAlgParams);
					AlgorithmIdentifier maskGenAlgorithm = param.getMaskGenAlgorithm();
					if (PKCSObjectIdentifiers.id_mgf1.equals(maskGenAlgorithm.getAlgorithm())) {
						return MaskGenerationFunction.MGF1;
					} else {
						LOG.warn("Unsupported mask algorithm : {}", maskGenAlgorithm.getAlgorithm());
					}
				}
			}
		}
	} catch (IOException e) {
		LOG.warn("Unable to analyze EncryptionAlgParams", e);
	}
	return null;
}
 
Example #8
Source File: RsaSigningClient.java    From protect with MIT License 6 votes vote down vote up
public 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() / 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: Spkac.java    From keystore-explorer with GNU General Public License v3.0 6 votes vote down vote up
private ASN1Sequence createPublicKeyAndChallenge() throws SpkacException {
	ASN1EncodableVector publicKeyAlgorithm = new ASN1EncodableVector();
	publicKeyAlgorithm.add(new ASN1ObjectIdentifier(getPublicKeyAlg().oid()));

	if (getPublicKey() instanceof RSAPublicKey) {
		publicKeyAlgorithm.add(DERNull.INSTANCE);
	} else {
		DSAParams dsaParams = ((DSAPublicKey) getPublicKey()).getParams();

		ASN1EncodableVector dssParams = new ASN1EncodableVector();
		dssParams.add(new ASN1Integer(dsaParams.getP()));
		dssParams.add(new ASN1Integer(dsaParams.getQ()));
		dssParams.add(new ASN1Integer(dsaParams.getG()));

		publicKeyAlgorithm.add(new DERSequence(dssParams));
	}

	ASN1EncodableVector spki = new ASN1EncodableVector();
	spki.add(new DERSequence(publicKeyAlgorithm));
	spki.add(encodePublicKeyAsBitString(getPublicKey()));

	ASN1EncodableVector publicKeyAndChallenge = new ASN1EncodableVector();
	publicKeyAndChallenge.add(new DERSequence(spki));
	publicKeyAndChallenge.add(new DERIA5String(getChallenge()));
	return new DERSequence(publicKeyAndChallenge);
}
 
Example #10
Source File: SigningCertificate.java    From signer with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Override
public Attribute getValue() {
    try {
        X509Certificate cert = (X509Certificate) certificates[0];
        Digest digest = DigestFactory.getInstance().factoryDefault();
        digest.setAlgorithm(DigestAlgorithmEnum.SHA_1);
        byte[] hash = digest.digest(cert.getEncoded());
        X500Name dirName = new X500Name(cert.getSubjectDN().getName());
        GeneralName name = new GeneralName(dirName);
        GeneralNames issuer = new GeneralNames(name);
        ASN1Integer serial = new ASN1Integer(cert.getSerialNumber());
        IssuerSerial issuerSerial = new IssuerSerial(issuer, serial);
        ESSCertID essCertId = new ESSCertID(hash, issuerSerial);
        return new Attribute(new ASN1ObjectIdentifier(identifier), new DERSet(new DERSequence(new ASN1Encodable[]{new DERSequence(essCertId), new DERSequence(DERNull.INSTANCE)})));

    } catch (CertificateEncodingException ex) {
        throw new SignerException(ex.getMessage());
    }
}
 
Example #11
Source File: BouncyCastleV1CryptoProvider.java    From paseto with MIT License 6 votes vote down vote up
@Override
public KeyPair rsaGenerate() {
	RSAKeyPairGenerator keyGen = new RSAKeyPairGenerator();
	keyGen.init(new RSAKeyGenerationParameters(E, new SecureRandom(), RSA_KEY_SIZE,
			PrimeCertaintyCalculator.getDefaultCertainty(RSA_KEY_SIZE)));
	AsymmetricCipherKeyPair pair = keyGen.generateKeyPair();

	RSAKeyParameters pub = (RSAKeyParameters) pair.getPublic();
	RSAPrivateCrtKeyParameters priv = (RSAPrivateCrtKeyParameters) pair.getPrivate();

	// As in BCRSAPrivateKey / BCRSAPublicKey
	AlgorithmIdentifier algo = new AlgorithmIdentifier(PKCSObjectIdentifiers.rsaEncryption, DERNull.INSTANCE);
	byte[] publicKey = KeyUtil.getEncodedSubjectPublicKeyInfo(algo, new RSAPublicKey(pub.getModulus(),
			pub.getExponent()));
	byte[] privateKey = KeyUtil.getEncodedPrivateKeyInfo(algo, new RSAPrivateKey(priv.getModulus(),
			priv.getPublicExponent(), priv.getExponent(), priv.getP(), priv.getQ(), priv.getDP(), priv.getDQ(),
			priv.getQInv()));

	return new KeyPair(privateKey, publicKey);
}
 
Example #12
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);
}
 
Example #13
Source File: SignInSteps.java    From testarea-itext5 with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * <a href="http://stackoverflow.com/questions/33305800/difference-between-sha256withrsa-and-sha256-then-rsa">
 * Difference between SHA256withRSA and SHA256 then RSA
 * </a>
 * <p>
 * This method is the updated code provided by the OP. As expected it shows two equal signatures.
 * The OP's observations seem to differ, though.
 * </p>
 */
public void testAsGreenhandUpdated(PrivateKey privateKey) throws GeneralSecurityException, IOException
{
    System.out.println("\nGreenhandUpdated:");

    String s = "1234";
    MessageDigest messageDigest = MessageDigest.getInstance("SHA-256");
    messageDigest.update(s.getBytes());
    byte[] outputDigest = messageDigest.digest();

    AlgorithmIdentifier sha256Aid = new AlgorithmIdentifier(NISTObjectIdentifiers.id_sha256, DERNull.INSTANCE);
    DigestInfo di = new DigestInfo(sha256Aid, outputDigest);
    //sign SHA256 with RSA
    Signature rsaSignature = Signature.getInstance("RSA");
    rsaSignature.initSign(privateKey);
    byte[] encodedDigestInfo = di.toASN1Primitive().getEncoded();
    rsaSignature.update(encodedDigestInfo);
    byte[] signed = rsaSignature.sign();
    System.out.println("method 1: "+bytesToHex(signed));
    System.out.println("    hash: " + bytesToHex(outputDigest));
    System.out.println("    algo: " + sha256Aid.getAlgorithm());
    System.out.println("    info: " + bytesToHex(encodedDigestInfo));

    //compute SHA256withRSA as a single step
    Signature rsaSha256Signature = Signature.getInstance("SHA256withRSA");
    rsaSha256Signature.initSign(privateKey);
    rsaSha256Signature.update(s.getBytes());
    byte[] signed2 = rsaSha256Signature.sign();
    System.out.println("method 2: "+bytesToHex(signed2));
}
 
Example #14
Source File: CaClientExample.java    From xipki with Apache License 2.0 5 votes vote down vote up
protected static MyKeypair generateRsaKeypair() throws Exception {
  KeyPairGenerator kpGen = KeyPairGenerator.getInstance("RSA");
  kpGen.initialize(2048);

  KeyPair kp = kpGen.generateKeyPair();
  RSAPublicKey pubKey = (RSAPublicKey) kp.getPublic();

  SubjectPublicKeyInfo subjectPublicKeyInfo = new SubjectPublicKeyInfo(
      new AlgorithmIdentifier(PKCSObjectIdentifiers.rsaEncryption, DERNull.INSTANCE),
      new org.bouncycastle.asn1.pkcs.RSAPublicKey(pubKey.getModulus(),
          pubKey.getPublicExponent()));
  return new MyKeypair(kp.getPrivate(), subjectPublicKeyInfo);
}
 
Example #15
Source File: CaClientExample.java    From xipki with Apache License 2.0 5 votes vote down vote up
protected static MyKeypair generateRsaKeypair() throws Exception {
  KeyPairGenerator kpGen = KeyPairGenerator.getInstance("RSA");
  kpGen.initialize(2048);

  KeyPair kp = kpGen.generateKeyPair();
  RSAPublicKey pubKey = (RSAPublicKey) kp.getPublic();

  SubjectPublicKeyInfo subjectPublicKeyInfo = new SubjectPublicKeyInfo(
      new AlgorithmIdentifier(PKCSObjectIdentifiers.rsaEncryption, DERNull.INSTANCE),
      new org.bouncycastle.asn1.pkcs.RSAPublicKey(pubKey.getModulus(),
          pubKey.getPublicExponent()));
  return new MyKeypair(kp.getPrivate(), subjectPublicKeyInfo);
}
 
Example #16
Source File: KeypairGenControl.java    From xipki with Apache License 2.0 5 votes vote down vote up
public RSAKeypairGenControl(int keysize, BigInteger publicExponent,
    ASN1ObjectIdentifier keyAlgorithmOid) {
  if (keysize < 1024 || keysize % 512 != 0) {
    throw new IllegalArgumentException("invalid keysize " + keysize);
  }

  this.keysize = keysize;
  this.publicExponent = (publicExponent != null) ? publicExponent
      : BigInteger.valueOf(0x10001);
  this.keyAlgorithm = new AlgorithmIdentifier(
      (keyAlgorithmOid != null) ? keyAlgorithmOid : PKCSObjectIdentifiers.rsaEncryption,
      DERNull.INSTANCE);
}
 
Example #17
Source File: P12KeyGenerator.java    From xipki with Apache License 2.0 5 votes vote down vote up
private KeyPairWithSubjectPublicKeyInfo genRSAKeypair(int keysize,
    BigInteger publicExponent, SecureRandom random) throws Exception {
  KeyPair kp = KeyUtil.generateRSAKeypair(keysize, publicExponent, random);
  java.security.interfaces.RSAPublicKey rsaPubKey =
      (java.security.interfaces.RSAPublicKey) kp.getPublic();

  SubjectPublicKeyInfo spki = new SubjectPublicKeyInfo(
      new AlgorithmIdentifier(PKCSObjectIdentifiers.rsaEncryption, DERNull.INSTANCE),
      new RSAPublicKey(rsaPubKey.getModulus(), rsaPubKey.getPublicExponent()));
  return new KeyPairWithSubjectPublicKeyInfo(kp, spki);
}
 
Example #18
Source File: CaEnrollBenchKeyEntry.java    From xipki with Apache License 2.0 5 votes vote down vote up
public RSAKeyEntry(int keysize) throws Exception {
  if (keysize % 1024 != 0) {
    throw new IllegalArgumentException("invalid RSA keysize " + keysize);
  }

  AlgorithmIdentifier keyAlgId = new AlgorithmIdentifier(
      PKCSObjectIdentifiers.rsaEncryption, DERNull.INSTANCE);

  String modulusStr;
  if (keysize == 1024 || keysize == 2048 || keysize == 3072 || keysize == 4096) {
    if (keysize == 1024) {
      modulusStr = N_1024;
    } else if (keysize == 2048) {
      modulusStr = N_2048;
    } else if (keysize == 3072) {
      modulusStr = N_3072;
    } else { // if (keysize == 4096) {
      modulusStr = N_4096;
    }
    BigInteger modulus = base64ToInt(modulusStr);
    this.spki = new SubjectPublicKeyInfo(keyAlgId,
        new org.bouncycastle.asn1.pkcs.RSAPublicKey(modulus, PUBLIC_EXPONENT));
  } else {
    KeyPairGenerator kp = KeyPairGenerator.getInstance("RSA");
    kp.initialize(keysize);
    RSAPublicKey publicKey = (RSAPublicKey) kp.generateKeyPair().getPublic();
    this.spki = new SubjectPublicKeyInfo(keyAlgId,
        new org.bouncycastle.asn1.pkcs.RSAPublicKey(
            publicKey.getModulus(), publicKey.getPublicExponent()));
  }
}
 
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: AlgorithmUtil.java    From xipki with Apache License 2.0 5 votes vote down vote up
private static AlgorithmIdentifier getRSASigAlgId(HashAlgo hashAlgo, boolean mgf1)
    throws NoSuchAlgorithmException {
  Args.notNull(hashAlgo, "hashAlgo");
  if (mgf1) {
    return buildRSAPSSAlgId(hashAlgo);
  }

  ASN1ObjectIdentifier sigAlgOid = digestToRSASigAlgMap.get(hashAlgo);
  if (sigAlgOid == null) {
    throw new NoSuchAlgorithmException("unsupported hash " + hashAlgo + " for RSA key");
  }

  return new AlgorithmIdentifier(sigAlgOid, DERNull.INSTANCE);
}
 
Example #21
Source File: CAdESSignature.java    From dss with GNU Lesser General Public License v2.1 5 votes vote down vote up
public DigestAlgorithm getPSSHashAlgorithm() {
	try {
		byte[] encryptionAlgParams = signerInformation.getEncryptionAlgParams();
		if (Utils.isArrayNotEmpty(encryptionAlgParams) && !Arrays.equals(DERNull.INSTANCE.getEncoded(), encryptionAlgParams)) {
			RSASSAPSSparams param = RSASSAPSSparams.getInstance(encryptionAlgParams);
			AlgorithmIdentifier pssHashAlgo = param.getHashAlgorithm();
			return DigestAlgorithm.forOID(pssHashAlgo.getAlgorithm().getId());
		}
	} catch (IOException e) {
		LOG.error("Unable to analyze EncryptionAlgParams", e);
	}
	return null;
}
 
Example #22
Source File: AlgorithmUtil.java    From xipki with Apache License 2.0 5 votes vote down vote up
public static AlgorithmIdentifier getMacAlgId(String macAlgName) throws NoSuchAlgorithmException {
  String algoS = Args.notNull(macAlgName, "macAlgName").toUpperCase();
  algoS = canonicalizeAlgoText(algoS);

  ASN1ObjectIdentifier oid = macAlgNameToOidMap.get(algoS);
  if (oid == null) {
    throw new NoSuchAlgorithmException("unsupported MAC algorithm " + algoS);
  }
  return new AlgorithmIdentifier(oid, DERNull.INSTANCE);
}
 
Example #23
Source File: SAML2SPKeystoreTest.java    From syncope with Apache License 2.0 5 votes vote down vote up
private static Certificate createSelfSignedCert(final KeyPair keyPair) throws Exception {
    final X500Name dn = new X500Name("cn=Unknown");
    final V3TBSCertificateGenerator certGen = new V3TBSCertificateGenerator();

    certGen.setSerialNumber(new ASN1Integer(BigInteger.valueOf(1)));
    certGen.setIssuer(dn);
    certGen.setSubject(dn);
    certGen.setStartDate(new Time(new Date(System.currentTimeMillis() - 1000L)));

    final Date expiration = new Date(System.currentTimeMillis() + 100000);
    certGen.setEndDate(new Time(expiration));

    final AlgorithmIdentifier sigAlgID = new AlgorithmIdentifier(PKCSObjectIdentifiers.sha1WithRSAEncryption, DERNull.INSTANCE);
    certGen.setSignature(sigAlgID);
    certGen.setSubjectPublicKeyInfo(SubjectPublicKeyInfo.getInstance(keyPair.getPublic().getEncoded()));

    final Signature sig = Signature.getInstance("SHA1WithRSA");
    sig.initSign(keyPair.getPrivate());
    sig.update(certGen.generateTBSCertificate().getEncoded(ASN1Encoding.DER));

    final TBSCertificate tbsCert = certGen.generateTBSCertificate();
    final ASN1EncodableVector v = new ASN1EncodableVector();

    v.add(tbsCert);
    v.add(sigAlgID);
    v.add(new DERBitString(sig.sign()));

    final Certificate cert = CertificateFactory.getInstance("X.509")
        .generateCertificate(new ByteArrayInputStream(new DERSequence(v).getEncoded(ASN1Encoding.DER)));
    cert.verify(keyPair.getPublic());
    return cert;
}
 
Example #24
Source File: BaseSyncopeWASAML2ClientTest.java    From syncope with Apache License 2.0 5 votes vote down vote up
protected static Certificate createSelfSignedCert(final KeyPair keyPair) throws Exception {
    final X500Name dn = new X500Name("cn=Unknown");
    final V3TBSCertificateGenerator certGen = new V3TBSCertificateGenerator();

    certGen.setSerialNumber(new ASN1Integer(BigInteger.valueOf(1)));
    certGen.setIssuer(dn);
    certGen.setSubject(dn);
    certGen.setStartDate(new Time(new Date(System.currentTimeMillis() - 1000L)));

    final Date expiration = new Date(System.currentTimeMillis() + 100000);
    certGen.setEndDate(new Time(expiration));

    final AlgorithmIdentifier sigAlgID = new AlgorithmIdentifier(PKCSObjectIdentifiers.sha1WithRSAEncryption, DERNull.INSTANCE);
    certGen.setSignature(sigAlgID);
    certGen.setSubjectPublicKeyInfo(SubjectPublicKeyInfo.getInstance(keyPair.getPublic().getEncoded()));

    final Signature sig = Signature.getInstance("SHA1WithRSA");
    sig.initSign(keyPair.getPrivate());
    sig.update(certGen.generateTBSCertificate().getEncoded(ASN1Encoding.DER));

    final TBSCertificate tbsCert = certGen.generateTBSCertificate();
    final ASN1EncodableVector v = new ASN1EncodableVector();

    v.add(tbsCert);
    v.add(sigAlgID);
    v.add(new DERBitString(sig.sign()));

    final Certificate cert = CertificateFactory.getInstance("X.509")
        .generateCertificate(new ByteArrayInputStream(new DERSequence(v).getEncoded(ASN1Encoding.DER)));
    cert.verify(keyPair.getPublic());
    return cert;
}
 
Example #25
Source File: DSSRevocationUtils.java    From dss with GNU Lesser General Public License v2.1 5 votes vote down vote up
public static DigestCalculator getDigestCalculator(DigestAlgorithm digestAlgorithm) {
	try {
		final DigestCalculatorProvider digestCalculatorProvider = jcaDigestCalculatorProviderBuilder.build();
		return digestCalculatorProvider.get(new AlgorithmIdentifier(new ASN1ObjectIdentifier(digestAlgorithm.getOid()), DERNull.INSTANCE));
	} catch (OperatorCreationException e) {
		throw new DSSException(
				String.format("Unable to create a DigestCalculator instance. DigestAlgorithm %s is not supported", digestAlgorithm.name()), e);
	}
}
 
Example #26
Source File: SelectedCommitmentTypes.java    From signer with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
public void parse(ASN1Primitive derObject) {
    ASN1Sequence derSequence = ASN1Object.getDERSequence(derObject);
    ASN1Primitive object = derSequence.getObjectAt(0).toASN1Primitive();
    if (object instanceof DERNull) {
        this.recognizedCommitmentType = null;
    } else if (object instanceof DERSequence) {
        this.recognizedCommitmentType = new CommitmentType();
        this.recognizedCommitmentType.parse(object);
    }
}
 
Example #27
Source File: ExtensionSyntaxChecker.java    From xipki with Apache License 2.0 4 votes vote down vote up
private static ASN1Encodable getParsedImplicitValue(String name, ASN1TaggedObject taggedObject,
    FieldType fieldType) throws BadCertTemplateException {
  try {
    switch (fieldType) {
      case BIT_STRING:
        return DERBitString.getInstance(taggedObject, false);
      case BMPString:
        return DERBMPString.getInstance(taggedObject, false);
      case BOOLEAN:
        return ASN1Boolean.getInstance(taggedObject, false);
      case ENUMERATED:
        return ASN1Enumerated.getInstance(taggedObject, false);
      case GeneralizedTime:
        return DERGeneralizedTime.getInstance(taggedObject, false);
      case IA5String:
        return DERIA5String.getInstance(taggedObject, false);
      case INTEGER:
        return ASN1Integer.getInstance(taggedObject, false);
      case Name:
        return X500Name.getInstance(taggedObject, false);
      case NULL:
        if (!(taggedObject.getObject() instanceof ASN1OctetString
            && ((ASN1OctetString) taggedObject.getObject()).getOctets().length == 0)) {
          throw new BadCertTemplateException("invalid " + name);
        }
        return DERNull.INSTANCE;
      case OCTET_STRING:
        return DEROctetString.getInstance(taggedObject, false);
      case OID:
        return ASN1ObjectIdentifier.getInstance(taggedObject, false);
      case PrintableString:
        return DERPrintableString.getInstance(taggedObject, false);
      case RAW:
        return taggedObject.getObject();
      case SEQUENCE:
      case SEQUENCE_OF:
        return ASN1Sequence.getInstance(taggedObject, false);
      case SET:
      case SET_OF:
        return ASN1Set.getInstance(taggedObject, false);
      case TeletexString:
        return DERT61String.getInstance(taggedObject, false);
      case UTCTime:
        return DERUTCTime.getInstance(taggedObject, false);
      case UTF8String:
        return DERUTF8String.getInstance(taggedObject, false);
      default:
        throw new RuntimeException("Unknown FieldType " + fieldType);
    }
  } catch (IllegalArgumentException ex) {
    throw new BadCertTemplateException("invalid " + name, ex);
  }
}
 
Example #28
Source File: ProfileConfCreatorDemo.java    From xipki with Apache License 2.0 4 votes vote down vote up
private static List<ExtensionType> createConstantExtensions(
    ASN1ObjectIdentifier oidPrefix, Tag tag) throws IOException {
  List<ExtensionType> list = new LinkedList<>();

  // Custom Constant Extension Value
  list.add(createConstantExtension(oidPrefix.branch("1"), true, false, tag,
      FieldType.BIT_STRING, Base64.encodeToString(new byte[] {1, 2})));
  list.add(createConstantExtension(oidPrefix.branch("2"), true, false, tag,
      FieldType.BMPString, "A BMP string"));
  list.add(createConstantExtension(oidPrefix.branch("3"), true, false, tag,
      FieldType.BOOLEAN, Boolean.TRUE.toString()));
  list.add(createConstantExtension(oidPrefix.branch("4"), true, false, tag,
      FieldType.IA5String, "An IA5 string"));
  list.add(createConstantExtension(oidPrefix.branch("5"), true, false, tag,
      FieldType.INTEGER, "10"));
  list.add(createConstantExtension(oidPrefix.branch("6"), true, false, tag,
      FieldType.NULL, null));
  list.add(createConstantExtension(oidPrefix.branch("7"), true, false, tag,
      FieldType.OCTET_STRING, Base64.encodeToString(new byte[] {3, 4})));
  list.add(createConstantExtension(oidPrefix.branch("8"), true, false, tag,
      FieldType.OID, "2.3.4.5"));
  list.add(createConstantExtension(oidPrefix.branch("9"), true, false, tag,
      FieldType.PrintableString, "A printable string"));
  list.add(createConstantExtension(oidPrefix.branch("10"), true, false, tag,
      FieldType.RAW, Base64.encodeToString(DERNull.INSTANCE.getEncoded())));
  last(list).getConstant().setDescription("DER NULL");

  list.add(createConstantExtension(oidPrefix.branch("11"), true, false, tag,
      FieldType.TeletexString, "A teletax string"));
  list.add(createConstantExtension(oidPrefix.branch("12"), true, false, tag,
      FieldType.UTF8String, "A UTF8 string"));
  list.add(createConstantExtension(oidPrefix.branch("13"), true, false, tag,
      FieldType.ENUMERATED, "2"));
  list.add(createConstantExtension(oidPrefix.branch("14"), true, false, tag,
      FieldType.GeneralizedTime, new ASN1GeneralizedTime("20180314130102Z").getTimeString()));
  list.add(createConstantExtension(oidPrefix.branch("15"), true, false, tag,
      FieldType.UTCTime, "190314130102Z"));
  list.add(createConstantExtension(oidPrefix.branch("16"), true, false, tag,
      FieldType.Name, "CN=abc,C=DE"));

  list.add(createConstantExtension(oidPrefix.branch("17"), true, false, tag,
      FieldType.SEQUENCE, null));
  last(list).getConstant().setListValue(createConstantSequenceOrSet());

  list.add(createConstantExtension(oidPrefix.branch("18"), true, false, tag,
      FieldType.SEQUENCE_OF, null));
  last(list).getConstant().setListValue(createConstantSequenceOfOrSetOf());

  list.add(createConstantExtension(oidPrefix.branch("19"), true, false, tag,
      FieldType.SET, null));
  last(list).getConstant().setListValue(createConstantSequenceOrSet());

  list.add(createConstantExtension(oidPrefix.branch("20"), true, false, tag,
      FieldType.SET_OF, null));
  last(list).getConstant().setListValue(createConstantSequenceOfOrSetOf());

  return list;
}
 
Example #29
Source File: ExtensionSyntaxChecker.java    From xipki with Apache License 2.0 4 votes vote down vote up
private static FieldType getFieldType(ASN1Encodable obj) {
  FieldType expectedType;
  if (obj instanceof DERBitString) {
    expectedType = FieldType.BIT_STRING;
  } else if (obj instanceof DERBMPString) {
    expectedType = FieldType.BMPString;
  } else if (obj instanceof ASN1Boolean) {
    expectedType = FieldType.BOOLEAN;
  } else if (obj instanceof ASN1Enumerated) {
    expectedType = FieldType.ENUMERATED;
  } else if (obj instanceof DERGeneralizedTime) {
    expectedType = FieldType.GeneralizedTime;
  } else if (obj instanceof DERIA5String) {
    expectedType = FieldType.IA5String;
  } else if (obj instanceof ASN1Integer) {
    expectedType = FieldType.INTEGER;
  } else if (obj instanceof DERNull) {
    expectedType = FieldType.NULL;
  } else if (obj instanceof DEROctetString) {
    expectedType = FieldType.OCTET_STRING;
  } else if (obj instanceof ASN1ObjectIdentifier) {
    expectedType = FieldType.OID;
  } else if (obj instanceof DERPrintableString) {
    expectedType = FieldType.PrintableString;
  } else if (obj instanceof DERT61String) {
    expectedType = FieldType.TeletexString;
  } else if (obj instanceof DERUTCTime) {
    expectedType = FieldType.UTCTime;
  } else if (obj instanceof DERUTF8String) {
    expectedType = FieldType.UTF8String;
  } else if (obj instanceof X500Name) {
    expectedType = FieldType.Name;
  } else if (obj instanceof ASN1Sequence) {
    try {
      X500Name.getInstance(obj);
      expectedType = FieldType.Name;
    } catch (Exception ex) {
      expectedType = FieldType.SEQUENCE;
    }
  } else if (obj instanceof ASN1Set) {
    expectedType = FieldType.SET;
  } else {
    expectedType = null;
  }

  return expectedType;
}
 
Example #30
Source File: Pkcs12SHA256withRSATest.java    From xipki with Apache License 2.0 4 votes vote down vote up
@Override
protected AlgorithmIdentifier getSignatureAlgorithm() {
  return new AlgorithmIdentifier(PKCSObjectIdentifiers.sha256WithRSAEncryption,
      DERNull.INSTANCE);
}