use of org.bouncycastle.asn1.ASN1Integer in project jruby-openssl by jruby.
the class MiscPEMGenerator method createPemObject.
private PemObject createPemObject(Object o) throws IOException {
String type;
byte[] encoding;
if (o instanceof PemObject) {
return (PemObject) o;
}
if (o instanceof PemObjectGenerator) {
return ((PemObjectGenerator) o).generate();
}
if (o instanceof X509CertificateHolder) {
type = "CERTIFICATE";
encoding = ((X509CertificateHolder) o).getEncoded();
} else if (o instanceof X509CRLHolder) {
type = "X509 CRL";
encoding = ((X509CRLHolder) o).getEncoded();
} else if (o instanceof PrivateKeyInfo) {
PrivateKeyInfo info = (PrivateKeyInfo) o;
ASN1ObjectIdentifier algOID = info.getPrivateKeyAlgorithm().getAlgorithm();
if (algOID.equals(PKCSObjectIdentifiers.rsaEncryption)) {
type = "RSA PRIVATE KEY";
encoding = info.parsePrivateKey().toASN1Primitive().getEncoded();
} else if (algOID.equals(dsaOids[0]) || algOID.equals(dsaOids[1])) {
type = "DSA PRIVATE KEY";
DSAParameter p = DSAParameter.getInstance(info.getPrivateKeyAlgorithm().getParameters());
ASN1EncodableVector v = new ASN1EncodableVector();
v.add(new ASN1Integer(BigInteger.ZERO));
v.add(new ASN1Integer(p.getP()));
v.add(new ASN1Integer(p.getQ()));
v.add(new ASN1Integer(p.getG()));
BigInteger x = ASN1Integer.getInstance(info.parsePrivateKey()).getValue();
BigInteger y = p.getG().modPow(x, p.getP());
v.add(new ASN1Integer(y));
v.add(new ASN1Integer(x));
encoding = new DERSequence(v).getEncoded();
} else if (algOID.equals(X9ObjectIdentifiers.id_ecPublicKey)) {
type = "EC PRIVATE KEY";
encoding = info.parsePrivateKey().toASN1Primitive().getEncoded();
} else {
throw new IOException("Cannot identify private key");
}
} else if (o instanceof SubjectPublicKeyInfo) {
type = "PUBLIC KEY";
encoding = ((SubjectPublicKeyInfo) o).getEncoded();
} else if (o instanceof X509AttributeCertificateHolder) {
type = "ATTRIBUTE CERTIFICATE";
encoding = ((X509AttributeCertificateHolder) o).getEncoded();
} else if (o instanceof PKCS10CertificationRequest) {
type = "CERTIFICATE REQUEST";
encoding = ((PKCS10CertificationRequest) o).getEncoded();
} else if (o instanceof ContentInfo) {
type = "PKCS7";
encoding = ((ContentInfo) o).getEncoded();
} else //
if (// 1.47 compatibility
o instanceof java.security.cert.X509Certificate) {
type = "CERTIFICATE";
try {
encoding = ((java.security.cert.X509Certificate) o).getEncoded();
} catch (CertificateEncodingException e) {
throw new PemGenerationException("Cannot encode object: " + e.toString());
}
} else if (// 1.47 compatibility
o instanceof java.security.cert.X509CRL) {
type = "X509 CRL";
try {
encoding = ((java.security.cert.X509CRL) o).getEncoded();
} catch (CRLException e) {
throw new PemGenerationException("Cannot encode object: " + e.toString());
}
} else if (// 1.47 compatibility
o instanceof java.security.KeyPair) {
return createPemObject(((java.security.KeyPair) o).getPrivate());
} else if (// 1.47 compatibility
o instanceof java.security.PrivateKey) {
PrivateKeyInfo info = new PrivateKeyInfo((ASN1Sequence) ASN1Primitive.fromByteArray(((java.security.Key) o).getEncoded()));
if (o instanceof java.security.interfaces.RSAPrivateKey) {
type = "RSA PRIVATE KEY";
encoding = info.parsePrivateKey().toASN1Primitive().getEncoded();
} else if (o instanceof java.security.interfaces.DSAPrivateKey) {
type = "DSA PRIVATE KEY";
DSAParameter p = DSAParameter.getInstance(info.getPrivateKeyAlgorithm().getParameters());
ASN1EncodableVector v = new ASN1EncodableVector();
v.add(new DERInteger(0));
v.add(new DERInteger(p.getP()));
v.add(new DERInteger(p.getQ()));
v.add(new DERInteger(p.getG()));
BigInteger x = ((java.security.interfaces.DSAPrivateKey) o).getX();
BigInteger y = p.getG().modPow(x, p.getP());
v.add(new DERInteger(y));
v.add(new DERInteger(x));
encoding = new DERSequence(v).getEncoded();
} else if (((java.security.PrivateKey) o).getAlgorithm().equals("ECDSA")) {
type = "EC PRIVATE KEY";
encoding = info.parsePrivateKey().toASN1Primitive().getEncoded();
} else {
throw new IOException("Cannot identify private key");
}
} else if (// 1.47 compatibility
o instanceof java.security.PublicKey) {
type = "PUBLIC KEY";
encoding = ((java.security.PublicKey) o).getEncoded();
} else if (// 1.47 compatibility
o instanceof X509AttributeCertificate) {
type = "ATTRIBUTE CERTIFICATE";
encoding = ((X509AttributeCertificate) o).getEncoded();
} else //
//
//
{
throw new PemGenerationException("unknown object passed - can't encode.");
}
if (// NEW STUFF (NOT IN OLD)
encryptor != null) {
String dekAlgName = Strings.toUpperCase(encryptor.getAlgorithm());
// Note: For backward compatibility
if (dekAlgName.equals("DESEDE")) {
dekAlgName = "DES-EDE3-CBC";
}
byte[] iv = encryptor.getIV();
byte[] encData = encryptor.encrypt(encoding);
List<PemHeader> headers = new ArrayList<PemHeader>(2);
headers.add(new PemHeader("Proc-Type", "4,ENCRYPTED"));
headers.add(new PemHeader("DEK-Info", dekAlgName + "," + getHexEncoded(iv)));
return new PemObject(type, headers, encData);
}
return new PemObject(type, encoding);
}
use of org.bouncycastle.asn1.ASN1Integer in project jruby-openssl by jruby.
the class StoreContext method checkChainExtensions.
/**
* c: check_chain_extensions
*/
public int checkChainExtensions() throws Exception {
int ok, must_be_ca;
X509AuxCertificate x;
int proxy_path_length = 0;
int allow_proxy_certs = (verifyParameter.flags & X509Utils.V_FLAG_ALLOW_PROXY_CERTS) != 0 ? 1 : 0;
must_be_ca = -1;
try {
final String allowProxyCerts = System.getenv("OPENSSL_ALLOW_PROXY_CERTS");
if (allowProxyCerts != null && !"false".equalsIgnoreCase(allowProxyCerts)) {
allow_proxy_certs = 1;
}
} catch (SecurityException e) {
/* ignore if we can't use System.getenv */
}
for (int i = 0; i < lastUntrusted; i++) {
int ret;
x = chain.get(i);
if ((verifyParameter.flags & X509Utils.V_FLAG_IGNORE_CRITICAL) == 0 && unhandledCritical(x)) {
error = X509Utils.V_ERR_UNHANDLED_CRITICAL_EXTENSION;
errorDepth = i;
currentCertificate = x;
ok = verifyCallback.call(this, ZERO);
if (ok == 0)
return ok;
}
if (allow_proxy_certs == 0 && x.getExtensionValue("1.3.6.1.5.5.7.1.14") != null) {
error = X509Utils.V_ERR_PROXY_CERTIFICATES_NOT_ALLOWED;
errorDepth = i;
currentCertificate = x;
ok = verifyCallback.call(this, ZERO);
if (ok == 0)
return ok;
}
ret = Purpose.checkCA(x);
switch(must_be_ca) {
case -1:
if ((verifyParameter.flags & X509Utils.V_FLAG_X509_STRICT) != 0 && ret != 1 && ret != 0) {
ret = 0;
error = X509Utils.V_ERR_INVALID_CA;
} else {
ret = 1;
}
break;
case 0:
if (ret != 0) {
ret = 0;
error = X509Utils.V_ERR_INVALID_NON_CA;
} else {
ret = 1;
}
break;
default:
if (ret == 0 || ((verifyParameter.flags & X509Utils.V_FLAG_X509_STRICT) != 0 && ret != 1)) {
ret = 0;
error = X509Utils.V_ERR_INVALID_CA;
} else {
ret = 1;
}
break;
}
if (ret == 0) {
errorDepth = i;
currentCertificate = x;
ok = verifyCallback.call(this, ZERO);
if (ok == 0)
return ok;
}
if (verifyParameter.purpose > 0) {
ret = Purpose.checkPurpose(x, verifyParameter.purpose, must_be_ca > 0 ? 1 : 0);
if (ret == 0 || ((verifyParameter.flags & X509Utils.V_FLAG_X509_STRICT) != 0 && ret != 1)) {
error = X509Utils.V_ERR_INVALID_PURPOSE;
errorDepth = i;
currentCertificate = x;
ok = verifyCallback.call(this, ZERO);
if (ok == 0) {
return ok;
}
}
}
if (i > 1 && x.getBasicConstraints() != -1 && x.getBasicConstraints() != Integer.MAX_VALUE && (i > (x.getBasicConstraints() + proxy_path_length + 1))) {
error = X509Utils.V_ERR_PATH_LENGTH_EXCEEDED;
errorDepth = i;
currentCertificate = x;
ok = verifyCallback.call(this, ZERO);
if (ok == 0)
return ok;
}
if (x.getExtensionValue("1.3.6.1.5.5.7.1.14") != null) {
ASN1Sequence pci = (ASN1Sequence) new ASN1InputStream(x.getExtensionValue("1.3.6.1.5.5.7.1.14")).readObject();
if (pci.size() > 0 && pci.getObjectAt(0) instanceof ASN1Integer) {
int pcpathlen = ((ASN1Integer) pci.getObjectAt(0)).getValue().intValue();
if (i > pcpathlen) {
error = X509Utils.V_ERR_PROXY_PATH_LENGTH_EXCEEDED;
errorDepth = i;
currentCertificate = x;
ok = verifyCallback.call(this, ZERO);
if (ok == 0)
return ok;
}
}
proxy_path_length++;
must_be_ca = 0;
} else {
must_be_ca = 1;
}
}
return 1;
}
use of org.bouncycastle.asn1.ASN1Integer in project pac4j by pac4j.
the class SAML2ClientConfiguration method createSelfSignedCert.
/**
* Generate a self-signed certificate for dn using the provided signature algorithm and key pair.
*
* @param dn X.500 name to associate with certificate issuer/subject.
* @param sigName name of the signature algorithm to use.
* @param sigAlgID algorithm ID associated with the signature algorithm name.
* @param keyPair the key pair to associate with the certificate.
* @return an X509Certificate containing the public key in keyPair.
* @throws Exception
*/
private X509Certificate createSelfSignedCert(X500Name dn, String sigName, AlgorithmIdentifier sigAlgID, KeyPair keyPair) throws Exception {
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 Calendar c = Calendar.getInstance();
c.setTime(new Date());
c.add(Calendar.YEAR, 1);
certGen.setEndDate(new Time(c.getTime()));
certGen.setSignature(sigAlgID);
certGen.setSubjectPublicKeyInfo(SubjectPublicKeyInfo.getInstance(keyPair.getPublic().getEncoded()));
Signature sig = Signature.getInstance(sigName);
sig.initSign(keyPair.getPrivate());
sig.update(certGen.generateTBSCertificate().getEncoded(ASN1Encoding.DER));
TBSCertificate tbsCert = certGen.generateTBSCertificate();
ASN1EncodableVector v = new ASN1EncodableVector();
v.add(tbsCert);
v.add(sigAlgID);
v.add(new DERBitString(sig.sign()));
X509Certificate cert = (X509Certificate) CertificateFactory.getInstance("X.509").generateCertificate(new ByteArrayInputStream(new DERSequence(v).getEncoded(ASN1Encoding.DER)));
// check the certificate - this will confirm the encoded sig algorithm ID is correct.
cert.verify(keyPair.getPublic());
return cert;
}
use of org.bouncycastle.asn1.ASN1Integer in project certmgr by hdecarne.
the class AuthorityKeyIdentifierExtensionData method encode.
@Override
public ASN1Encodable encode() throws IOException {
ASN1EncodableVector sequence = new ASN1EncodableVector();
byte[] checkedKeyIdentifier = this.keyIdentifier;
if (checkedKeyIdentifier != null) {
sequence.add(new DERTaggedObject(false, 0, new DEROctetString(checkedKeyIdentifier)));
}
GeneralNames checkedAuthorityCertIssuer = this.authorityCertIssuer;
if (checkedAuthorityCertIssuer != null) {
sequence.add(new DERTaggedObject(false, 1, checkedAuthorityCertIssuer.encode()));
}
BigInteger checkedAuthorityCertSerialNumber = this.authorityCertSerialNumber;
if (checkedAuthorityCertSerialNumber != null) {
sequence.add(new DERTaggedObject(false, 2, new ASN1Integer(checkedAuthorityCertSerialNumber)));
}
return new DERSequence(sequence);
}
use of org.bouncycastle.asn1.ASN1Integer in project xipki by xipki.
the class XmlX509Certprofile method initQcStatements.
private void initQcStatements(Set<ASN1ObjectIdentifier> extnIds, ExtensionsType extensionsType) throws CertprofileException {
ASN1ObjectIdentifier type = Extension.qCStatements;
if (!extensionControls.containsKey(type)) {
return;
}
extnIds.remove(type);
QcStatements extConf = (QcStatements) getExtensionValue(type, extensionsType, QcStatements.class);
if (extConf == null) {
return;
}
List<QcStatementType> qcStatementTypes = extConf.getQcStatement();
this.qcStatementsOption = new ArrayList<>(qcStatementTypes.size());
Set<String> currencyCodes = new HashSet<>();
boolean requireInfoFromReq = false;
for (QcStatementType m : qcStatementTypes) {
ASN1ObjectIdentifier qcStatementId = new ASN1ObjectIdentifier(m.getStatementId().getValue());
QcStatementOption qcStatementOption;
QcStatementValueType statementValue = m.getStatementValue();
if (statementValue == null) {
QCStatement qcStatment = new QCStatement(qcStatementId);
qcStatementOption = new QcStatementOption(qcStatment);
} else if (statementValue.getQcRetentionPeriod() != null) {
QCStatement qcStatment = new QCStatement(qcStatementId, new ASN1Integer(statementValue.getQcRetentionPeriod()));
qcStatementOption = new QcStatementOption(qcStatment);
} else if (statementValue.getConstant() != null) {
ASN1Encodable constantStatementValue;
try {
constantStatementValue = new ASN1StreamParser(statementValue.getConstant().getValue()).readObject();
} catch (IOException ex) {
throw new CertprofileException("can not parse the constant value of QcStatement");
}
QCStatement qcStatment = new QCStatement(qcStatementId, constantStatementValue);
qcStatementOption = new QcStatementOption(qcStatment);
} else if (statementValue.getQcEuLimitValue() != null) {
QcEuLimitValueType euLimitType = statementValue.getQcEuLimitValue();
String tmpCurrency = euLimitType.getCurrency().toUpperCase();
if (currencyCodes.contains(tmpCurrency)) {
throw new CertprofileException("Duplicated definition of qcStatments with QCEuLimitValue" + " for the currency " + tmpCurrency);
}
Iso4217CurrencyCode currency = StringUtil.isNumber(tmpCurrency) ? new Iso4217CurrencyCode(Integer.parseInt(tmpCurrency)) : new Iso4217CurrencyCode(tmpCurrency);
Range2Type r1 = euLimitType.getAmount();
Range2Type r2 = euLimitType.getExponent();
if (r1.getMin() == r1.getMax() && r2.getMin() == r2.getMax()) {
MonetaryValue monetaryValue = new MonetaryValue(currency, r1.getMin(), r2.getMin());
QCStatement qcStatement = new QCStatement(qcStatementId, monetaryValue);
qcStatementOption = new QcStatementOption(qcStatement);
} else {
MonetaryValueOption monetaryValueOption = new MonetaryValueOption(currency, r1, r2);
qcStatementOption = new QcStatementOption(qcStatementId, monetaryValueOption);
requireInfoFromReq = true;
}
currencyCodes.add(tmpCurrency);
} else if (statementValue.getPdsLocations() != null) {
ASN1EncodableVector vec = new ASN1EncodableVector();
for (PdsLocationType pl : statementValue.getPdsLocations().getPdsLocation()) {
ASN1EncodableVector vec2 = new ASN1EncodableVector();
vec2.add(new DERIA5String(pl.getUrl()));
String lang = pl.getLanguage();
if (lang.length() != 2) {
throw new RuntimeException("invalid language '" + lang + "'");
}
vec2.add(new DERPrintableString(lang));
DERSequence seq = new DERSequence(vec2);
vec.add(seq);
}
QCStatement qcStatement = new QCStatement(qcStatementId, new DERSequence(vec));
qcStatementOption = new QcStatementOption(qcStatement);
} else {
throw new RuntimeException("unknown value of qcStatment");
}
this.qcStatementsOption.add(qcStatementOption);
}
if (requireInfoFromReq) {
return;
}
ASN1EncodableVector vec = new ASN1EncodableVector();
for (QcStatementOption m : qcStatementsOption) {
if (m.getStatement() == null) {
throw new RuntimeException("should not reach here");
}
vec.add(m.getStatement());
}
ASN1Sequence seq = new DERSequence(vec);
qcStatments = new ExtensionValue(extensionControls.get(type).isCritical(), seq);
qcStatementsOption = null;
}
Aggregations