Java Code Examples for org.bouncycastle.asn1.nist.NISTObjectIdentifiers

The following examples show how to use org.bouncycastle.asn1.nist.NISTObjectIdentifiers. These examples are extracted from open source projects. 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 Project: protect   Source File: RsaSigningClient.java    License: 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 2
Source Project: protect   Source File: RsaCertificateAuthorityClient.java    License: 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 3
@Override
	public Attribute getValue() throws SignerException {
		try {
			X509Certificate cert = (X509Certificate) certificates[0];
			X509Certificate issuerCert = (X509Certificate) certificates[1];
			Digest digest = DigestFactory.getInstance().factoryDefault();
			digest.setAlgorithm(DigestAlgorithmEnum.SHA_256);
			byte[] certHash = digest.digest(cert.getEncoded());
			X500Name dirName = new X500Name(issuerCert.getSubjectX500Principal().getName());
			GeneralName name = new GeneralName(dirName);
			GeneralNames issuer = new GeneralNames(name);
			ASN1Integer serialNumber = new ASN1Integer(cert.getSerialNumber());
			IssuerSerial issuerSerial = new IssuerSerial(issuer, serialNumber);
			AlgorithmIdentifier algId = new AlgorithmIdentifier(NISTObjectIdentifiers.id_sha256);// SHA-256
			ESSCertIDv2 essCertIDv2 = new ESSCertIDv2(algId, certHash, issuerSerial);
//			return new Attribute(new ASN1ObjectIdentifier(identifier), new DERSet(new DERSequence(essCertIDv2)));
			return new Attribute(new ASN1ObjectIdentifier(identifier), new DERSet(new DERSequence(
					new ASN1Encodable[] { new DERSequence(essCertIDv2) })));
		} catch (CertificateEncodingException ex) {
			throw new SignerException(ex.getMessage());
		}
	}
 
Example 4
Source Project: xipki   Source File: AlgorithmUtil.java    License: 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 5
Source Project: xipki   Source File: AlgorithmUtil.java    License: 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 6
Source Project: xipki   Source File: AlgorithmUtil.java    License: 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 7
Source Project: xipki   Source File: SignatureCmpCaClient.java    License: Apache License 2.0 6 votes vote down vote up
public SignatureCmpCaClient(String caUri, X509Certificate caCert, PrivateKey requestorKey,
    X509Certificate requestorCert, X509Certificate responderCert, String hashAlgo)
    throws Exception {
  super(caUri, caCert,
      X500Name.getInstance(requestorCert.getSubjectX500Principal().getEncoded()),
      X500Name.getInstance(responderCert.getSubjectX500Principal().getEncoded()),
      hashAlgo);

  this.requestorKey = SdkUtil.requireNonNull("requestorKey", requestorKey);
  SdkUtil.requireNonNull("requestorCert", requestorCert);

  this.responderCert = SdkUtil.requireNonNull("responderCert", responderCert);
  this.requestorSigner = buildSigner(requestorKey);

  ASN1ObjectIdentifier[] oids = {PKCSObjectIdentifiers.sha256WithRSAEncryption,
    PKCSObjectIdentifiers.sha384WithRSAEncryption, PKCSObjectIdentifiers.sha512WithRSAEncryption,
    X9ObjectIdentifiers.ecdsa_with_SHA256, X9ObjectIdentifiers.ecdsa_with_SHA384,
    X9ObjectIdentifiers.ecdsa_with_SHA512, NISTObjectIdentifiers.dsa_with_sha256,
    NISTObjectIdentifiers.dsa_with_sha384, NISTObjectIdentifiers.dsa_with_sha512};
  for (ASN1ObjectIdentifier oid : oids) {
    trustedProtectionAlgOids.add(oid.getId());
  }
}
 
Example 8
Source Project: xipki   Source File: RequestOptions.java    License: 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 9
Source Project: snowflake-kafka-connector   Source File: FIPSTest.java    License: Apache License 2.0 5 votes vote down vote up
public static String generateAESKey(PrivateKey key, char[] passwd) throws IOException, OperatorCreationException
{
  Security.addProvider(new BouncyCastleFipsProvider());
  StringWriter writer = new StringWriter();
  JcaPEMWriter pemWriter = new JcaPEMWriter(writer);
  PKCS8EncryptedPrivateKeyInfoBuilder pkcs8EncryptedPrivateKeyInfoBuilder =
    new JcaPKCS8EncryptedPrivateKeyInfoBuilder(key);
  pemWriter.writeObject(pkcs8EncryptedPrivateKeyInfoBuilder
    .build(new JcePKCSPBEOutputEncryptorBuilder(NISTObjectIdentifiers.id_aes256_CBC)
      .setProvider("BCFIPS").build(passwd)));
  pemWriter.close();
  return writer.toString();
}
 
Example 10
Source Project: hedera-sdk-java   Source File: PemUtils.java    License: Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unused")
public static void writeEncryptedPrivateKey(PrivateKeyInfo pkInfo, Writer out, String passphrase) throws IOException {
    byte[] salt = CryptoUtils.randomBytes(CryptoUtils.SALT_LEN);

    KeyParameter derivedKey = CryptoUtils.deriveKeySha256(
        passphrase, salt, CryptoUtils.ITERATIONS, CryptoUtils.CBC_DK_LEN);

    byte[] iv = CryptoUtils.randomBytes(CryptoUtils.IV_LEN);

    Cipher cipher = CryptoUtils.initAesCbc128Encrypt(derivedKey, iv);

    byte[] encryptedKey = CryptoUtils.runCipher(cipher, pkInfo.getEncoded());

    // I wanted to just do this with BC's PKCS8Generator and KcePKCSPBEOutputEncryptorBuilder
    // but it tries to init AES instance of `Cipher` with a `PBKDF2Key` and the former complains

    // So this is basically a reimplementation of that minus the excess OO
    PBES2Parameters parameters = new PBES2Parameters(
        new KeyDerivationFunc(
            PKCSObjectIdentifiers.id_PBKDF2,
            new PBKDF2Params(
                salt,
                CryptoUtils.ITERATIONS,
                CryptoUtils.CBC_DK_LEN,
                new AlgorithmIdentifier(PKCSObjectIdentifiers.id_hmacWithSHA256))),
        new EncryptionScheme(NISTObjectIdentifiers.id_aes128_CBC,
            ASN1Primitive.fromByteArray(cipher.getParameters().getEncoded())));

    EncryptedPrivateKeyInfo encryptedPrivateKeyInfo = new EncryptedPrivateKeyInfo(
        new AlgorithmIdentifier(PKCSObjectIdentifiers.id_PBES2, parameters),
        encryptedKey);

    PemWriter writer = new PemWriter(out);
    writer.writeObject(new PemObject(TYPE_ENCRYPTED_PRIVATE_KEY, encryptedPrivateKeyInfo.getEncoded()));
    writer.flush();
}
 
Example 11
/**
 * <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 12
Source Project: signer   Source File: RevocationRefs.java    License: GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * 
 * 
 * @param extract
 *            CrlValidatedID from X509CRL
 * @return a CrlValidatedID
 * @throws NoSuchAlgorithmException
 * @throws CRLException
 */

private CrlValidatedID makeCrlValidatedID(X509CRL crl)
		throws NoSuchAlgorithmException, CRLException {

	Digest digest = DigestFactory.getInstance().factoryDefault();
	digest.setAlgorithm(DigestAlgorithmEnum.SHA_256);
	
	OtherHashAlgAndValue otherHashAlgAndValue = new OtherHashAlgAndValue(
				new AlgorithmIdentifier(NISTObjectIdentifiers.id_sha256), new DEROctetString(digest.digest(crl.getEncoded())));
	
	OtherHash hash = new OtherHash(otherHashAlgAndValue);

	BigInteger crlnumber;
	CrlIdentifier crlid;
	if (crl.getExtensionValue("2.5.29.20") != null) {
		ASN1Integer varASN1Integer = new ASN1Integer(crl.getExtensionValue("2.5.29.20"));
		crlnumber = varASN1Integer.getPositiveValue();

		crlid = new CrlIdentifier(new X500Name(crl.getIssuerX500Principal()
				.getName()), new DERUTCTime(crl.getThisUpdate()), crlnumber);
	} else {
		crlid = new CrlIdentifier(new X500Name(crl.getIssuerX500Principal()
				.getName()), new DERUTCTime(crl.getThisUpdate()));
	}

	CrlValidatedID crlvid = new CrlValidatedID(hash, crlid);

	return crlvid;
}
 
Example 13
Source Project: xipki   Source File: P11ContentSigner.java    License: Apache License 2.0 5 votes vote down vote up
Mac(P11CryptService cryptService, P11IdentityId identityId,
    AlgorithmIdentifier macAlgId) throws XiSecurityException, P11TokenException {
  super(cryptService, identityId, macAlgId);

  ASN1ObjectIdentifier oid = macAlgId.getAlgorithm();
  if (PKCSObjectIdentifiers.id_hmacWithSHA1.equals(oid)) {
    mechanism = PKCS11Constants.CKM_SHA_1_HMAC;
  } else if (PKCSObjectIdentifiers.id_hmacWithSHA224.equals(oid)) {
    mechanism = PKCS11Constants.CKM_SHA224_HMAC;
  } else if (PKCSObjectIdentifiers.id_hmacWithSHA256.equals(oid)) {
    mechanism = PKCS11Constants.CKM_SHA256_HMAC;
  } else if (PKCSObjectIdentifiers.id_hmacWithSHA384.equals(oid)) {
    mechanism = PKCS11Constants.CKM_SHA384_HMAC;
  } else if (PKCSObjectIdentifiers.id_hmacWithSHA512.equals(oid)) {
    mechanism = PKCS11Constants.CKM_SHA512_HMAC;
  } else if (NISTObjectIdentifiers.id_hmacWithSHA3_224.equals(oid)) {
    mechanism = PKCS11Constants.CKM_SHA3_224_HMAC;
  } else if (NISTObjectIdentifiers.id_hmacWithSHA3_256.equals(oid)) {
    mechanism = PKCS11Constants.CKM_SHA3_256_HMAC;
  } else if (NISTObjectIdentifiers.id_hmacWithSHA3_384.equals(oid)) {
    mechanism = PKCS11Constants.CKM_SHA3_384_HMAC;
  } else if (NISTObjectIdentifiers.id_hmacWithSHA3_512.equals(oid)) {
    mechanism = PKCS11Constants.CKM_SHA3_512_HMAC;
  } else {
    throw new IllegalArgumentException("unknown algorithm identifier " + oid.getId());
  }

  P11Slot slot = cryptService.getSlot(identityId.getSlotId());
  if (slot.supportsMechanism(mechanism)) {
    throw new XiSecurityException("unsupported MAC algorithm " + oid.getId());
  }

  this.outputStream = new ByteArrayOutputStream();
}
 
Example 14
Source Project: xipki   Source File: P12MacContentSignerBuilder.java    License: Apache License 2.0 5 votes vote down vote up
public ConcurrentContentSigner createSigner(AlgorithmIdentifier signatureAlgId,
    int parallelism, SecureRandom random) throws XiSecurityException {
  Args.notNull(signatureAlgId, "signatureAlgId");
  Args.positive(parallelism, "parallelism");

  List<XiContentSigner> signers = new ArrayList<>(parallelism);

  boolean gmac = false;
  ASN1ObjectIdentifier oid = signatureAlgId.getAlgorithm();
  if (oid.equals(NISTObjectIdentifiers.id_aes128_GCM)
      || oid.equals(NISTObjectIdentifiers.id_aes192_GCM)
      || oid.equals(NISTObjectIdentifiers.id_aes256_GCM)) {
    gmac = true;
  }

  for (int i = 0; i < parallelism; i++) {
    XiContentSigner signer;
    if (gmac) {
      signer = new AESGmacContentSigner(oid, key);
    } else {
      signer = new HmacContentSigner(signatureAlgId, key);
    }
    signers.add(signer);
  }

  final boolean mac = true;
  DfltConcurrentContentSigner concurrentSigner;
  try {
    concurrentSigner = new DfltConcurrentContentSigner(mac, signers, key);
  } catch (NoSuchAlgorithmException ex) {
    throw new XiSecurityException(ex.getMessage(), ex);
  }
  concurrentSigner.setSha1DigestOfMacKey(HashAlgo.SHA1.hash(key.getEncoded()));

  return concurrentSigner;
}
 
Example 15
Source Project: xipki   Source File: ScepUtil.java    License: Apache License 2.0 5 votes vote down vote up
public static ASN1ObjectIdentifier extractDigesetAlgorithmIdentifier(String sigOid,
    byte[] sigParams) throws NoSuchAlgorithmException {
  Args.notBlank(sigOid, "sigOid");

  ASN1ObjectIdentifier algOid = new ASN1ObjectIdentifier(sigOid);

  ASN1ObjectIdentifier digestAlgOid;
  if (PKCSObjectIdentifiers.md5WithRSAEncryption.equals(algOid)) {
    digestAlgOid = PKCSObjectIdentifiers.md5;
  } else if (PKCSObjectIdentifiers.sha1WithRSAEncryption.equals(algOid)) {
    digestAlgOid = X509ObjectIdentifiers.id_SHA1;
  } else if (PKCSObjectIdentifiers.sha224WithRSAEncryption.equals(algOid)) {
    digestAlgOid = NISTObjectIdentifiers.id_sha224;
  } else if (PKCSObjectIdentifiers.sha256WithRSAEncryption.equals(algOid)) {
    digestAlgOid = NISTObjectIdentifiers.id_sha256;
  } else if (PKCSObjectIdentifiers.sha384WithRSAEncryption.equals(algOid)) {
    digestAlgOid = NISTObjectIdentifiers.id_sha384;
  } else if (PKCSObjectIdentifiers.sha512WithRSAEncryption.equals(algOid)) {
    digestAlgOid = NISTObjectIdentifiers.id_sha512;
  } else if (PKCSObjectIdentifiers.id_RSASSA_PSS.equals(algOid)) {
    RSASSAPSSparams param = RSASSAPSSparams.getInstance(sigParams);
    digestAlgOid = param.getHashAlgorithm().getAlgorithm();
  } else {
    throw new NoSuchAlgorithmException("unknown signature algorithm" + algOid.getId());
  }

  return digestAlgOid;
}
 
Example 16
Source Project: hedera-sdk-java   Source File: PemUtils.java    License: Apache License 2.0 4 votes vote down vote up
private static PrivateKeyInfo decryptPrivateKey(byte[] encodedStruct, String passphrase) throws IOException {
    PKCS8EncryptedPrivateKeyInfo encryptedPrivateKeyInfo = new PKCS8EncryptedPrivateKeyInfo(encodedStruct);

    AlgorithmIdentifier encryptAlg = encryptedPrivateKeyInfo.getEncryptionAlgorithm();

    if (!encryptAlg.getAlgorithm().equals(PKCSObjectIdentifiers.id_PBES2)) {
        throw new BadKeyException("unsupported PEM key encryption: " + encryptAlg);
    }

    PBES2Parameters params = PBES2Parameters.getInstance(encryptAlg.getParameters());
    KeyDerivationFunc kdf = params.getKeyDerivationFunc();
    EncryptionScheme encScheme = params.getEncryptionScheme();

    if (!kdf.getAlgorithm().equals(PKCSObjectIdentifiers.id_PBKDF2)) {
        throw new BadKeyException("unsupported KDF: " + kdf.getAlgorithm());
    }

    if (!encScheme.getAlgorithm().equals(NISTObjectIdentifiers.id_aes128_CBC)) {
        throw new BadKeyException("unsupported encryption: " + encScheme.getAlgorithm());
    }

    PBKDF2Params kdfParams = PBKDF2Params.getInstance(kdf.getParameters());

    if (!kdfParams.getPrf().getAlgorithm().equals(PKCSObjectIdentifiers.id_hmacWithSHA256)) {
        throw new BadKeyException("unsupported PRF: " + kdfParams.getPrf());
    }

    int keyLength = kdfParams.getKeyLength() != null
        ? kdfParams.getKeyLength().intValueExact()
        : CryptoUtils.CBC_DK_LEN;

    KeyParameter derivedKey = CryptoUtils.deriveKeySha256(
        passphrase,
        kdfParams.getSalt(),
        kdfParams.getIterationCount().intValueExact(),
        keyLength);

    AlgorithmParameters aesParams;
    try {
        aesParams = AlgorithmParameters.getInstance("AES");
    } catch (NoSuchAlgorithmException e) {
        throw new RuntimeException(e);
    }
    aesParams.init(encScheme.getParameters().toASN1Primitive().getEncoded());

    Cipher cipher = CryptoUtils.initAesCbc128Decrypt(derivedKey, aesParams);
    byte[] decrypted = CryptoUtils.runCipher(cipher, encryptedPrivateKeyInfo.getEncryptedData());

    // we need to parse our input data as the cipher may add padding
    ASN1InputStream inputStream = new ASN1InputStream(new ByteArrayInputStream(decrypted));
    return PrivateKeyInfo.getInstance(inputStream.readObject());
}
 
Example 17
Source Project: xipki   Source File: RequestOptions.java    License: 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 18
Source Project: keycloak   Source File: OcspHandler.java    License: Apache License 2.0 4 votes vote down vote up
@Override
public void handleRequest(final HttpServerExchange exchange) throws Exception {
    if (exchange.isInIoThread()) {
        exchange.dispatch(this);
        return;
    }

    final byte[] buffy = new byte[16384];
    try (InputStream requestStream = exchange.getInputStream()) {
        requestStream.read(buffy);
    }

    final OCSPReq request = new OCSPReq(buffy);
    final Req[] requested = request.getRequestList();

    final Extension nonce = request.getExtension(OCSPObjectIdentifiers.id_pkix_ocsp_nonce);

    final DigestCalculator sha1Calculator = new JcaDigestCalculatorProviderBuilder().build()
            .get(AlgorithmIdentifier.getInstance(RespID.HASH_SHA1));

    final BasicOCSPRespBuilder responseBuilder = new BasicOCSPRespBuilder(subjectPublicKeyInfo, sha1Calculator);

    if (nonce != null) {
        responseBuilder.setResponseExtensions(new Extensions(nonce));
    }

    for (final Req req : requested) {
        final CertificateID certId = req.getCertID();

        final BigInteger certificateSerialNumber = certId.getSerialNumber();
        responseBuilder.addResponse(certId, REVOKED_CERTIFICATES_STATUS.get(certificateSerialNumber));
    }

    final ContentSigner contentSigner = new BcRSAContentSignerBuilder(
            new AlgorithmIdentifier(PKCSObjectIdentifiers.sha256WithRSAEncryption),
            new AlgorithmIdentifier(NISTObjectIdentifiers.id_sha256)).build(privateKey);

    final OCSPResp response = new OCSPRespBuilder().build(OCSPResp.SUCCESSFUL,
            responseBuilder.build(contentSigner, chain, new Date()));

    final byte[] responseBytes = response.getEncoded();

    final HeaderMap responseHeaders = exchange.getResponseHeaders();
    responseHeaders.put(Headers.CONTENT_TYPE, "application/ocsp-response");

    final Sender responseSender = exchange.getResponseSender();
    responseSender.send(ByteBuffer.wrap(responseBytes));

    exchange.endExchange();
}