use of org.xipki.security.pkcs11.P11TokenException in project xipki by xipki.
the class XiKeyStoreSpi method engineLoad.
private void engineLoad(String moduleName) throws P11TokenException, XiSecurityException {
P11CryptService p11Service = p11CryptServiceFactory.getP11CryptService(moduleName);
P11Module module = p11Service.getModule();
List<P11SlotIdentifier> slotIds = module.getSlotIds();
for (P11SlotIdentifier slotId : slotIds) {
P11Slot slot = module.getSlot(slotId);
Set<P11ObjectIdentifier> identityIds = slot.getIdentityIdentifiers();
for (P11ObjectIdentifier objId : identityIds) {
P11Identity identity = slot.getIdentity(objId);
X509Certificate[] chain = identity.certificateChain();
if (chain == null || chain.length == 0) {
continue;
}
P11PrivateKey key = new P11PrivateKey(p11Service, identity.getIdentityId());
KeyCertEntry keyCertEntry = new KeyCertEntry(key, chain);
keyCerts.put(moduleName + "#slotid-" + slotId.getId() + "#keyid-" + objId.getIdHex(), keyCertEntry);
keyCerts.put(moduleName + "#slotid-" + slotId.getId() + "#keylabel-" + objId.getLabel(), keyCertEntry);
keyCerts.put(moduleName + "#slotindex-" + slotId.getIndex() + "#keyid-" + objId.getIdHex(), keyCertEntry);
keyCerts.put(moduleName + "#slotindex-" + slotId.getIndex() + "#keylabel-" + objId.getLabel(), keyCertEntry);
}
}
}
use of org.xipki.security.pkcs11.P11TokenException in project xipki by xipki.
the class P11SM3WithSM2SignatureSpi method engineSign.
@Override
protected byte[] engineSign() throws SignatureException {
byte[] dataToSign;
if (outputStream instanceof ByteArrayOutputStream) {
dataToSign = ((ByteArrayOutputStream) outputStream).toByteArray();
((ByteArrayOutputStream) outputStream).reset();
} else {
dataToSign = ((DigestOutputStream) outputStream).digest();
((DigestOutputStream) outputStream).reset();
try {
outputStream.write(sm2Z, 0, sm2Z.length);
} catch (IOException ex) {
throw new SignatureException(ex.getMessage(), ex);
}
}
try {
byte[] plainSignature = signingKey.sign(mechanism, p11Params, dataToSign);
return SignerUtil.dsaSigPlainToX962(plainSignature);
} catch (XiSecurityException | P11TokenException ex) {
throw new SignatureException(ex.getMessage(), ex);
}
}
use of org.xipki.security.pkcs11.P11TokenException in project xipki by xipki.
the class P11ContentSignerBuilder method createSigner.
// constructor
public ConcurrentContentSigner createSigner(AlgorithmIdentifier signatureAlgId, int parallelism) throws XiSecurityException, P11TokenException {
ParamUtil.requireMin("parallelism", parallelism, 1);
List<XiContentSigner> signers = new ArrayList<>(parallelism);
Boolean isSm2p256v1 = null;
for (int i = 0; i < parallelism; i++) {
XiContentSigner signer;
if (publicKey instanceof RSAPublicKey) {
if (i == 0 && !AlgorithmUtil.isRSASigAlgId(signatureAlgId)) {
throw new XiSecurityException("the given algorithm is not a valid RSA signature algorithm '" + signatureAlgId.getAlgorithm().getId() + "'");
}
signer = createRSAContentSigner(signatureAlgId);
} else if (publicKey instanceof ECPublicKey) {
ECPublicKey ecKey = (ECPublicKey) publicKey;
if (i == 0) {
isSm2p256v1 = GMUtil.isSm2primev2Curve(ecKey.getParams().getCurve());
if (isSm2p256v1) {
if (!AlgorithmUtil.isSM2SigAlg(signatureAlgId)) {
throw new XiSecurityException("the given algorithm is not a valid SM2 signature algorithm '" + signatureAlgId.getAlgorithm().getId() + "'");
}
} else {
if (!AlgorithmUtil.isECSigAlg(signatureAlgId)) {
throw new XiSecurityException("the given algorithm is not a valid EC signature algorithm '" + signatureAlgId.getAlgorithm().getId() + "'");
}
}
}
if (isSm2p256v1) {
java.security.spec.ECPoint w = ecKey.getW();
signer = createSM2ContentSigner(signatureAlgId, GMObjectIdentifiers.sm2p256v1, w.getAffineX(), w.getAffineY());
} else {
signer = createECContentSigner(signatureAlgId);
}
} else if (publicKey instanceof DSAPublicKey) {
if (i == 0 && !AlgorithmUtil.isDSASigAlg(signatureAlgId)) {
throw new XiSecurityException("the given algorithm is not a valid DSA signature algorithm '" + signatureAlgId.getAlgorithm().getId() + "'");
}
signer = createDSAContentSigner(signatureAlgId);
} else {
throw new XiSecurityException("unsupported key " + publicKey.getClass().getName());
}
signers.add(signer);
}
// end for
final boolean mac = false;
PrivateKey privateKey = new P11PrivateKey(cryptService, identityId);
DfltConcurrentContentSigner concurrentSigner;
try {
concurrentSigner = new DfltConcurrentContentSigner(mac, signers, privateKey);
} catch (NoSuchAlgorithmException ex) {
throw new XiSecurityException(ex.getMessage(), ex);
}
if (certificateChain != null) {
concurrentSigner.setCertificateChain(certificateChain);
} else {
concurrentSigner.setPublicKey(publicKey);
}
return concurrentSigner;
}
use of org.xipki.security.pkcs11.P11TokenException in project xipki by xipki.
the class P11ProxyResponder method processRequest.
/**
* The request is constructed as follows:
* <pre>
* 0 - - - 1 - - - 2 - - - 3 - - - 4 - - - 5 - - - 6 - - - 7 - - - 8
* | Version | Transaction ID | Body ... |
* | ... Length | Action | Module ID | Content... |
* | .Content | <-- 10 + Length (offset).
*
* </pre>
*/
byte[] processRequest(LocalP11CryptServicePool pool, byte[] request) {
int reqLen = request.length;
// TransactionID
byte[] transactionId = new byte[4];
if (reqLen > 5) {
System.arraycopy(request, 2, transactionId, 0, 4);
}
// Action
short action = P11ProxyConstants.ACTION_NOPE;
if (reqLen > 11) {
action = IoUtil.parseShort(request, 10);
}
if (reqLen < 14) {
LOG.error("response too short");
return getResp(P11ProxyConstants.VERSION_V1_0, transactionId, action, P11ProxyConstants.RC_BAD_REQUEST);
}
// Version
short version = IoUtil.parseShort(request, 0);
if (!versions.contains(version)) {
LOG.error("unsupported version {}", version);
return getResp(P11ProxyConstants.VERSION_V1_0, transactionId, action, P11ProxyConstants.RC_UNSUPPORTED_VERSION);
}
// Length
int reqBodyLen = IoUtil.parseInt(request, 6);
if (reqBodyLen + 10 != reqLen) {
LOG.error("message length unmatch");
return getResp(version, transactionId, action, P11ProxyConstants.RC_BAD_REQUEST);
}
short moduleId = IoUtil.parseShort(request, 12);
int contentLen = reqLen - 14;
byte[] content;
if (contentLen == 0) {
if (actionsRequireNonNullRequest.contains(action)) {
LOG.error("content is not present but is required");
return getResp(version, transactionId, P11ProxyConstants.RC_BAD_REQUEST, action);
}
content = null;
} else {
if (actionsRequireNullRequest.contains(action)) {
LOG.error("content is present but is not permitted");
return getResp(version, transactionId, P11ProxyConstants.RC_BAD_REQUEST, action);
}
content = new byte[contentLen];
System.arraycopy(request, 14, content, 0, contentLen);
}
P11CryptService p11CryptService = pool.getP11CryptService(moduleId);
if (p11CryptService == null) {
LOG.error("no module {} available", moduleId);
return getResp(version, transactionId, P11ProxyConstants.RC_UNKNOWN_MODULE, action);
}
try {
switch(action) {
case P11ProxyConstants.ACTION_ADD_CERT:
{
Asn1EntityIdAndCert asn1 = Asn1EntityIdAndCert.getInstance(content);
P11Slot slot = getSlot(p11CryptService, asn1.getEntityId());
X509Certificate cert = X509Util.toX509Cert(asn1.getCertificate());
slot.addCert(asn1.getEntityId().getObjectId().getObjectId(), cert);
return getSuccessResp(version, transactionId, action, (byte[]) null);
}
case P11ProxyConstants.ACTION_DIGEST_SECRETKEY:
{
Asn1DigestSecretKeyTemplate template = Asn1DigestSecretKeyTemplate.getInstance(content);
long mechanism = template.getMechanism().getMechanism();
P11Identity identity = p11CryptService.getIdentity(template.getIdentityId().getEntityId());
byte[] hashValue = identity.digestSecretKey(mechanism);
ASN1Object obj = new DEROctetString(hashValue);
return getSuccessResp(version, transactionId, action, obj);
}
case P11ProxyConstants.ACTION_GEN_KEYPAIR_DSA:
{
Asn1GenDSAKeypairParams asn1 = Asn1GenDSAKeypairParams.getInstance(content);
P11Slot slot = getSlot(p11CryptService, asn1.getSlotId());
P11ObjectIdentifier keyId = slot.generateDSAKeypair(asn1.getP(), asn1.getQ(), asn1.getG(), asn1.getLabel(), asn1.getControl());
ASN1Object obj = new Asn1P11EntityIdentifier(asn1.getSlotId(), keyId);
return getSuccessResp(version, transactionId, action, obj);
}
case P11ProxyConstants.ACTION_GEN_KEYPAIR_EC:
{
Asn1GenECKeypairParams asn1 = Asn1GenECKeypairParams.getInstance(content);
P11Slot slot = getSlot(p11CryptService, asn1.getSlotId());
P11ObjectIdentifier keyId = slot.generateECKeypair(asn1.getCurveId().getId(), asn1.getLabel(), asn1.getControl());
ASN1Object obj = new Asn1P11EntityIdentifier(asn1.getSlotId(), keyId);
return getSuccessResp(version, transactionId, action, obj);
}
case P11ProxyConstants.ACTION_GEN_KEYPAIR_RSA:
{
Asn1GenRSAKeypairParams asn1 = Asn1GenRSAKeypairParams.getInstance(content);
P11Slot slot = getSlot(p11CryptService, asn1.getSlotId());
P11ObjectIdentifier keyId = slot.generateRSAKeypair(asn1.getKeysize(), asn1.getPublicExponent(), asn1.getLabel(), asn1.getControl());
ASN1Object obj = new Asn1P11EntityIdentifier(asn1.getSlotId(), keyId);
return getSuccessResp(version, transactionId, action, obj);
}
case P11ProxyConstants.ACTION_GEN_KEYPAIR_SM2:
{
Asn1GenSM2KeypairParams asn1 = Asn1GenSM2KeypairParams.getInstance(content);
P11Slot slot = getSlot(p11CryptService, asn1.getSlotId());
P11ObjectIdentifier keyId = slot.generateSM2Keypair(asn1.getLabel(), asn1.getControl());
ASN1Object obj = new Asn1P11EntityIdentifier(asn1.getSlotId(), keyId);
return getSuccessResp(version, transactionId, action, obj);
}
case P11ProxyConstants.ACTION_GEN_SECRET_KEY:
{
Asn1GenSecretKeyParams asn1 = Asn1GenSecretKeyParams.getInstance(content);
P11Slot slot = getSlot(p11CryptService, asn1.getSlotId());
P11ObjectIdentifier keyId = slot.generateSecretKey(asn1.getKeyType(), asn1.getKeysize(), asn1.getLabel(), asn1.getControl());
ASN1Object obj = new Asn1P11EntityIdentifier(asn1.getSlotId(), keyId);
return getSuccessResp(version, transactionId, action, obj);
}
case P11ProxyConstants.ACTION_GET_CERT:
{
P11EntityIdentifier entityId = Asn1P11EntityIdentifier.getInstance(content).getEntityId();
X509Certificate cert = p11CryptService.getIdentity(entityId).getCertificate();
return getSuccessResp(version, transactionId, action, cert.getEncoded());
}
case P11ProxyConstants.ACTION_GET_CERT_IDS:
case P11ProxyConstants.ACTION_GET_IDENTITY_IDS:
{
Asn1P11SlotIdentifier slotId = Asn1P11SlotIdentifier.getInstance(content);
P11Slot slot = p11CryptService.getModule().getSlot(slotId.getSlotId());
Set<P11ObjectIdentifier> objectIds;
if (P11ProxyConstants.ACTION_GET_CERT_IDS == action) {
objectIds = slot.getCertIdentifiers();
} else {
objectIds = slot.getIdentityIdentifiers();
}
ASN1EncodableVector vec = new ASN1EncodableVector();
for (P11ObjectIdentifier objectId : objectIds) {
vec.add(new Asn1P11ObjectIdentifier(objectId));
}
ASN1Object obj = new DERSequence(vec);
return getSuccessResp(version, transactionId, action, obj);
}
case P11ProxyConstants.ACTION_GET_MECHANISMS:
{
P11SlotIdentifier slotId = Asn1P11SlotIdentifier.getInstance(content).getSlotId();
Set<Long> mechs = p11CryptService.getSlot(slotId).getMechanisms();
ASN1EncodableVector vec = new ASN1EncodableVector();
for (Long mech : mechs) {
vec.add(new ASN1Integer(mech));
}
ASN1Object obj = new DERSequence(vec);
return getSuccessResp(version, transactionId, action, obj);
}
case P11ProxyConstants.ACTION_GET_PUBLICKEY:
{
P11EntityIdentifier identityId = Asn1P11EntityIdentifier.getInstance(content).getEntityId();
PublicKey pubKey = p11CryptService.getIdentity(identityId).getPublicKey();
if (pubKey == null) {
throw new P11UnknownEntityException(identityId);
}
ASN1Object obj = KeyUtil.createSubjectPublicKeyInfo(pubKey);
return getSuccessResp(version, transactionId, action, obj);
}
case P11ProxyConstants.ACTION_GET_SERVER_CAPS:
{
boolean readOnly = p11CryptService.getModule().isReadOnly();
ASN1Object obj = new Asn1ServerCaps(readOnly, versions);
return getSuccessResp(version, transactionId, action, obj);
}
case P11ProxyConstants.ACTION_GET_SLOT_IDS:
{
List<P11SlotIdentifier> slotIds = p11CryptService.getModule().getSlotIds();
ASN1EncodableVector vector = new ASN1EncodableVector();
for (P11SlotIdentifier slotId : slotIds) {
vector.add(new Asn1P11SlotIdentifier(slotId));
}
ASN1Object obj = new DERSequence(vector);
return getSuccessResp(version, transactionId, action, obj);
}
case P11ProxyConstants.ACTION_IMPORT_SECRET_KEY:
{
Asn1ImportSecretKeyParams asn1 = Asn1ImportSecretKeyParams.getInstance(content);
P11Slot slot = getSlot(p11CryptService, asn1.getSlotId());
P11ObjectIdentifier keyId = slot.importSecretKey(asn1.getKeyType(), asn1.getKeyValue(), asn1.getLabel(), asn1.getControl());
ASN1Object obj = new Asn1P11EntityIdentifier(asn1.getSlotId(), keyId);
return getSuccessResp(version, transactionId, action, obj);
}
case P11ProxyConstants.ACTION_REMOVE_CERTS:
{
Asn1P11EntityIdentifier asn1 = Asn1P11EntityIdentifier.getInstance(content);
P11Slot slot = getSlot(p11CryptService, asn1);
slot.removeCerts(asn1.getObjectId().getObjectId());
return getSuccessResp(version, transactionId, action, (byte[]) null);
}
case P11ProxyConstants.ACTION_REMOVE_IDENTITY:
{
Asn1P11EntityIdentifier asn1 = Asn1P11EntityIdentifier.getInstance(content);
P11Slot slot = getSlot(p11CryptService, asn1);
slot.removeIdentity(asn1.getObjectId().getObjectId());
return getSuccessResp(version, transactionId, action, (byte[]) null);
}
case P11ProxyConstants.ACTION_REMOVE_OBJECTS:
{
Asn1RemoveObjectsParams asn1 = Asn1RemoveObjectsParams.getInstance(content);
P11Slot slot = getSlot(p11CryptService, asn1.getSlotId());
int num = slot.removeObjects(asn1.getOjectId(), asn1.getObjectLabel());
ASN1Object obj = new ASN1Integer(num);
return getSuccessResp(version, transactionId, action, obj);
}
case P11ProxyConstants.ACTION_SIGN:
{
Asn1SignTemplate signTemplate = Asn1SignTemplate.getInstance(content);
long mechanism = signTemplate.getMechanism().getMechanism();
Asn1P11Params asn1Params = signTemplate.getMechanism().getParams();
P11Params params = null;
if (asn1Params != null) {
switch(asn1Params.getTagNo()) {
case Asn1P11Params.TAG_RSA_PKCS_PSS:
params = Asn1RSAPkcsPssParams.getInstance(asn1Params).getPkcsPssParams();
break;
case Asn1P11Params.TAG_OPAQUE:
params = new P11ByteArrayParams(ASN1OctetString.getInstance(asn1Params).getOctets());
break;
case Asn1P11Params.TAG_IV:
params = new P11IVParams(ASN1OctetString.getInstance(asn1Params).getOctets());
break;
default:
throw new BadAsn1ObjectException("unknown SignTemplate.params: unknown tag " + asn1Params.getTagNo());
}
}
byte[] message = signTemplate.getMessage();
P11Identity identity = p11CryptService.getIdentity(signTemplate.getIdentityId().getEntityId());
byte[] signature = identity.sign(mechanism, params, message);
ASN1Object obj = new DEROctetString(signature);
return getSuccessResp(version, transactionId, action, obj);
}
case P11ProxyConstants.ACTION_UPDATE_CERT:
{
Asn1EntityIdAndCert asn1 = Asn1EntityIdAndCert.getInstance(content);
P11Slot slot = getSlot(p11CryptService, asn1.getEntityId());
slot.updateCertificate(asn1.getEntityId().getObjectId().getObjectId(), X509Util.toX509Cert(asn1.getCertificate()));
return getSuccessResp(version, transactionId, action, (byte[]) null);
}
default:
{
LOG.error("unsupported XiPKI action code '{}'", action);
return getResp(version, transactionId, action, P11ProxyConstants.RC_UNSUPPORTED_ACTION);
}
}
} catch (BadAsn1ObjectException ex) {
LogUtil.error(LOG, ex, "could not process decode requested content (tid=" + Hex.encode(transactionId) + ")");
return getResp(version, transactionId, action, P11ProxyConstants.RC_BAD_REQUEST);
} catch (P11TokenException ex) {
LogUtil.error(LOG, ex, buildErrorMsg(action, transactionId));
short rc;
if (ex instanceof P11UnknownEntityException) {
rc = P11ProxyConstants.RC_DUPLICATE_ENTITY;
} else if (ex instanceof P11DuplicateEntityException) {
rc = P11ProxyConstants.RC_DUPLICATE_ENTITY;
} else if (ex instanceof P11UnsupportedMechanismException) {
rc = P11ProxyConstants.RC_UNSUPPORTED_MECHANISM;
} else {
rc = P11ProxyConstants.RC_P11_TOKENERROR;
}
return getResp(version, transactionId, action, rc);
} catch (XiSecurityException | CertificateException | InvalidKeyException ex) {
LogUtil.error(LOG, ex, buildErrorMsg(action, transactionId));
return getResp(version, transactionId, action, P11ProxyConstants.RC_INTERNAL_ERROR);
} catch (Throwable th) {
LogUtil.error(LOG, th, buildErrorMsg(action, transactionId));
return getResp(version, transactionId, action, P11ProxyConstants.RC_INTERNAL_ERROR);
}
}
use of org.xipki.security.pkcs11.P11TokenException in project xipki by xipki.
the class BSpeedP11Action method getSlot.
protected P11Slot getSlot() throws XiSecurityException, P11TokenException, IllegalCmdParamException {
P11CryptService p11Service = p11CryptServiceFactory.getP11CryptService(moduleName);
if (p11Service == null) {
throw new IllegalCmdParamException("undefined module " + moduleName);
}
P11Module module = p11Service.getModule();
P11SlotIdentifier slotId = module.getSlotIdForIndex(slotIndex);
return module.getSlot(slotId);
}
Aggregations