Example usage for org.bouncycastle.asn1 DEROctetString DEROctetString

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

Introduction

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

Prototype

public DEROctetString(ASN1Encodable obj) throws IOException 

Source Link

Document

Constructor from the encoding of an ASN.1 object.

Usage

From source file:org.xipki.pki.scep.message.PkiMessage.java

License:Open Source License

private AttributeTable getSignedAttributes() {
    ASN1EncodableVector vec = new ASN1EncodableVector();
    // messageType
    addAttribute(vec, ScepObjectIdentifiers.ID_MESSAGE_TYPE,
            new DERPrintableString(Integer.toString(messageType.getCode())));

    // senderNonce
    addAttribute(vec, ScepObjectIdentifiers.ID_SENDER_NONCE, new DEROctetString(senderNonce.getBytes()));

    // transactionID
    addAttribute(vec, ScepObjectIdentifiers.ID_TRANSACTION_ID, new DERPrintableString(transactionId.getId()));

    // failInfo//from   ww  w .  ja  v a  2  s .  c  o  m
    if (failInfo != null) {
        addAttribute(vec, ScepObjectIdentifiers.ID_FAILINFO,
                new DERPrintableString(Integer.toString(failInfo.getCode())));
    }

    // pkiStatus
    if (pkiStatus != null) {
        addAttribute(vec, ScepObjectIdentifiers.ID_PKI_STATUS,
                new DERPrintableString(Integer.toString(pkiStatus.getCode())));
    }

    // recipientNonce
    if (recipientNonce != null) {
        addAttribute(vec, ScepObjectIdentifiers.ID_RECIPIENT_NONCE,
                new DEROctetString(recipientNonce.getBytes()));
    }

    for (ASN1ObjectIdentifier type : signedAttributes.keySet()) {
        addAttribute(vec, type, signedAttributes.get(type));
    }
    return new AttributeTable(vec);
}

From source file:org.xipki.remotep11.server.impl.CmpResponder.java

License:Open Source License

PKIMessage processPKIMessage(final LocalP11CryptServicePool localP11CryptServicePool, final String moduleName,
        final PKIMessage pkiMessage) {
    GeneralPKIMessage message = new GeneralPKIMessage(pkiMessage);

    PKIHeader reqHeader = message.getHeader();
    ASN1OctetString tid = reqHeader.getTransactionID();

    if (tid == null) {
        byte[] randomBytes = randomTransactionId();
        tid = new DEROctetString(randomBytes);
    }//from ww  w.  j  a v a 2s  .  c o  m
    String tidStr = Hex.toHexString(tid.getOctets());

    PKIHeaderBuilder respHeaderBuilder = new PKIHeaderBuilder(reqHeader.getPvno().getValue().intValue(), sender,
            reqHeader.getSender());
    respHeaderBuilder.setTransactionID(tid);

    PKIBody reqBody = message.getBody();
    final int type = reqBody.getType();

    PKIHeader respHeader = respHeaderBuilder.build();

    if (type != PKIBody.TYPE_GEN_MSG) {
        ErrorMsgContent emc = new ErrorMsgContent(new PKIStatusInfo(PKIStatus.rejection,
                new PKIFreeText("unsupported type " + type), new PKIFailureInfo(PKIFailureInfo.badRequest)));

        PKIBody respBody = new PKIBody(PKIBody.TYPE_ERROR, emc);

        return new PKIMessage(respHeader, respBody);
    }

    GenMsgContent genMsgBody = (GenMsgContent) reqBody.getContent();
    InfoTypeAndValue[] itvs = genMsgBody.toInfoTypeAndValueArray();

    InfoTypeAndValue itv = null;
    if (itvs != null && itvs.length > 0) {
        for (InfoTypeAndValue m : itvs) {
            ASN1ObjectIdentifier itvType = m.getInfoType();
            if (ObjectIdentifiers.id_xipki_cmp.equals(itvType)) {
                itv = m;
                break;
            }
        }
    }

    if (itv == null) {
        final String statusMessage = String.format("PKIBody type %s is only supported with the sub-knownTypes",
                ObjectIdentifiers.id_xipki_cmp.getId());
        return createRejectionPKIMessage(respHeader, PKIFailureInfo.badRequest, statusMessage);
    }

    try {
        ASN1Encodable asn1 = itv.getInfoValue();
        ASN1Integer asn1Code = null;
        ASN1Encodable reqValue = null;

        try {
            ASN1Sequence seq = ASN1Sequence.getInstance(asn1);
            asn1Code = ASN1Integer.getInstance(seq.getObjectAt(0));
            if (seq.size() > 1) {
                reqValue = seq.getObjectAt(1);
            }
        } catch (IllegalArgumentException e) {
            final String statusMessage = "invalid value of the InfoTypeAndValue for "
                    + ObjectIdentifiers.id_xipki_cmp.getId();
            return createRejectionPKIMessage(respHeader, PKIFailureInfo.badRequest, statusMessage);
        }

        int action = asn1Code.getPositiveValue().intValue();
        ASN1Encodable respItvInfoValue;

        P11CryptService p11CryptService = localP11CryptServicePool.getP11CryptService(moduleName);

        switch (action) {
        case XipkiCmpConstants.ACTION_RP11_VERSION: {
            respItvInfoValue = new ASN1Integer(localP11CryptServicePool.getVersion());
            break;
        }
        case XipkiCmpConstants.ACTION_RP11_PSO_DSA_PLAIN:
        case XipkiCmpConstants.ACTION_RP11_PSO_DSA_X962:
        case XipkiCmpConstants.ACTION_RP11_PSO_ECDSA_PLAIN:
        case XipkiCmpConstants.ACTION_RP11_PSO_ECDSA_X962:
        case XipkiCmpConstants.ACTION_RP11_PSO_RSA_PKCS:
        case XipkiCmpConstants.ACTION_RP11_PSO_RSA_X509: {
            byte[] psoMessage = null;
            P11SlotIdentifier slot = null;
            P11KeyIdentifier keyId = null;
            {
                try {
                    PSOTemplate psoTemplate = PSOTemplate.getInstance(reqValue);
                    psoMessage = psoTemplate.getMessage();
                    SlotAndKeyIdentifer slotAndKeyIdentifier = psoTemplate.getSlotAndKeyIdentifer();
                    slot = slotAndKeyIdentifier.getSlotIdentifier().getSlotId();
                    KeyIdentifier keyIdentifier = slotAndKeyIdentifier.getKeyIdentifier();
                    keyId = keyIdentifier.getKeyId();
                } catch (IllegalArgumentException e) {
                    final String statusMessage = "invalid PSOTemplate";
                    return createRejectionPKIMessage(respHeader, PKIFailureInfo.badRequest, statusMessage);
                }
            }

            byte[] signature;

            if (XipkiCmpConstants.ACTION_RP11_PSO_ECDSA_PLAIN == action) {
                signature = p11CryptService.CKM_ECDSA_Plain(psoMessage, slot, keyId);
            } else if (XipkiCmpConstants.ACTION_RP11_PSO_ECDSA_X962 == action) {
                signature = p11CryptService.CKM_ECDSA_X962(psoMessage, slot, keyId);
            } else if (XipkiCmpConstants.ACTION_RP11_PSO_DSA_PLAIN == action) {
                signature = p11CryptService.CKM_DSA_Plain(psoMessage, slot, keyId);
            } else if (XipkiCmpConstants.ACTION_RP11_PSO_DSA_X962 == action) {
                signature = p11CryptService.CKM_DSA_X962(psoMessage, slot, keyId);
            } else if (XipkiCmpConstants.ACTION_RP11_PSO_RSA_X509 == action) {
                signature = p11CryptService.CKM_RSA_X509(psoMessage, slot, keyId);
            } else if (XipkiCmpConstants.ACTION_RP11_PSO_RSA_PKCS == action) {
                signature = p11CryptService.CKM_RSA_PKCS(psoMessage, slot, keyId);
            } else {
                throw new RuntimeException("should not reach here");
            }

            respItvInfoValue = new DEROctetString(signature);
            break;
        }
        case XipkiCmpConstants.ACTION_RP11_GET_CERTIFICATE:
        case XipkiCmpConstants.ACTION_RP11_GET_PUBLICKEY: {
            P11SlotIdentifier slot = null;
            P11KeyIdentifier keyId = null;
            try {
                SlotAndKeyIdentifer slotAndKeyIdentifier = SlotAndKeyIdentifer.getInstance(reqValue);
                slot = slotAndKeyIdentifier.getSlotIdentifier().getSlotId();
                KeyIdentifier keyIdentifier = slotAndKeyIdentifier.getKeyIdentifier();
                keyId = keyIdentifier.getKeyId();
            } catch (IllegalArgumentException e) {
                final String statusMessage = "invalid SlotAndKeyIdentifier";
                return createRejectionPKIMessage(respHeader, PKIFailureInfo.badRequest, statusMessage);
            }

            byte[] encodeCertOrKey;
            if (XipkiCmpConstants.ACTION_RP11_GET_CERTIFICATE == action) {
                encodeCertOrKey = p11CryptService.getCertificate(slot, keyId).getEncoded();
            } else if (XipkiCmpConstants.ACTION_RP11_GET_PUBLICKEY == action) {
                encodeCertOrKey = p11CryptService.getPublicKey(slot, keyId).getEncoded();
            } else {
                throw new RuntimeException("should not reach here");
            }

            respItvInfoValue = new DEROctetString(encodeCertOrKey);
            break;
        }
        case XipkiCmpConstants.ACTION_RP11_LIST_SLOTS: {
            P11SlotIdentifier[] slotIds = p11CryptService.getSlotIdentifiers();

            ASN1EncodableVector vector = new ASN1EncodableVector();
            for (P11SlotIdentifier slotId : slotIds) {
                vector.add(new SlotIdentifier(slotId));
            }
            respItvInfoValue = new DERSequence(vector);
            break;
        }
        case XipkiCmpConstants.ACTION_RP11_LIST_KEYLABELS: {
            SlotIdentifier slotId = SlotIdentifier.getInstance(reqValue);
            String[] keyLabels = p11CryptService.getKeyLabels(slotId.getSlotId());

            ASN1EncodableVector vector = new ASN1EncodableVector();
            for (String keyLabel : keyLabels) {
                vector.add(new DERUTF8String(keyLabel));
            }
            respItvInfoValue = new DERSequence(vector);
            break;
        }
        default: {
            final String statusMessage = "unsupported XiPKI action code '" + action + "'";
            return createRejectionPKIMessage(respHeader, PKIFailureInfo.badRequest, statusMessage);
        }
        } // end switch(code)

        ASN1EncodableVector v = new ASN1EncodableVector();
        v.add(new ASN1Integer(action));
        if (respItvInfoValue != null) {
            v.add(respItvInfoValue);
        }
        InfoTypeAndValue respItv = new InfoTypeAndValue(ObjectIdentifiers.id_xipki_cmp, new DERSequence(v));
        GenRepContent genRepContent = new GenRepContent(respItv);
        PKIBody respBody = new PKIBody(PKIBody.TYPE_GEN_REP, genRepContent);
        return new PKIMessage(respHeader, respBody);
    } catch (Throwable t) {
        LOG.error("error while processing CMP message {}, message: {}", tidStr, t.getMessage());
        LOG.debug("error while processing CMP message " + tidStr, t);
        return createRejectionPKIMessage(respHeader, PKIFailureInfo.systemFailure, t.getMessage());
    }
}

From source file:org.xipki.security.api.p11.remote.KeyIdentifier.java

License:Open Source License

@Override
public ASN1Primitive toASN1Primitive() {
    if (keyId.getKeyLabel() != null) {
        return new DERUTF8String(keyId.getKeyLabel());
    } else {/*w w  w.  j  av a  2s  .  c o  m*/
        return new DEROctetString(keyId.getKeyId());
    }
}

From source file:org.xipki.security.api.p11.remote.PSOTemplate.java

License:Open Source License

@Override
public ASN1Primitive toASN1Primitive() {
    ASN1EncodableVector vector = new ASN1EncodableVector();
    vector.add(slotAndKeyIdentifier.toASN1Primitive());
    vector.add(new DEROctetString(message));
    return new DERSequence(vector);
}

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;
    }//from w  ww  .  j a  va2 s .  c  om
    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.remote.RemoteP11CryptService.java

License:Open Source License

private PKIHeader buildPKIHeader(ASN1OctetString tid) {
    PKIHeaderBuilder hBuilder = new PKIHeaderBuilder(PKIHeader.CMP_2000, sender, recipient);
    hBuilder.setMessageTime(new ASN1GeneralizedTime(new Date()));

    if (tid == null) {
        tid = new DEROctetString(randomTransactionId());
    }/*from  w  ww  .j  a v a  2s  .c om*/
    hBuilder.setTransactionID(tid);

    return hBuilder.build();
}

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.// w  w  w.ja v a2  s .c  om
 * @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./*from w w  w  .  j ava  2s.  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./*www  .  j  a  va2  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./* ww  w .j ava2 s . c  o m*/
 *
 * @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);
}