public static byte[] EMSA_PKCS1_v1_5_encoding(byte[] encodedDigestInfo, int modulusBigLength) throws XiSecurityException { Args.notNull(encodedDigestInfo, "encodedDigestInfo"); int msgLen = encodedDigestInfo.length; int blockSize = (modulusBigLength + 7) / 8; if (msgLen + 3 > blockSize) { throw new XiSecurityException("data too long (maximal " + (blockSize - 3) + " allowed): " + msgLen); } byte[] block = new byte[blockSize]; block[0] = 0x00; // type code 1 block[1] = 0x01; int offset = 2; while (offset < block.length - msgLen - 1) { block[offset++] = (byte) 0xFF; } // mark the end of the padding block[offset++] = 0x00; System.arraycopy(encodedDigestInfo, 0, block, offset, encodedDigestInfo.length); return block; }
public static byte[] EMSA_PSS_ENCODE(HashAlgo contentDigest, byte[] hashValue, HashAlgo mgfDigest, int saltLen, int modulusBitLength, SecureRandom random) throws XiSecurityException { final int hLen = contentDigest.getLength(); final byte[] salt = new byte[saltLen]; final byte[] mDash = new byte[8 + saltLen + hLen]; final byte trailer = (byte)0xBC; if (hashValue.length != hLen) { throw new XiSecurityException("hashValue.length is incorrect: " + hashValue.length + " != " + hLen); } int emBits = modulusBitLength - 1; if (emBits < (8 * hLen + 8 * saltLen + 9)) { throw new IllegalArgumentException("key too small for specified hash and salt lengths"); } System.arraycopy(hashValue, 0, mDash, mDash.length - hLen - saltLen, hLen); random.nextBytes(salt); System.arraycopy(salt, 0, mDash, mDash.length - saltLen, saltLen); byte[] hv = contentDigest.hash(mDash); byte[] block = new byte[(emBits + 7) / 8]; block[block.length - saltLen - 1 - hLen - 1] = 0x01; System.arraycopy(salt, 0, block, block.length - saltLen - hLen - 1, saltLen); byte[] dbMask = maskGeneratorFunction1(mgfDigest, hv, block.length - hLen - 1); for (int i = 0; i != dbMask.length; i++) { block[i] ^= dbMask[i]; } block[0] &= (0xff >> ((block.length * 8) - emBits)); System.arraycopy(hv, 0, block, block.length - hLen - 1, hLen); block[block.length - 1] = trailer; return block; }
@Override public void refreshToken(String type) throws XiSecurityException { if (!TYPE.equalsIgnoreCase(type)) { // Nothing to do return; } Set<String> errorModules = new HashSet<>(2); for (String name : p11CryptServiceFactory.getModuleNames()) { try { p11CryptServiceFactory.getP11CryptService(name).refresh(); } catch (P11TokenException ex) { LogUtil.error(LOG, ex, "could not refresh PKCS#11 module " + name); errorModules.add(name); } } if (!errorModules.isEmpty()) { throw new XiSecurityException("could not refreshed modules " + errorModules); } }
public static byte[] dsaSigToPlain(BigInteger sigR, BigInteger sigS, int keyBitLen) throws XiSecurityException { Args.notNull(sigR, "sigR"); Args.notNull(sigS, "sigS"); final int blockSize = (keyBitLen + 7) / 8; int bitLenOfR = sigR.bitLength(); int bitLenOfS = sigS.bitLength(); int bitLen = Math.max(bitLenOfR, bitLenOfS); if ((bitLen + 7) / 8 > blockSize) { throw new XiSecurityException("signature is too large"); } byte[] plainSignature = new byte[2 * blockSize]; bigIntToBytes(sigR, plainSignature, 0, blockSize); bigIntToBytes(sigS, plainSignature, blockSize, blockSize); return plainSignature; }
public static List<String[]> splitCaSignerConfs(String conf) throws XiSecurityException { ConfPairs pairs = new ConfPairs(conf); String str = pairs.value("algo"); if (str == null) { throw new XiSecurityException("no algo is defined in CA signerConf"); } List<String> list = StringUtil.split(str, ":"); if (CollectionUtil.isEmpty(list)) { throw new XiSecurityException("empty algo is defined in CA signerConf"); } List<String[]> signerConfs = new ArrayList<>(list.size()); for (String n : list) { String c14nAlgo; try { c14nAlgo = AlgorithmUtil.canonicalizeSignatureAlgo(n); } catch (NoSuchAlgorithmException ex) { throw new XiSecurityException(ex.getMessage(), ex); } pairs.putPair("algo", c14nAlgo); signerConfs.add(new String[]{c14nAlgo, pairs.getEncoded()}); } return signerConfs; }
public static byte[] dsaSigPlainToX962(byte[] signature) throws XiSecurityException { Args.notNull(signature, "signature"); if (signature.length % 2 != 0) { throw new XiSecurityException("signature.lenth must be even, but is odd"); } 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 { return seq.getEncoded(); } catch (IOException ex) { throw new XiSecurityException("IOException, message: " + ex.getMessage(), ex); } }
public XiWrappedContentSigner(ContentSigner signer, boolean fixedAlgorithmIdentifier) throws XiSecurityException { this.signer = Args.notNull(signer, "signer"); if (fixedAlgorithmIdentifier) { try { this.encodedAlgorithmIdentifier = signer.getAlgorithmIdentifier().getEncoded(); } catch (IOException ex) { throw new XiSecurityException("could not encode AlgorithmIdentifier", ex); } } }
public static byte[] EMSA_PKCS1_v1_5_encoding(byte[] hashValue, int modulusBigLength, HashAlgo hashAlgo) throws XiSecurityException { Args.notNull(hashValue, "hashValue"); Args.notNull(hashAlgo, "hashAlgo"); final int hashLen = hashAlgo.getLength(); Args.range(hashValue.length, "hashValue.length", hashLen, hashLen); int blockSize = (modulusBigLength + 7) / 8; byte[] prefix = digestPkcsPrefix.get(hashAlgo); if (prefix.length + hashLen + 3 > blockSize) { throw new XiSecurityException("data too long (maximal " + (blockSize - 3) + " allowed): " + (prefix.length + hashLen)); } byte[] block = new byte[blockSize]; block[0] = 0x00; // type code 1 block[1] = 0x01; int offset = 2; while (offset < block.length - prefix.length - hashLen - 1) { block[offset++] = (byte) 0xFF; } // mark the end of the padding block[offset++] = 0x00; System.arraycopy(prefix, 0, block, offset, prefix.length); offset += prefix.length; System.arraycopy(hashValue, 0, block, offset, hashValue.length); return block; }
DSA(P11CryptService cryptService, P11IdentityId identityId, AlgorithmIdentifier signatureAlgId, boolean plain) throws XiSecurityException, P11TokenException { super(cryptService, identityId, signatureAlgId); this.plain = plain; String algOid = signatureAlgId.getAlgorithm().getId(); HashAlgo hashAlgo = sigAlgHashMap.get(algOid); if (hashAlgo == null) { throw new XiSecurityException("unsupported signature algorithm " + algOid); } P11SlotIdentifier slotId = identityId.getSlotId(); P11Slot slot = cryptService.getSlot(slotId); if (slot.supportsMechanism(PKCS11Constants.CKM_DSA)) { this.mechanism = PKCS11Constants.CKM_DSA; Digest digest = hashAlgo.createDigest(); this.outputStream = new DigestOutputStream(digest); } else { this.mechanism = hashMechMap.get(hashAlgo).longValue(); if (!slot.supportsMechanism(this.mechanism)) { throw new XiSecurityException("unsupported signature algorithm " + algOid); } this.outputStream = new ByteArrayOutputStream(); } }
ECDSA(P11CryptService cryptService, P11IdentityId identityId, AlgorithmIdentifier signatureAlgId, boolean plain) throws XiSecurityException, P11TokenException { super(cryptService, identityId, signatureAlgId); this.plain = plain; String algOid = signatureAlgId.getAlgorithm().getId(); HashAlgo hashAlgo = sigAlgHashMap.get(algOid); if (hashAlgo == null) { throw new XiSecurityException("unsupported signature algorithm " + algOid); } P11Slot slot = cryptService.getSlot(identityId.getSlotId()); if (slot.supportsMechanism(PKCS11Constants.CKM_ECDSA)) { this.mechanism = PKCS11Constants.CKM_ECDSA; Digest digest = hashAlgo.createDigest(); this.outputStream = new DigestOutputStream(digest); } else { this.mechanism = hashMechMap.get(hashAlgo).longValue(); if (!slot.supportsMechanism(this.mechanism)) { throw new XiSecurityException("unsupported signature algorithm " + algOid); } this.outputStream = new ByteArrayOutputStream(); } }
SM2(P11CryptService cryptService, P11IdentityId identityId, AlgorithmIdentifier signatureAlgId, ASN1ObjectIdentifier curveOid, BigInteger pubPointX, BigInteger pubPointY) throws XiSecurityException, P11TokenException { super(cryptService, identityId, signatureAlgId); String algOid = signatureAlgId.getAlgorithm().getId(); HashAlgo hashAlgo = sigAlgHashMap.get(algOid); if (hashAlgo == null) { throw new XiSecurityException("unsupported signature algorithm " + algOid); } P11Slot slot = cryptService.getSlot(identityId.getSlotId()); if (slot.supportsMechanism(PKCS11Constants.CKM_VENDOR_SM2)) { this.z = GMUtil.getSM2Z(curveOid, pubPointX, pubPointY); this.mechanism = PKCS11Constants.CKM_VENDOR_SM2; Digest digest = hashAlgo.createDigest(); this.outputStream = new DigestOutputStream(digest); } else { this.z = null; // not required Long ll = hashMechMap.get(hashAlgo); if (ll == null) { throw new XiSecurityException("hash algorithm " + hashAlgo + " is not suitable for SM2"); } this.mechanism = ll.longValue(); if (!slot.supportsMechanism(this.mechanism)) { throw new XiSecurityException("unsupported signature algorithm " + algOid); } this.outputStream = new ByteArrayOutputStream(); } }
public synchronized P11CryptService getP11CryptService(String moduleName) throws XiSecurityException, P11TokenException { try { init(); } catch (InvalidConfException ex) { throw new IllegalStateException( "could not initialize P11CryptServiceFactory: " + ex.getMessage(), ex); } if (moduleConfs == null) { throw new IllegalStateException("please set pkcs11ConfFile and then call init() first"); } final String name = getModuleName(moduleName); P11ModuleConf conf = moduleConfs.get(name); if (conf == null) { throw new XiSecurityException("PKCS#11 module " + name + " is not defined"); } P11CryptService instance = services.get(name); if (instance == null) { P11Module p11Module = p11ModuleFactoryRegister.getP11Module(conf); instance = new P11CryptService(p11Module); LOG.info("added PKCS#11 module {}\n{}", name, instance.getModule().getDescription()); services.put(name, instance); } return instance; }
P11ContentSigner(P11CryptService cryptService, P11IdentityId identityId, AlgorithmIdentifier signatureAlgId) throws XiSecurityException, P11TokenException { this.identityId = Args.notNull(identityId, "identityId"); this.cryptService = Args.notNull(cryptService, "cryptService"); this.algorithmIdentifier = Args.notNull(signatureAlgId, "signatureAlgId"); try { this.encodedAlgorithmIdentifier = algorithmIdentifier.getEncoded(); } catch (IOException ex) { throw new XiSecurityException("could not encode AlgorithmIdentifier", ex); } }
public SignatureSigner(AlgorithmIdentifier sigAlgId, Signature signer, PrivateKey key) throws XiSecurityException { this.sigAlgId = Args.notNull(sigAlgId, "sigAlgId"); this.signer = Args.notNull(signer, "signer"); this.key = Args.notNull(key, "key"); try { this.encodedSigAlgId = sigAlgId.getEncoded(); } catch (IOException ex) { throw new XiSecurityException("could not encode AlgorithmIdentifier", ex); } }
HashAlgo hashAlgo = sigAlgHashAlgMap.get(algOid); if (hashAlgo == null) { throw new XiSecurityException("unsupported signature algorithm " + algOid.getId()); throw new XiSecurityException("unsupported signature algorithm " + algOid.getId());
public ConcurrentContentSigner createSigner(AlgorithmIdentifier signatureAlgId, int parallelism) throws XiSecurityException, P11TokenException { Args.positive(parallelism, "parallelism"); List<XiContentSigner> signers = new ArrayList<>(parallelism); for (int i = 0; i < parallelism; i++) { XiContentSigner signer = new P11ContentSigner.Mac(cryptService, identityId, signatureAlgId); signers.add(signer); } // end for final boolean mac = true; DfltConcurrentContentSigner concurrentSigner; try { concurrentSigner = new DfltConcurrentContentSigner(mac, signers, null); } catch (NoSuchAlgorithmException ex) { throw new XiSecurityException(ex.getMessage(), ex); } try { byte[] sha1HashOfKey = cryptService.getIdentity(identityId).digestSecretKey( PKCS11Constants.CKM_SHA_1); concurrentSigner.setSha1DigestOfMacKey(sha1HashOfKey); } catch (P11TokenException | XiSecurityException ex) { LogUtil.warn(LOG, ex, "could not compute the digest of secret key " + identityId); } return concurrentSigner; } // method createSigner
private static Digest getDigest(AlgorithmIdentifier hashAlgo) throws XiSecurityException { HashAlgo hat = HashAlgo.getInstance(hashAlgo.getAlgorithm()); if (hat != null) { return hat.createDigest(); } else { throw new XiSecurityException("could not get digest for " + hashAlgo.getAlgorithm().getId()); } }
public static PSSSigner createPSSRSASigner(AlgorithmIdentifier sigAlgId, AsymmetricBlockCipher cipher) throws XiSecurityException { Args.notNull(sigAlgId, "sigAlgId"); if (!PKCSObjectIdentifiers.id_RSASSA_PSS.equals(sigAlgId.getAlgorithm())) { throw new XiSecurityException("signature algorithm " + sigAlgId.getAlgorithm() + " is not allowed"); } AlgorithmIdentifier digAlgId; try { digAlgId = AlgorithmUtil.extractDigesetAlgFromSigAlg(sigAlgId); } catch (NoSuchAlgorithmException ex) { throw new XiSecurityException(ex.getMessage(), ex); } RSASSAPSSparams param = RSASSAPSSparams.getInstance(sigAlgId.getParameters()); AlgorithmIdentifier mfgDigAlgId = AlgorithmIdentifier.getInstance( param.getMaskGenAlgorithm().getParameters()); Digest dig = getDigest(digAlgId); Digest mfgDig = getDigest(mfgDigAlgId); int saltSize = param.getSaltLength().intValue(); int trailerField = param.getTrailerField().intValue(); AsymmetricBlockCipher tmpCipher = (cipher == null) ? new RSABlindedEngine() : cipher; return new PSSSigner(tmpCipher, dig, mfgDig, saltSize, getTrailer(trailerField)); }
public HmacContentSigner(HashAlgo hashAlgo, AlgorithmIdentifier algorithmIdentifier, SecretKey signingKey) throws XiSecurityException { this.algorithmIdentifier = Args.notNull(algorithmIdentifier, "algorithmIdentifier"); Args.notNull(signingKey, "signingKey"); try { this.encodedAlgorithmIdentifier = algorithmIdentifier.getEncoded(); } catch (IOException ex) { throw new XiSecurityException("could not encode AlgorithmIdentifier", ex); } if (hashAlgo == null) { hashAlgo = AlgorithmUtil.extractHashAlgoFromMacAlg(algorithmIdentifier); } this.hmac = new HMac(hashAlgo.createDigest()); byte[] keyBytes = signingKey.getEncoded(); this.hmac.init(new KeyParameter(keyBytes, 0, keyBytes.length)); this.outLen = hmac.getMacSize(); this.outputStream = new HmacOutputStream(); }
private static byte[] decrypt(EncryptedValue ev, char[] password) throws XiSecurityException { AlgorithmIdentifier symmAlg = ev.getSymmAlg(); if (!PKCSObjectIdentifiers.id_PBES2.equals(symmAlg.getAlgorithm())) { throw new XiSecurityException("unsupported symmAlg " + symmAlg.getAlgorithm().getId()); } PBES2Parameters alg = PBES2Parameters.getInstance(symmAlg.getParameters()); PBKDF2Params func = PBKDF2Params.getInstance(alg.getKeyDerivationFunc().getParameters()); AlgorithmIdentifier encScheme = AlgorithmIdentifier.getInstance(alg.getEncryptionScheme()); try { SecretKeyFactory keyFact = SecretKeyFactory.getInstance(alg.getKeyDerivationFunc().getAlgorithm().getId()); SecretKey key; int iterations = func.getIterationCount().intValue(); key = keyFact.generateSecret(new PBKDF2KeySpec(password, func.getSalt(), iterations, KEYSIZE_PROVIDER.getKeySize(encScheme), func.getPrf())); key = new SecretKeySpec(key.getEncoded(), "AES"); String cipherAlgOid = alg.getEncryptionScheme().getAlgorithm().getId(); Cipher cipher = Cipher.getInstance(cipherAlgOid); ASN1Encodable encParams = alg.getEncryptionScheme().getParameters(); GCMParameters gcmParameters = GCMParameters.getInstance(encParams); GCMParameterSpec gcmParamSpec = new GCMParameterSpec(gcmParameters.getIcvLen() * 8, gcmParameters.getNonce()); cipher.init(Cipher.DECRYPT_MODE, key, gcmParamSpec); return cipher.doFinal(ev.getEncValue().getOctets()); } catch (IllegalBlockSizeException | BadPaddingException | NoSuchAlgorithmException | InvalidKeySpecException | NoSuchPaddingException | InvalidKeyException | InvalidAlgorithmParameterException ex) { throw new XiSecurityException("Error while decrypting the EncryptedValue", ex); } }