protected void processCertificateVerify( ServerHandshakeState state, byte[] body, TlsHandshakeHash prepareFinishHash) throws IOException { ByteArrayInputStream buf = new ByteArrayInputStream(body); DigitallySigned clientCertificateVerify = DigitallySigned.parse(state.serverContext, buf); TlsProtocol.assertEmpty(buf); // Verify the CertificateVerify message contains a correct signature. try { // TODO For TLS 1.2, this needs to be the hash specified in the DigitallySigned byte[] certificateVerifyHash = TlsProtocol.getCurrentPRFHash(state.serverContext, prepareFinishHash, null); org.bouncycastle.asn1.x509.Certificate x509Cert = state.clientCertificate.getCertificateAt(0); SubjectPublicKeyInfo keyInfo = x509Cert.getSubjectPublicKeyInfo(); AsymmetricKeyParameter publicKey = PublicKeyFactory.createKey(keyInfo); TlsSigner tlsSigner = TlsUtils.createTlsSigner(state.clientCertificateType); tlsSigner.init(state.serverContext); tlsSigner.verifyRawSignature( clientCertificateVerify.getAlgorithm(), clientCertificateVerify.getSignature(), publicKey, certificateVerifyHash); } catch (Exception e) { throw new TlsFatalAlert(AlertDescription.decrypt_error); } }
public CryptEngineImpl(Context ctx) throws Exception { // Получаем действующее хранилище IKeyStorage storage = KeyStorageFactory.getKeyStorage(ctx); Log.v("TFORWARD.CryptEngineImpl", "Decoding public key..."); byte[] publicKey = Base64.decode(storage.getKey(IKeyStorage.PUBLIC_KEY_TYPE), Base64.DEFAULT); Log.v("TFORWARD.CryptEngineImpl", "Decoding ASN1 Structure"); ASN1InputStream asnStream = new ASN1InputStream(publicKey); ASN1Sequence sequence = null; try { Log.v("TFORWARD.CryptEngineImpl", "Reading ASN1 Sequence"); sequence = (ASN1Sequence) asnStream.readObject(); } finally { asnStream.close(); } Log.v("TFORWARD.CryptEngineImpl", "Creating certificate. " + sequence.size()); Certificate certificate = Certificate.getInstance(sequence); SubjectPublicKeyInfo publicKeyInfo = certificate.getSubjectPublicKeyInfo(); RSAPublicKey publicKeyStructure = RSAPublicKey.getInstance(publicKeyInfo.parsePublicKey()); BigInteger mod = publicKeyStructure.getModulus(); BigInteger pubExp = publicKeyStructure.getPublicExponent(); publicRsaKey = new RSAKeyParameters(false, mod, pubExp); // ------------------------ PRIVATE KEY -------------------------------- byte[] privateKeyData = Base64.decode(storage.getKey(IKeyStorage.SECRET_KEY_TYPE), Base64.DEFAULT); asnStream = new ASN1InputStream(privateKeyData); ASN1Sequence asnSequence = null; try { asnSequence = (ASN1Sequence) asnStream.readObject(); } finally { asnStream.close(); } RSAPrivateKey privateKey = RSAPrivateKey.getInstance(asnSequence); privateRsaKey = new RSAPrivateCrtKeyParameters( privateKey.getModulus(), privateKey.getPublicExponent(), privateKey.getPrivateExponent(), privateKey.getPrime1(), privateKey.getPrime2(), privateKey.getExponent1(), privateKey.getExponent2(), privateKey.getCoefficient()); RSAEngine engine = new RSAEngine(); digest = new MD5Digest(); cipher = new PKCS1Encoding(engine); }
@Override protected Object _doExecute() throws Exception { P10RequestGenerator p10Gen = new P10RequestGenerator(); hashAlgo = hashAlgo.trim().toUpperCase(); if (hashAlgo.indexOf('-') != -1) { hashAlgo = hashAlgo.replaceAll("-", ""); } if (needExtensionTypes == null) { needExtensionTypes = new LinkedList<>(); } // SubjectAltNames List<Extension> extensions = new LinkedList<>(); if (isNotEmpty(subjectAltNames)) { extensions.add(P10RequestGenerator.createExtensionSubjectAltName(subjectAltNames, false)); needExtensionTypes.add(Extension.subjectAlternativeName.getId()); } // SubjectInfoAccess if (isNotEmpty(subjectInfoAccesses)) { extensions.add( P10RequestGenerator.createExtensionSubjectInfoAccess(subjectInfoAccesses, false)); needExtensionTypes.add(Extension.subjectInfoAccess.getId()); } // Keyusage if (isNotEmpty(keyusages)) { Set<KeyUsage> usages = new HashSet<>(); for (String usage : keyusages) { usages.add(KeyUsage.getKeyUsage(usage)); } org.bouncycastle.asn1.x509.KeyUsage extValue = X509Util.createKeyUsage(usages); ASN1ObjectIdentifier extType = Extension.keyUsage; extensions.add(new Extension(extType, false, extValue.getEncoded())); needExtensionTypes.add(extType.getId()); } // ExtendedKeyusage if (isNotEmpty(extkeyusages)) { Set<ASN1ObjectIdentifier> oids = new HashSet<>(SecurityUtil.textToASN1ObjectIdentifers(extkeyusages)); ExtendedKeyUsage extValue = X509Util.createExtendedUsage(oids); ASN1ObjectIdentifier extType = Extension.extendedKeyUsage; extensions.add(new Extension(extType, false, extValue.getEncoded())); needExtensionTypes.add(extType.getId()); } // QcEuLimitValue if (isNotEmpty(qcEuLimits)) { ASN1EncodableVector v = new ASN1EncodableVector(); for (String m : qcEuLimits) { StringTokenizer st = new StringTokenizer(m, ":"); try { String currencyS = st.nextToken(); String amountS = st.nextToken(); String exponentS = st.nextToken(); Iso4217CurrencyCode currency; try { int intValue = Integer.parseInt(currencyS); currency = new Iso4217CurrencyCode(intValue); } catch (NumberFormatException e) { currency = new Iso4217CurrencyCode(currencyS); } int amount = Integer.parseInt(amountS); int exponent = Integer.parseInt(exponentS); MonetaryValue monterayValue = new MonetaryValue(currency, amount, exponent); QCStatement statment = new QCStatement(ObjectIdentifiers.id_etsi_qcs_QcLimitValue, monterayValue); v.add(statment); } catch (Exception e) { throw new Exception("invalid qc-eu-limit '" + m + "'"); } } ASN1ObjectIdentifier extType = Extension.qCStatements; ASN1Sequence extValue = new DERSequence(v); extensions.add(new Extension(extType, false, extValue.getEncoded())); needExtensionTypes.add(extType.getId()); } // biometricInfo if (biometricType != null && biometricHashAlgo != null && biometricFile != null) { TypeOfBiometricData _biometricType; if (StringUtil.isNumber(biometricType)) { _biometricType = new TypeOfBiometricData(Integer.parseInt(biometricType)); } else { _biometricType = new TypeOfBiometricData(new ASN1ObjectIdentifier(biometricType)); } ASN1ObjectIdentifier _biometricHashAlgo = AlgorithmUtil.getHashAlg(biometricHashAlgo); byte[] biometricBytes = IoUtil.read(biometricFile); MessageDigest md = MessageDigest.getInstance(_biometricHashAlgo.getId()); md.reset(); byte[] _biometricDataHash = md.digest(biometricBytes); DERIA5String _sourceDataUri = null; if (biometricUri != null) { _sourceDataUri = new DERIA5String(biometricUri); } BiometricData biometricData = new BiometricData( _biometricType, new AlgorithmIdentifier(_biometricHashAlgo), new DEROctetString(_biometricDataHash), _sourceDataUri); ASN1EncodableVector v = new ASN1EncodableVector(); v.add(biometricData); ASN1ObjectIdentifier extType = Extension.biometricInfo; ASN1Sequence extValue = new DERSequence(v); extensions.add(new Extension(extType, false, extValue.getEncoded())); needExtensionTypes.add(extType.getId()); } else if (biometricType == null && biometricHashAlgo == null && biometricFile == null) { // Do nothing } else { throw new Exception( "either all of biometric triples (type, hash algo, file)" + " must be set or none of them should be set"); } if (isNotEmpty(needExtensionTypes) || isNotEmpty(wantExtensionTypes)) { ExtensionExistence ee = new ExtensionExistence( SecurityUtil.textToASN1ObjectIdentifers(needExtensionTypes), SecurityUtil.textToASN1ObjectIdentifers(wantExtensionTypes)); extensions.add( new Extension( ObjectIdentifiers.id_xipki_ext_cmpRequestExtensions, false, ee.toASN1Primitive().getEncoded())); } ConcurrentContentSigner identifiedSigner = getSigner(hashAlgo, new SignatureAlgoControl(rsaMgf1, dsaPlain)); Certificate cert = Certificate.getInstance(identifiedSigner.getCertificate().getEncoded()); X500Name subjectDN; if (subject != null) { subjectDN = getSubject(subject); } else { subjectDN = cert.getSubject(); } SubjectPublicKeyInfo subjectPublicKeyInfo = cert.getSubjectPublicKeyInfo(); ContentSigner signer = identifiedSigner.borrowContentSigner(); PKCS10CertificationRequest p10Req; try { p10Req = p10Gen.generateRequest(signer, subjectPublicKeyInfo, subjectDN, extensions); } finally { identifiedSigner.returnContentSigner(signer); } File file = new File(outputFilename); saveVerbose("saved PKCS#10 request to file", file, p10Req.getEncoded()); return null; }
private void import_issuer(final Issuers issuers) throws DataAccessException, CertificateException, IOException { System.out.println("importing table ISSUER"); PreparedStatement ps = prepareStatement(SQL_ADD_ISSUER); try { for (IssuerType issuer : issuers.getIssuer()) { try { String certFilename = issuer.getCertFile(); String b64Cert = new String(IoUtil.read(new File(baseDir, certFilename))); byte[] encodedCert = Base64.decode(b64Cert); Certificate c; byte[] encodedName; try { c = Certificate.getInstance(encodedCert); encodedName = c.getSubject().getEncoded("DER"); } catch (Exception e) { LOG.error("could not parse certificate of issuer {}", issuer.getId()); LOG.debug("could not parse certificate of issuer " + issuer.getId(), e); if (e instanceof CertificateException) { throw (CertificateException) e; } else { throw new CertificateException(e.getMessage(), e); } } byte[] encodedKey = c.getSubjectPublicKeyInfo().getPublicKeyData().getBytes(); int idx = 1; ps.setInt(idx++, issuer.getId()); ps.setString(idx++, X509Util.cutX500Name(c.getSubject(), maxX500nameLen)); ps.setLong(idx++, c.getTBSCertificate().getStartDate().getDate().getTime() / 1000); ps.setLong(idx++, c.getTBSCertificate().getEndDate().getDate().getTime() / 1000); ps.setString(idx++, sha1(encodedName)); ps.setString(idx++, sha1(encodedKey)); ps.setString(idx++, sha224(encodedName)); ps.setString(idx++, sha224(encodedKey)); ps.setString(idx++, sha256(encodedName)); ps.setString(idx++, sha256(encodedKey)); ps.setString(idx++, sha384(encodedName)); ps.setString(idx++, sha384(encodedKey)); ps.setString(idx++, sha512(encodedName)); ps.setString(idx++, sha512(encodedKey)); ps.setString(idx++, sha1(encodedCert)); ps.setString(idx++, b64Cert); setBoolean(ps, idx++, issuer.isRevoked()); setInt(ps, idx++, issuer.getRevReason()); setLong(ps, idx++, issuer.getRevTime()); setLong(ps, idx++, issuer.getRevInvTime()); ps.execute(); } catch (SQLException e) { System.err.println("error while importing issuer with id=" + issuer.getId()); throw translate(SQL_ADD_ISSUER, e); } catch (CertificateException e) { System.err.println("error while importing issuer with id=" + issuer.getId()); throw e; } } } finally { releaseResources(ps, null); } System.out.println(" imported table ISSUER"); } // method import_issuer