Java Code Examples for org.bouncycastle.asn1.DERNull#INSTANCE

The following examples show how to use org.bouncycastle.asn1.DERNull#INSTANCE . 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: 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 3
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 4
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 5
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 6
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 7
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 8
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 9
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 10
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 11
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 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: 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 15
Source File: EmulatorP11Slot.java    From xipki with Apache License 2.0 4 votes vote down vote up
private static AlgorithmIdentifier buildAlgId(ASN1ObjectIdentifier identifier) {
  return new AlgorithmIdentifier(identifier, DERNull.INSTANCE);
}
 
Example 16
Source File: RequestOptions.java    From xipki with Apache License 2.0 4 votes vote down vote up
private static AlgorithmIdentifier createAlgId(String algoName) {
  algoName = algoName.toUpperCase();
  ASN1ObjectIdentifier algOid = null;
  if ("SHA1WITHRSA".equals(algoName)) {
    algOid = PKCSObjectIdentifiers.sha1WithRSAEncryption;
  } else if ("SHA256WITHRSA".equals(algoName)) {
    algOid = PKCSObjectIdentifiers.sha256WithRSAEncryption;
  } else if ("SHA384WITHRSA".equals(algoName)) {
    algOid = PKCSObjectIdentifiers.sha384WithRSAEncryption;
  } else if ("SHA512WITHRSA".equals(algoName)) {
    algOid = PKCSObjectIdentifiers.sha512WithRSAEncryption;
  } else if ("SHA1WITHECDSA".equals(algoName)) {
    algOid = X9ObjectIdentifiers.ecdsa_with_SHA1;
  } else if ("SHA256WITHECDSA".equals(algoName)) {
    algOid = X9ObjectIdentifiers.ecdsa_with_SHA256;
  } else if ("SHA384WITHECDSA".equals(algoName)) {
    algOid = X9ObjectIdentifiers.ecdsa_with_SHA384;
  } else if ("SHA512WITHECDSA".equals(algoName)) {
    algOid = X9ObjectIdentifiers.ecdsa_with_SHA512;
  } else if ("SHA1WITHRSAANDMGF1".equals(algoName) || "SHA256WITHRSAANDMGF1".equals(algoName)
      || "SHA384WITHRSAANDMGF1".equals(algoName) || "SHA512WITHRSAANDMGF1".equals(algoName)) {
    algOid = PKCSObjectIdentifiers.id_RSASSA_PSS;
  } else {
    throw new IllegalStateException("Unsupported algorithm " + algoName); // should not happen
  }

  ASN1Encodable params;
  if (PKCSObjectIdentifiers.id_RSASSA_PSS.equals(algOid)) {
    ASN1ObjectIdentifier digestAlgOid = null;
    if ("SHA1WITHRSAANDMGF1".equals(algoName)) {
      digestAlgOid = X509ObjectIdentifiers.id_SHA1;
    } else if ("SHA256WITHRSAANDMGF1".equals(algoName)) {
      digestAlgOid = NISTObjectIdentifiers.id_sha256;
    } else if ("SHA384WITHRSAANDMGF1".equals(algoName)) {
      digestAlgOid = NISTObjectIdentifiers.id_sha384;
    } else { // if ("SHA512WITHRSAANDMGF1".equals(algoName))
      digestAlgOid = NISTObjectIdentifiers.id_sha512;
    }
    params = createPSSRSAParams(digestAlgOid);
  } else {
    params = DERNull.INSTANCE;
  }

  return new AlgorithmIdentifier(algOid, params);
}
 
Example 17
Source File: CmpUtil.java    From xipki with Apache License 2.0 4 votes vote down vote up
public static InfoTypeAndValue getImplictConfirmGeneralInfo() {
  return new InfoTypeAndValue(CMPObjectIdentifiers.it_implicitConfirm, DERNull.INSTANCE);
}
 
Example 18
Source File: P12KeyGenerator.java    From xipki with Apache License 2.0 4 votes vote down vote up
private static AlgorithmIdentifier buildAlgId(ASN1ObjectIdentifier identifier) {
  return new AlgorithmIdentifier(identifier, DERNull.INSTANCE);
}
 
Example 19
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);
}
 
Example 20
Source File: DSSUtils.java    From dss with GNU Lesser General Public License v2.1 3 votes vote down vote up
/**
 * This method wraps the digest value in a DigestInfo (combination of digest
 * algorithm and value). This encapsulation is required to operate NONEwithRSA
 * signatures.
 * 
 * @param digestAlgorithm
 *                        the used digest algorithm
 * @param digest
 *                        the digest value
 * @return DER encoded binaries of the related digest info
 */
public static byte[] encodeRSADigest(final DigestAlgorithm digestAlgorithm, final byte[] digest) {
	try {
		AlgorithmIdentifier algId = new AlgorithmIdentifier(new ASN1ObjectIdentifier(digestAlgorithm.getOid()), DERNull.INSTANCE);
		DigestInfo digestInfo = new DigestInfo(algId, digest);
		return digestInfo.getEncoded(ASN1Encoding.DER);
	} catch (IOException e) {
		throw new DSSException("Unable to encode digest", e);
	}
}