private Properties loadProperties(File file) throws P11TokenException { try { try (InputStream stream = Files.newInputStream(file.toPath())) { Properties props = new Properties(); props.load(stream); return props; } } catch (IOException ex) { throw new P11TokenException("could not load properties from the file " + file.getPath(), ex); } }
@Override public byte[] getSignature() { try { byte[] dataToSign = outputStream.toByteArray(); outputStream.reset(); return cryptService.getIdentity(identityId).sign(mechanism, null, dataToSign); } catch (P11TokenException ex) { LogUtil.warn(LOG, ex); throw new RuntimeCryptoException("P11TokenException: " + ex.getMessage()); } catch (Throwable th) { LogUtil.warn(LOG, th); throw new RuntimeCryptoException(th.getClass().getName() + ": " + th.getMessage()); } }
encodedCurveId = curveId.getEncoded(); } catch (IOException ex) { throw new P11TokenException(ex.getMessage(), ex); publicKey.getEcdsaParams().setByteArrayValue(ecParams.getEncoded()); } catch (IOException ex2) { throw new P11TokenException(ex.getMessage(), ex);
private static void bigIntToBytes(String numName, BigInteger num, byte[] dest, int destPos, int length) throws P11TokenException { if (num.signum() != 1) { throw new P11TokenException(numName + " is not positive"); } byte[] bytes = num.toByteArray(); if (bytes.length == length) { System.arraycopy(bytes, 0, dest, destPos, length); } else if (bytes.length < length) { System.arraycopy(bytes, 0, dest, destPos + length - bytes.length, bytes.length); } else { System.arraycopy(bytes, bytes.length - length, dest, destPos, length); } }
public static P11RSAKeyParameter getInstance(P11CryptService p11CryptService, P11IdentityId identityId) throws InvalidKeyException { Args.notNull(p11CryptService, "p11CryptService"); Args.notNull(identityId, "identityId"); RSAPublicKey key; try { key = (RSAPublicKey) p11CryptService.getIdentity(identityId).getPublicKey(); } catch (P11TokenException ex) { throw new InvalidKeyException(ex.getMessage(), ex); } BigInteger modulus = key.getModulus(); BigInteger publicExponent = key.getPublicExponent(); return new P11RSAKeyParameter(p11CryptService, identityId, modulus, publicExponent); }
private ASN1Sequence requireSequence(byte[] response) throws P11TokenException { try { return ASN1Sequence.getInstance(response); } catch (IllegalArgumentException ex) { throw new P11TokenException("response is not ASN1Sequence", ex); } }
@Override public byte[] processBlock(byte[] in, int inOff, int len) throws InvalidCipherTextException { byte[] content = new byte[getInputBlockSize()]; System.arraycopy(in, inOff, content, content.length - len, len); try { P11Identity identity = param.getP11CryptService().getIdentity(param.getIdentityId()); return identity.sign(PKCS11Constants.CKM_RSA_X_509, null, content); } catch (P11TokenException ex) { throw new InvalidCipherTextException(ex.getMessage(), ex); } }
public void setCertificates(X509Certificate[] certificateChain) throws P11TokenException { if (CollectionUtil.isEmpty(certificateChain)) { this.certificateChain = null; } else { PublicKey pk = certificateChain[0].getPublicKey(); if (!this.publicKey.equals(pk)) { throw new P11TokenException("certificateChain is not for the key"); } this.certificateChain = certificateChain; } }
@Override public byte[] getSignature() { if (outputStream instanceof PSSSignerOutputStream) { try { return ((PSSSignerOutputStream) outputStream).generateSignature(); } catch (CryptoException ex) { LogUtil.warn(LOG, ex); throw new RuntimeCryptoException("CryptoException: " + ex.getMessage()); } } byte[] dataToSign; if (outputStream instanceof ByteArrayOutputStream) { dataToSign = ((ByteArrayOutputStream) outputStream).toByteArray(); } else { dataToSign = ((DigestOutputStream) outputStream).digest(); } try { return cryptService.getIdentity(identityId).sign(mechanism, parameters, dataToSign); } catch (P11TokenException ex) { LogUtil.warn(LOG, ex, "could not sign"); throw new RuntimeCryptoException("SignerException: " + ex.getMessage()); } }
@Override protected byte[] digestSecretKey0(long mechanism) throws P11TokenException { if (!(signingKey instanceof SecretKey)) { throw new P11TokenException("digestSecretKey could not be applied to non-SecretKey"); } HashAlgo hashAlgo = getHashAlgoForPkcs11HashMech(mechanism); if (hashAlgo == null) { throw new P11TokenException( "unknown mechanism " + Functions.mechanismCodeToString(mechanism)); } return hashAlgo.hash(((SecretKey) signingKey).getEncoded()); }
@Override protected byte[] digestSecretKey0(long mechanism) throws P11TokenException { if (! (signingKey instanceof SecretKey)) { throw new P11TokenException("could not digest asymmetric key"); } Boolean bv = ((SecretKey) signingKey).getExtractable().getBooleanValue(); if (bv != null && !bv.booleanValue()) { throw new P11TokenException("could not digest unextractable key"); } bv = ((SecretKey) signingKey).getNeverExtractable().getBooleanValue(); if (bv != null && bv.booleanValue()) { throw new P11TokenException("could not digest unextractable key"); } return ((IaikP11Slot) slot).digestKey(mechanism, this); }
private String savePkcs11SecretKey(byte[] id, String label, SecretKey secretKey) throws P11TokenException { assertValidId(id); if (vendor == Vendor.YUBIKEY) { label = "Secret key " + id[0]; } byte[] encrytedValue; try { KeyStore ks = KeyStore.getInstance("JCEKS"); ks.load(null, password); ks.setKeyEntry("main", secretKey, password, null); ByteArrayOutputStream outStream = new ByteArrayOutputStream(); ks.store(outStream, password); outStream.flush(); encrytedValue = outStream.toByteArray(); } catch (NoSuchAlgorithmException | KeyStoreException | CertificateException | IOException ex) { throw new P11TokenException(ex.getClass().getName() + ": " + ex.getMessage(), ex); } savePkcs11Entry(secKeyDir, id, label, encrytedValue); return label; }
private byte[] rsaX509Sign(byte[] dataToSign) throws P11TokenException { ConcurrentBagEntry<Cipher> cipher; try { cipher = rsaCiphers.borrow(5000, TimeUnit.MILLISECONDS); } catch (InterruptedException ex) { throw new P11TokenException("could not take any idle signer"); } if (cipher == null) { throw new P11TokenException("no idle RSA cipher available"); } try { return cipher.value().doFinal(dataToSign); } catch (BadPaddingException ex) { throw new P11TokenException("BadPaddingException: " + ex.getMessage(), ex); } catch (IllegalBlockSizeException ex) { throw new P11TokenException("IllegalBlockSizeException: " + ex.getMessage(), ex); } finally { rsaCiphers.requite(cipher); } }
private static P11TokenException buildP11TokenException(long p11ErrorCode) { return new P11TokenException(new PKCS11Exception(p11ErrorCode)); }
private void singleLogin(Session session, char[] pin) throws P11TokenException { char[] tmpPin = pin; // some driver does not accept null PIN if (pin == null) { tmpPin = new char[]{}; } try { session.login(userType, tmpPin); LOG.info("login successful as user " + userTypeText); } catch (TokenException ex) { // 0x100: user already logged in if (ex instanceof PKCS11Exception && ((PKCS11Exception) ex).getErrorCode() == 0x100) { LOG.info("user already logged in"); } else { LOG.info("login failed as user " + userTypeText); throw new P11TokenException( "login failed as user " + userTypeText + ": " + ex.getMessage(), ex); } } }
@Override protected P11Identity generateRSAKeypair0(int keysize, BigInteger publicExponent, P11NewKeyControl control) throws P11TokenException { assertMechanismSupported(PKCS11Constants.CKM_RSA_PKCS_KEY_PAIR_GEN); KeyPair keypair; try { keypair = KeyUtil.generateRSAKeypair(keysize, publicExponent, random); } catch (NoSuchAlgorithmException | NoSuchProviderException | InvalidAlgorithmParameterException ex) { throw new P11TokenException(ex.getMessage(), ex); } return saveP11Entity(keypair, control); }
private byte[] sm2Sign(P11Params params, byte[] dataToSign, HashAlgo hash) throws P11TokenException { if (params == null) { throw new P11TokenException("userId may not be null"); userId = ((P11Params.P11ByteArrayParams) params).getBytes(); } else { throw new P11TokenException("params must be instanceof P11ByteArrayParams"); sig0 = sm2Signers.borrow(5000, TimeUnit.MILLISECONDS); } catch (InterruptedException ex) { throw new P11TokenException("InterruptedException occurs while retrieving idle signature"); throw new P11TokenException("no idle SM2 Signer available"); return SignerUtil.dsaSigX962ToPlain(x962Signature, getSignatureKeyBitLength()); } catch (CryptoException ex) { throw new P11TokenException("CryptoException: " + ex.getMessage(), ex); } catch (XiSecurityException ex) { throw new P11TokenException("XiSecurityException: " + ex.getMessage(), ex); } finally { sm2Signers.requite(sig0);
private byte[] dsaAndEcdsaSign(byte[] dataToSign, HashAlgo hashAlgo) throws P11TokenException { byte[] hash = (hashAlgo == null) ? dataToSign : hashAlgo.hash(dataToSign); ConcurrentBagEntry<Signature> sig0; try { sig0 = dsaSignatures.borrow(5000, TimeUnit.MILLISECONDS); } catch (InterruptedException ex) { throw new P11TokenException("InterruptedException occurs while retrieving idle signature"); } if (sig0 == null) { throw new P11TokenException("no idle DSA Signature available"); } try { Signature sig = sig0.value(); sig.update(hash); byte[] x962Signature = sig.sign(); return SignerUtil.dsaSigX962ToPlain(x962Signature, getSignatureKeyBitLength()); } catch (SignatureException ex) { throw new P11TokenException("SignatureException: " + ex.getMessage(), ex); } catch (XiSecurityException ex) { throw new P11TokenException("XiSecurityException: " + ex.getMessage(), ex); } finally { dsaSignatures.requite(sig0); } }
@Override public int removeObjects(byte[] id, String label) throws P11TokenException { if ((id == null || id.length == 0) && StringUtil.isBlank(label)) { throw new IllegalArgumentException("at least one of id and label must not be null"); } ProxyMessage.RemoveObjectsParams params = new ProxyMessage.RemoveObjectsParams(slotId, id, label); byte[] resp = module.send(P11ProxyConstants.ACTION_REMOVE_OBJECTS, params); try { return ASN1Integer.getInstance(resp).getValue().intValue(); } catch (IllegalArgumentException ex) { throw new P11TokenException(ex.getMessage(), ex); } }
private Session openSession() throws P11TokenException { Session session; try { boolean rw = !isReadOnly(); session = slot.getToken().openSession(Token.SessionType.SERIAL_SESSION, rw, null, null); } catch (TokenException ex) { throw new P11TokenException(ex.getMessage(), ex); } countSessions.incrementAndGet(); return session; }