Example usage for org.bouncycastle.asn1 ASN1Integer ASN1Integer

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

Introduction

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

Prototype

public ASN1Integer(byte[] bytes) 

Source Link

Document

Construct an INTEGER from the passed in byte array.

Usage

From source file:org.xipki.security.p11.iaik.IaikP11Slot.java

License:Open Source License

private X509CertificateHolder generateCertificate(final Session session, final byte[] id, final String label,
        final String subject, final AlgorithmIdentifier signatureAlgId,
        final PrivateKeyAndPKInfo privateKeyAndPkInfo, Integer keyUsage,
        List<ASN1ObjectIdentifier> extendedKeyUsage) throws Exception {
    BigInteger serialNumber = BigInteger.ONE;
    Date startDate = new Date();
    Date endDate = new Date(startDate.getTime() + 20 * YEAR);

    X500Name x500Name_subject = new X500Name(subject);
    x500Name_subject = X509Util.sortX509Name(x500Name_subject);

    V3TBSCertificateGenerator tbsGen = new V3TBSCertificateGenerator();
    tbsGen.setSerialNumber(new ASN1Integer(serialNumber));
    tbsGen.setSignature(signatureAlgId);
    tbsGen.setIssuer(x500Name_subject);
    tbsGen.setStartDate(new Time(startDate));
    tbsGen.setEndDate(new Time(endDate));
    tbsGen.setSubject(x500Name_subject);
    tbsGen.setSubjectPublicKeyInfo(privateKeyAndPkInfo.getPublicKeyInfo());

    List<Extension> extensions = new ArrayList<>(2);
    if (keyUsage == null) {
        keyUsage = KeyUsage.keyCertSign | KeyUsage.cRLSign | KeyUsage.digitalSignature
                | KeyUsage.keyEncipherment;
    }//  w  w  w  .  ja v  a2  s.  co  m
    extensions.add(new Extension(Extension.keyUsage, true, new DEROctetString(new KeyUsage(keyUsage))));

    if (CollectionUtil.isNotEmpty(extendedKeyUsage)) {
        KeyPurposeId[] kps = new KeyPurposeId[extendedKeyUsage.size()];

        int i = 0;
        for (ASN1ObjectIdentifier oid : extendedKeyUsage) {
            kps[i++] = KeyPurposeId.getInstance(oid);
        }

        extensions.add(new Extension(Extension.extendedKeyUsage, false,
                new DEROctetString(new ExtendedKeyUsage(kps))));
    }

    Extensions paramX509Extensions = new Extensions(extensions.toArray(new Extension[0]));
    tbsGen.setExtensions(paramX509Extensions);

    TBSCertificate tbsCertificate = tbsGen.generateTBSCertificate();
    byte[] encodedTbsCertificate = tbsCertificate.getEncoded();
    byte[] signature = null;
    Digest digest = null;
    Mechanism sigMechanism = null;

    ASN1ObjectIdentifier sigAlgID = signatureAlgId.getAlgorithm();

    if (sigAlgID.equals(PKCSObjectIdentifiers.sha256WithRSAEncryption)) {
        sigMechanism = Mechanism.get(PKCS11Constants.CKM_SHA256_RSA_PKCS);
        session.signInit(sigMechanism, privateKeyAndPkInfo.getPrivateKey());
        signature = session.sign(encodedTbsCertificate);
    } else if (sigAlgID.equals(NISTObjectIdentifiers.dsa_with_sha256)) {
        digest = new SHA256Digest();
        byte[] digestValue = new byte[digest.getDigestSize()];
        digest.update(encodedTbsCertificate, 0, encodedTbsCertificate.length);
        digest.doFinal(digestValue, 0);

        session.signInit(Mechanism.get(PKCS11Constants.CKM_DSA), privateKeyAndPkInfo.getPrivateKey());
        byte[] rawSignature = session.sign(digestValue);
        signature = convertToX962Signature(rawSignature);
    } else {
        if (sigAlgID.equals(X9ObjectIdentifiers.ecdsa_with_SHA1)) {
            digest = new SHA1Digest();
        } else if (sigAlgID.equals(X9ObjectIdentifiers.ecdsa_with_SHA256)) {
            digest = new SHA256Digest();
        } else if (sigAlgID.equals(X9ObjectIdentifiers.ecdsa_with_SHA384)) {
            digest = new SHA384Digest();
        } else if (sigAlgID.equals(X9ObjectIdentifiers.ecdsa_with_SHA512)) {
            digest = new SHA512Digest();
        } else {
            System.err.println("unknown algorithm ID: " + sigAlgID.getId());
            return null;
        }

        byte[] digestValue = new byte[digest.getDigestSize()];
        digest.update(encodedTbsCertificate, 0, encodedTbsCertificate.length);
        digest.doFinal(digestValue, 0);

        session.signInit(Mechanism.get(PKCS11Constants.CKM_ECDSA), privateKeyAndPkInfo.getPrivateKey());
        byte[] rawSignature = session.sign(digestValue);
        signature = convertToX962Signature(rawSignature);
    }

    // build DER certificate
    ASN1EncodableVector v = new ASN1EncodableVector();
    v.add(tbsCertificate);
    v.add(signatureAlgId);
    v.add(new DERBitString(signature));
    DERSequence cert = new DERSequence(v);

    // build and store PKCS#11 certificate object
    X509PublicKeyCertificate certTemp = new X509PublicKeyCertificate();
    certTemp.getToken().setBooleanValue(true);
    certTemp.getId().setByteArrayValue(id);
    certTemp.getLabel().setCharArrayValue(label.toCharArray());
    certTemp.getSubject().setByteArrayValue(x500Name_subject.getEncoded());
    certTemp.getIssuer().setByteArrayValue(x500Name_subject.getEncoded());
    certTemp.getSerialNumber().setByteArrayValue(serialNumber.toByteArray());
    certTemp.getValue().setByteArrayValue(cert.getEncoded());
    session.createObject(certTemp);

    return new X509CertificateHolder(Certificate.getInstance(cert));
}

From source file:org.xipki.security.p11.iaik.IaikP11Slot.java

License:Open Source License

private static byte[] convertToX962Signature(final byte[] signature) throws IOException {
    int n = signature.length / 2;
    byte[] x = Arrays.copyOfRange(signature, 0, n);
    byte[] y = Arrays.copyOfRange(signature, n, 2 * n);

    ASN1EncodableVector sigder = new ASN1EncodableVector();
    sigder.add(new ASN1Integer(new BigInteger(1, x)));
    sigder.add(new ASN1Integer(new BigInteger(1, y)));

    return new DERSequence(sigder).getEncoded();
}

From source file:org.xipki.security.p11.remote.RemoteP11CryptService.java

License:Open Source License

private ASN1Encodable send(final int action, final ASN1Encodable content) throws SignerException {
    PKIHeader header = buildPKIHeader(null);
    ASN1EncodableVector v = new ASN1EncodableVector();
    v.add(new ASN1Integer(action));
    if (content != null) {
        v.add(content);/*from  w ww. ja va 2  s  .c  o  m*/
    }
    InfoTypeAndValue itvReq = new InfoTypeAndValue(ObjectIdentifiers.id_xipki_cmp, new DERSequence(v));

    GenMsgContent genMsgContent = new GenMsgContent(itvReq);
    PKIBody body = new PKIBody(PKIBody.TYPE_GEN_MSG, genMsgContent);
    PKIMessage request = new PKIMessage(header, body);

    byte[] encodedRequest;
    try {
        encodedRequest = request.getEncoded();
    } catch (IOException e) {
        LOG.error("error while encode the PKI request {}", request);
        throw new SignerException(e.getMessage(), e);
    }

    byte[] encodedResponse;
    try {
        encodedResponse = send(encodedRequest);
    } catch (IOException e) {
        LOG.error("error while send the PKI request {} to server", request);
        throw new SignerException(e.getMessage(), e);
    }

    GeneralPKIMessage response;
    try {
        response = new GeneralPKIMessage(encodedResponse);
    } catch (IOException e) {
        LOG.error("error while decode the received PKI message: {}", Hex.toHexString(encodedResponse));
        throw new SignerException(e.getMessage(), e);
    }

    PKIHeader respHeader = response.getHeader();
    ASN1OctetString tid = respHeader.getTransactionID();
    GeneralName recipient = respHeader.getRecipient();
    if (sender.equals(recipient) == false) {
        LOG.warn("tid={}: unknown CMP requestor '{}'", tid, recipient);
    }

    return extractItvInfoValue(action, response);
}

From source file:org.xipki.security.SignerUtil.java

License:Open Source License

public static byte[] convertPlainDSASigX962(final byte[] signature) throws SignerException {
    byte[] ba = new byte[signature.length / 2];
    ASN1EncodableVector sigder = new ASN1EncodableVector();

    System.arraycopy(signature, 0, ba, 0, ba.length);
    sigder.add(new ASN1Integer(new BigInteger(1, ba)));

    System.arraycopy(signature, ba.length, ba, 0, ba.length);
    sigder.add(new ASN1Integer(new BigInteger(1, ba)));

    DERSequence seq = new DERSequence(sigder);
    try {/* ww w . j  a  va 2 s.  c om*/
        return seq.getEncoded();
    } catch (IOException e) {
        throw new SignerException("IOException, message: " + e.getMessage(), e);
    }
}

From source file:org.xwiki.crypto.password.internal.kdf.PBKDF2Params.java

License:Open Source License

/**
 * Initialize parameters without key length and an default SHA-1 pseudo random function.
 *
 * @param salt the salt.//from  ww  w . jav a  2 s  .com
 * @param iterationCount the iteration count.
 */
public PBKDF2Params(byte[] salt, int iterationCount) {
    this(new DEROctetString(salt), new ASN1Integer(iterationCount), null, null);
}

From source file:org.xwiki.crypto.password.internal.kdf.PBKDF2Params.java

License:Open Source License

/**
 * Initialize parameters without key length.
 *
 * @param salt the salt./*ww w  .  j  a v  a 2  s  . c o  m*/
 * @param iterationCount the iteration count.
 * @param prf the pseudo random function identifier.
 */
public PBKDF2Params(byte[] salt, int iterationCount, AlgorithmIdentifier prf) {
    this(new DEROctetString(salt), new ASN1Integer(iterationCount), null, prf);
}

From source file:org.xwiki.crypto.password.internal.kdf.PBKDF2Params.java

License:Open Source License

/**
 * Initialize parameters with a default SHA-1 pseudo random function.
 *
 * @param salt the salt./*w ww  . j av  a  2  s .  c o  m*/
 * @param iterationCount the iteration count.
 * @param keyLength the key length.
 */
public PBKDF2Params(byte[] salt, int iterationCount, int keyLength) {
    this(new DEROctetString(salt), new ASN1Integer(iterationCount), new ASN1Integer(keyLength), null);
}

From source file:org.xwiki.crypto.password.internal.kdf.PBKDF2Params.java

License:Open Source License

/**
 * Initialize all parameters.//from  ww w  . ja v a  2s . c om
 *
 * @param salt the salt.
 * @param iterationCount the iteration count.
 * @param keyLength the key length.
 * @param prf the pseudo random function identifier.
 */
public PBKDF2Params(byte[] salt, int iterationCount, int keyLength, AlgorithmIdentifier prf) {
    this(new DEROctetString(salt), new ASN1Integer(iterationCount), new ASN1Integer(keyLength), prf);
}

From source file:org.xwiki.crypto.password.internal.kdf.ScryptKDFParams.java

License:Open Source License

/**
 * Create Scrypt parameters with a key length.
 *
 * @param salt is the salt value.//  w w w .  j av a2  s.c o m
 * @param costParameter is the CPU/Memory cost parameter N.
 * @param blockSize is the block size parameter r.
 * @param parallelizationParameter is the parallelization parameter.
 * @param keyLength is the length in octets of the derived key.
 */
public ScryptKDFParams(byte[] salt, int costParameter, int blockSize, int parallelizationParameter,
        int keyLength) {
    this.salt = new DEROctetString(salt);
    this.costParameter = new ASN1Integer(costParameter);
    this.blockSize = new ASN1Integer(blockSize);
    this.parallelizationParameter = new ASN1Integer(parallelizationParameter);
    this.keyLength = (keyLength >= 0) ? new ASN1Integer(keyLength) : null;
}

From source file:org.xwiki.crypto.password.internal.pbe.RC5CBCParameter.java

License:Open Source License

/**
 * Create a new instance with the optional initialization vector and a specific parameter version.
 * @param parameterVersion the version of this parameter structure, should be v1-0 (16).
 * @param rounds the number of "rounds" in the encryption operation between 8 and 127.
 * @param blockSizeInBits the block size in bits, may be 64 or 128.
 * @param iv the initialization vector./*  www  .j  a  v a2s  . co  m*/
 */
public RC5CBCParameter(int parameterVersion, int rounds, int blockSizeInBits, byte[] iv) {
    this.version = new ASN1Integer(parameterVersion);
    this.rounds = new ASN1Integer(rounds);
    this.blockSizeInBits = new ASN1Integer(blockSizeInBits);
    this.iv = (iv != null) ? new DEROctetString(iv) : null;
}