Example usage for org.bouncycastle.asn1 DERIA5String DERIA5String

List of usage examples for org.bouncycastle.asn1 DERIA5String DERIA5String

Introduction

In this page you can find the example usage for org.bouncycastle.asn1 DERIA5String DERIA5String.

Prototype

public DERIA5String(String string) 

Source Link

Document

Basic constructor - without validation.

Usage

From source file:org.jruby.ext.openssl.impl.NetscapeCertRequest.java

License:Open Source License

public void sign(final PrivateKey privateKey, SecureRandom random)
        throws NoSuchAlgorithmException, InvalidKeyException, SignatureException, InvalidKeySpecException {
    final Signature signature = getSignature();

    if (random != null) {
        signature.initSign(privateKey, random);
    } else {// w  w  w.ja v a2 s .co  m
        signature.initSign(privateKey);
    }

    ASN1EncodableVector pkac = new ASN1EncodableVector();

    try {
        pkac.add(getKeySpec());
    } catch (IOException e) {
        throw new InvalidKeySpecException(e);
    }
    pkac.add(new DERIA5String(challenge));

    try {
        signature.update(new DERSequence(pkac).getEncoded(ASN1Encoding.DER));
    } catch (IOException e) {
        throw new SignatureException(e);
    }

    signatureBits = signature.sign();
}

From source file:org.jruby.ext.openssl.impl.NetscapeCertRequest.java

License:Open Source License

public ASN1Primitive toASN1Primitive() throws IOException {
    ASN1EncodableVector spkac = new ASN1EncodableVector();
    ASN1EncodableVector pkac = new ASN1EncodableVector();

    try {/*from  ww w  .j a v  a 2 s  . c  om*/
        pkac.add(getKeySpec());
    } catch (IOException e) {
        // TODO is this really fine shouldn't it be thrown ?
    }

    pkac.add(new DERIA5String(challenge));

    spkac.add(new DERSequence(pkac));
    spkac.add(sigAlg);
    spkac.add(new DERBitString(signatureBits));

    return new DERSequence(spkac);
}

From source file:org.jruby.ext.openssl.NetscapeSPKI.java

License:LGPL

private byte[] internalToDer() throws IOException {
    ASN1Sequence b = (ASN1Sequence) cert.toASN1Primitive();
    ASN1ObjectIdentifier encType = null;
    DERBitString publicKey = new DERBitString(((PKey) public_key).to_der().convertToString().getBytes());
    DERIA5String encodedChallenge = new DERIA5String(this.challenge.toString());
    ASN1ObjectIdentifier sigAlg = null;//from  www .  jav  a2 s  .  c o  m
    DERBitString sig = null;
    encType = (ASN1ObjectIdentifier) ((ASN1Sequence) ((ASN1Sequence) ((ASN1Sequence) b.getObjectAt(0))
            .getObjectAt(0)).getObjectAt(0)).getObjectAt(0);
    sigAlg = ((AlgorithmIdentifier) b.getObjectAt(1)).getAlgorithm();
    sig = (DERBitString) b.getObjectAt(2);

    ASN1EncodableVector v1 = new ASN1EncodableVector();
    ASN1EncodableVector v1_2 = new ASN1EncodableVector();
    ASN1EncodableVector v2 = new ASN1EncodableVector();
    ASN1EncodableVector v3 = new ASN1EncodableVector();
    ASN1EncodableVector v4 = new ASN1EncodableVector();
    v4.add(encType);
    v4.add(new DERNull());
    v3.add(new DLSequence(v4));
    v3.add(publicKey);
    v2.add(new DLSequence(v3));
    v2.add(encodedChallenge);
    v1.add(new DLSequence(v2));
    v1_2.add(sigAlg);
    v1_2.add(new DERNull());
    v1.add(new DLSequence(v1_2));
    v1.add(sig);
    return new DLSequence(v1).getEncoded();
}

From source file:org.krakenapps.ca.util.CertificateBuilder.java

License:Apache License

public static X509Certificate createCertificate(CertificateRequest req) throws Exception {
    X509V3CertificateGenerator certGen = new X509V3CertificateGenerator();

    X509Principal subject = parseDn(req.getSubjectDn());
    X509Principal issuer = parseDn(req.getIssuerDn());

    certGen.setSerialNumber(req.getSerial());
    certGen.setIssuerDN(issuer);/*from   w  ww  . ja v  a  2s  .c om*/
    certGen.setSubjectDN(subject);
    certGen.setNotBefore(req.getNotBefore());
    certGen.setNotAfter(req.getNotAfter());
    certGen.setPublicKey(req.getKeyPair().getPublic());
    certGen.setSignatureAlgorithm(req.getSignatureAlgorithm());

    if (req.getCrlUrl() != null) {
        GeneralName gn = new GeneralName(6, new DERIA5String(req.getCrlUrl().toString()));

        ASN1EncodableVector vec = new ASN1EncodableVector();
        vec.add(gn);

        GeneralNames gns = new GeneralNames(new DERSequence(vec));
        DistributionPointName dpn = new DistributionPointName(0, gns);

        List<DistributionPoint> l = new ArrayList<DistributionPoint>();
        l.add(new DistributionPoint(dpn, null, null));

        CRLDistPoint crlDp = new CRLDistPoint(l.toArray(new DistributionPoint[0]));

        certGen.addExtension(new DERObjectIdentifier("2.5.29.31"), false, crlDp);
    }

    return certGen.generate(req.getIssuerKey(), "BC");
}

From source file:org.opensc.pkcs15.asn1.ref.URL.java

License:Apache License

@Override
public DERObject toASN1Object() {

    if (DERIA5String.isIA5String(this.url))
        return new DERIA5String(this.url);

    return new DERPrintableString(this.url);
}

From source file:org.qipki.crypto.x509.X509ExtensionsBuilderImpl.java

License:Open Source License

@Override
public CRLDistPoint buildCRLDistributionPoints(Map<X500Principal, Iterable<String>> crlDistPointsData) {
    List<DistributionPoint> distributionPoints = new ArrayList<DistributionPoint>();
    for (Map.Entry<X500Principal, Iterable<String>> eachIssuerEntry : crlDistPointsData.entrySet()) {

        GeneralName issuerName = new GeneralName(new X509Name(eachIssuerEntry.getKey().getName()));
        ASN1EncodableVector issuerVector = new ASN1EncodableVector();
        issuerVector.add(issuerName);/*from ww  w  . j  ava 2  s. c o  m*/
        GeneralNames issuerNames = new GeneralNames(new DERSequence(issuerVector));

        for (String eachEndpoint : eachIssuerEntry.getValue()) {

            GeneralName endpointName = new GeneralName(GeneralName.uniformResourceIdentifier,
                    new DERIA5String(eachEndpoint));
            ASN1EncodableVector epVector = new ASN1EncodableVector();
            epVector.add(endpointName);
            GeneralNames endpointNames = new GeneralNames(new DERSequence(epVector));
            DistributionPointName dpn = new DistributionPointName(DistributionPointName.FULL_NAME,
                    endpointNames);

            distributionPoints.add(new DistributionPoint(dpn, null, issuerNames));
        }
    }
    return new CRLDistPoint(distributionPoints.toArray(new DistributionPoint[distributionPoints.size()]));
}

From source file:org.signserver.validationservice.server.ValidationTestUtils.java

License:Open Source License

public static CRLDistPoint generateDistPointWithUrl(URL cdpUrl) {
    GeneralName gn = new GeneralName(GeneralName.uniformResourceIdentifier,
            new DERIA5String(cdpUrl.toExternalForm()));
    GeneralNames gns = new GeneralNames(gn);
    DistributionPointName dpn = new DistributionPointName(0, gns);
    return new CRLDistPoint(new DistributionPoint[] { new DistributionPoint(dpn, null, null) });
}

From source file:org.tdmx.client.crypto.certificate.TdmxZoneInfo.java

License:Open Source License

/**
 * Create a TdmxZoneInfo descriptor which describes a versioned TDMX relay interface for a normalized domain name
 * (zone apex).//  w ww .j  a v  a2 s .com
 * 
 * @param version
 *            currently only 1
 * @param zoneRoot
 *            must be uppercase
 * @param mrsUrl
 *            the MRS relay URL, ie. http://mrs.serviceprovider.com/api/v01/mrs
 */
public TdmxZoneInfo(int version, String zoneRoot, String mrsUrl) {
    this.version = new ASN1Integer(version);
    this.zoneRoot = new DERIA5String(zoneRoot);
    this.mrsUrl = new DERIA5String(mrsUrl);
}

From source file:org.tramaci.onionmail.LibSTLS.java

License:Open Source License

public static X509Certificate CreateCert(KeyPair KP, String onion, long Dfrom, long Dto, String info,
        String[] AltName) throws Exception { //OK

    byte[] bi = Stdio.md5(onion.getBytes());
    byte[] bx = new byte[bi.length + 9];
    System.arraycopy(bi, 0, bx, 1, bi.length);
    bx[0] = 0x7C;/*from ww  w  . ja v  a2 s  .  co m*/
    byte[] tmp = Stdio.Stosx(new long[] { Dfrom / 1000L, Dto / 1000L }, 4);
    int bp = 17;
    for (int ax = 0; ax < 8; ax++)
        bx[bp++] = tmp[ax];

    Date startDate = new Date(Dfrom); // time from which certificate is valid
    Date expiryDate = new Date(Dto); // time after which certificate is not valid
    BigInteger serialNumber = new BigInteger(bx); // serial number for certificate
    KeyPair keyPair = KP; // EC public/private key pair

    X509V3CertificateGenerator certGen = new X509V3CertificateGenerator();
    if (info != null && info.length() > 0)
        info = ", " + info;
    else
        info = "";
    X500Principal dnName = new X500Principal("CN=" + onion + info);
    certGen.setSerialNumber(serialNumber);
    certGen.setIssuerDN(dnName);
    certGen.setNotBefore(startDate);
    certGen.setNotAfter(expiryDate);
    certGen.setSubjectDN(dnName); // note: same as issuer
    certGen.setPublicKey(KP.getPublic());
    certGen.setSignatureAlgorithm("SHA256WithRSAEncryption");

    if (AltName != null) {
        int cx = AltName.length;
        for (int ax = 0; ax < cx; ax++)
            try {
                GeneralName generalName = new GeneralName(GeneralName.dNSName,
                        new DERIA5String(AltName[ax].toLowerCase().trim()));
                GeneralNames subjectAltNames = new GeneralNames(generalName);
                certGen.addExtension(X509Extensions.SubjectAlternativeName, false,
                        new DEROctetString(subjectAltNames));
            } catch (Exception EI) {
                Main.echo("CreateCert Error: " + EI.getMessage() + " (altName=`" + AltName[ax] + "`)\n");
            }
    }

    X509Certificate cert = certGen.generate(keyPair.getPrivate(), "BC");

    return cert;
}

From source file:org.xipki.commons.security.shell.CertRequestGenCommandSupport.java

License:Open Source License

@Override
protected Object doExecute() throws Exception {
    hashAlgo = hashAlgo.trim().toUpperCase();
    if (hashAlgo.indexOf('-') != -1) {
        hashAlgo = hashAlgo.replaceAll("-", "");
    }//from  ww w  .j  a  va2  s. co m

    if (needExtensionTypes == null) {
        needExtensionTypes = new LinkedList<>();
    }

    if (wantExtensionTypes == null) {
        wantExtensionTypes = new LinkedList<>();
    }

    // SubjectAltNames
    List<Extension> extensions = new LinkedList<>();

    ASN1OctetString extnValue = createExtnValueSubjectAltName();
    if (extnValue != null) {
        ASN1ObjectIdentifier oid = Extension.subjectAlternativeName;
        extensions.add(new Extension(oid, false, extnValue));
        needExtensionTypes.add(oid.getId());
    }

    // SubjectInfoAccess
    extnValue = createExtnValueSubjectInfoAccess();
    if (extnValue != null) {
        ASN1ObjectIdentifier oid = Extension.subjectInfoAccess;
        extensions.add(new Extension(oid, false, extnValue));
        needExtensionTypes.add(oid.getId());
    }

    // Keyusage
    if (isNotEmpty(keyusages)) {
        Set<KeyUsage> usages = new HashSet<>();
        for (String usage : keyusages) {
            usages.add(KeyUsage.getKeyUsage(usage));
        }
        org.bouncycastle.asn1.x509.KeyUsage extValue = X509Util.createKeyUsage(usages);
        ASN1ObjectIdentifier extType = Extension.keyUsage;
        extensions.add(new Extension(extType, false, extValue.getEncoded()));
        needExtensionTypes.add(extType.getId());
    }

    // ExtendedKeyusage
    if (isNotEmpty(extkeyusages)) {
        ExtendedKeyUsage extValue = X509Util.createExtendedUsage(textToAsn1ObjectIdentifers(extkeyusages));
        ASN1ObjectIdentifier extType = Extension.extendedKeyUsage;
        extensions.add(new Extension(extType, false, extValue.getEncoded()));
        needExtensionTypes.add(extType.getId());
    }

    // QcEuLimitValue
    if (isNotEmpty(qcEuLimits)) {
        ASN1EncodableVector vec = new ASN1EncodableVector();
        for (String m : qcEuLimits) {
            StringTokenizer st = new StringTokenizer(m, ":");
            try {
                String currencyS = st.nextToken();
                String amountS = st.nextToken();
                String exponentS = st.nextToken();

                Iso4217CurrencyCode currency;
                try {
                    int intValue = Integer.parseInt(currencyS);
                    currency = new Iso4217CurrencyCode(intValue);
                } catch (NumberFormatException ex) {
                    currency = new Iso4217CurrencyCode(currencyS);
                }

                int amount = Integer.parseInt(amountS);
                int exponent = Integer.parseInt(exponentS);

                MonetaryValue monterayValue = new MonetaryValue(currency, amount, exponent);
                QCStatement statment = new QCStatement(ObjectIdentifiers.id_etsi_qcs_QcLimitValue,
                        monterayValue);
                vec.add(statment);
            } catch (Exception ex) {
                throw new Exception("invalid qc-eu-limit '" + m + "'");
            }
        }

        ASN1ObjectIdentifier extType = Extension.qCStatements;
        ASN1Sequence extValue = new DERSequence(vec);
        extensions.add(new Extension(extType, false, extValue.getEncoded()));
        needExtensionTypes.add(extType.getId());
    }

    // biometricInfo
    if (biometricType != null && biometricHashAlgo != null && biometricFile != null) {
        TypeOfBiometricData tmpBiometricType = StringUtil.isNumber(biometricType)
                ? new TypeOfBiometricData(Integer.parseInt(biometricType))
                : new TypeOfBiometricData(new ASN1ObjectIdentifier(biometricType));

        ASN1ObjectIdentifier tmpBiometricHashAlgo = AlgorithmUtil.getHashAlg(biometricHashAlgo);
        byte[] biometricBytes = IoUtil.read(biometricFile);
        MessageDigest md = MessageDigest.getInstance(tmpBiometricHashAlgo.getId());
        md.reset();
        byte[] tmpBiometricDataHash = md.digest(biometricBytes);

        DERIA5String tmpSourceDataUri = null;
        if (biometricUri != null) {
            tmpSourceDataUri = new DERIA5String(biometricUri);
        }
        BiometricData biometricData = new BiometricData(tmpBiometricType,
                new AlgorithmIdentifier(tmpBiometricHashAlgo), new DEROctetString(tmpBiometricDataHash),
                tmpSourceDataUri);

        ASN1EncodableVector vec = new ASN1EncodableVector();
        vec.add(biometricData);

        ASN1ObjectIdentifier extType = Extension.biometricInfo;
        ASN1Sequence extValue = new DERSequence(vec);
        extensions.add(new Extension(extType, false, extValue.getEncoded()));
        needExtensionTypes.add(extType.getId());
    } else if (biometricType == null && biometricHashAlgo == null && biometricFile == null) {
        // Do nothing
    } else {
        throw new Exception("either all of biometric triples (type, hash algo, file)"
                + " must be set or none of them should be set");
    }

    for (Extension addExt : getAdditionalExtensions()) {
        extensions.add(addExt);
    }

    needExtensionTypes.addAll(getAdditionalNeedExtensionTypes());
    wantExtensionTypes.addAll(getAdditionalWantExtensionTypes());

    if (isNotEmpty(needExtensionTypes) || isNotEmpty(wantExtensionTypes)) {
        ExtensionExistence ee = new ExtensionExistence(textToAsn1ObjectIdentifers(needExtensionTypes),
                textToAsn1ObjectIdentifers(wantExtensionTypes));
        extensions.add(new Extension(ObjectIdentifiers.id_xipki_ext_cmpRequestExtensions, false,
                ee.toASN1Primitive().getEncoded()));
    }

    ConcurrentContentSigner signer = getSigner(new SignatureAlgoControl(rsaMgf1, dsaPlain));

    Map<ASN1ObjectIdentifier, ASN1Encodable> attributes = new HashMap<>();
    if (CollectionUtil.isNonEmpty(extensions)) {
        attributes.put(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest,
                new Extensions(extensions.toArray(new Extension[0])));
    }

    if (StringUtil.isNotBlank(challengePassword)) {
        attributes.put(PKCSObjectIdentifiers.pkcs_9_at_challengePassword,
                new DERPrintableString(challengePassword));
    }

    SubjectPublicKeyInfo subjectPublicKeyInfo;
    if (signer.getCertificate() != null) {
        Certificate cert = Certificate.getInstance(signer.getCertificate().getEncoded());
        subjectPublicKeyInfo = cert.getSubjectPublicKeyInfo();
    } else {
        subjectPublicKeyInfo = KeyUtil.createSubjectPublicKeyInfo(signer.getPublicKey());
    }

    X500Name subjectDn = getSubject(subject);
    PKCS10CertificationRequest csr = generateRequest(signer, subjectPublicKeyInfo, subjectDn, attributes);

    File file = new File(outputFilename);
    saveVerbose("saved CSR to file", file, csr.getEncoded());
    return null;
}