Crear un Archivo PDF de un Byte Array?

M

Mark Dev

Bueno amigos pido ayuda nuevamente, ya probe varias rutinas, para covertir un Byte Array a un archivo PDF, que encontre en la version en ingles de este foro, ya recibo un byte array de un web service, pero me generan errores como que no tiene permisos en el manifest, alguna sugerencia......

Code:
String nom_pdf = cv.getAsString("Id") + cv.getAsString("Tipo") + cv.getAsString("Dispositivo") +cv.getAsString("Fecha");

    File mfile = new File("/sdcard/" + nom_pdf +".pdf");


    try {
        FileUtils.writeByteArrayToFile(mfile, cv.getAsByteArray("ByteToPDF") );
    } catch (IOException e) {
        e.printStackTrace();
    }

La segunda forma que lo intente:

Code:
File dir = Environment.getExternalStorageDirectory();

    String nom_pdf = cv.getAsString("Id_mov") + cv.getAsString("TipoEdoCta") + cv.getAsString("Dispositivo") +cv.getAsString("FechaCorte");


    File assist = new File("/sdcard/" + nom_pdf +".pdf");
    try {
        InputStream fis = new FileInputStream(assist);

        long length = assist.length();
        if (length > Integer.MAX_VALUE) {
            Log.e("Muy largo", "No se puede leer");
        }
        byte[] bytes = new byte[(int) length];
        int offset = 0;
        int numRead = 0;
        while (offset < bytes.length && (numRead = fis.read(bytes, offset, bytes.length - offset)) >= 0) {
            offset += numRead;
        }

        File data = new File(dir, "mydemo.pdf");
        OutputStream op = new FileOutputStream(data);
        op.write(bytes);
    } catch (IOException e) {
        e.printStackTrace();
    }

la tercera forma:

Code:
File file = new File("java.pdf");

    FileOutputStream fis = new FileOutputStream(file);

    ByteArrayOutputStream bos = new ByteArrayOutputStream();

    byte[] buf = new byte[1024];

    for (int readNum; (readNum = fis.read(buf)) != -1; ){
        bos.write(buf, 0, readNum);
    }
 

Unreplied Threads

Как дообучить и использовать модель с Hugging Face?

Нашел языковую модель на HF и хочу ее дообучить на своих данных. Как мне ее в последствии использовать?

"Last seen more than x ago" is sometimes inaccurate

  • Franck Dernoncourt
  • Main Forum
  • Replies: 0
"Last seen more than x ago" is sometimes inaccurate. Example (mirror): "Last seen more than 1 month ago", even though they posted a question 22h ago.

Разделить список словарей

Есть список, содержащий словари с ключами name, age, city. Как этот список разделить на два списка:

В одном будут записи только с уникальными city (т.е. в этом городе записан только 1 человек)

В другом только те, у которых значение city совпадает.

Пример:

Code:
Лёша, 20, Москва
Гриша, 22, Питер
Оля 21, Москва

Словарь {name: Гриша, age: 22, city: Питер} должен быть в одном списке, а Лёша и Оля в другом.

Думал создать set с городами, и вложенными циклами бегать по сету и спискам, но не получилось...

Как скрыть только 1 компонент на странице, а не всю страницу React

Скажите, пожалуйста, как исправить код, чтобы при нажатии на кнопку не скрывалась вся страница, на которой находится эта функция?

мне нужно при нажатии на кнопку скрыть ТОЛЬКО компонент <Notification /> а component1 и component2 остаются, как и страница, на котрой они находятся

Code:
// функции
     
     
 const [hidden, setHidden] = useState(false);
 if (hidden) return null;
     
     <Component1 />
     
     <Notification title="заголовок">
        <Text weight="400" className={styles.text}>
      Текст
        </Text>
        <div className={styles.buttonContainer} >
        <Button className={styles.notificationButton} onClick={() => setHidden(true)}>
          OK!
        </Button>
        </div>
      </Notification>
      
  <Component2 />

Goal of CA is to allow clients ability to determine if TLS was tampered with while "in-transit"?

  • learningtech
  • Technology
  • Replies: 0
I believe my question will be a continuation of questions such as:

What's the point of the CA?

How does a digital certificate prove authenticity?

In short, I still don't have a firm grasp on why a TLS certificate signed by a reputable and public Certificate Authority (CA) is "better" than one that is not. I feel like I am not "connecting the dots" on this topic because I'm not seeing step-by-step examples of how a hacker can take advantage of TLS certificate that's not been signed by a CA.



EDIT

Actually, I spent a few days thinking through hypothetical situations. My current understanding is the main problem a CA is trying to solve is to ensure TLS certificates are not tampered with while in-transit between server and client. Is that correct? Please correct me if I am completely missing the point on what CAs are all about.

Here's a more detailed explanation of what I understand. I'll frame my understanding in the form of Problem and Solution and communicate my ideas with step-by-step demonstrations and use of pseudo-code.

Problem​


A TLS certificate contains a public key and the Subject Alt Name (SAN) or Common Name (CN) of the entity the public key is meant to encrypt information for. The public key is susceptible to being altered while in-transit from server (eg. Apache web server) to client (eg. FireFox web browser) in the form of man-in-the-middle attacks. Undesirable ways a TLS can be altered while in-transit are:


  • an unauthorized entity can intercept transmissions between server and client and inject a fraudulent public key into the TLS certificate. If client uses fraudulent public key to encrypt information and then clients sends this encrypted information to server, the unauthorized entity can intercept transmissions and decrypt the information with the unauthorized entity's corresponding private key.


  • network connectivity issues could corrupt the TLS certificate, which could corrupt the public key and make the public key unuseable

To demonstrate this problem, I will use an example:

Assume there are 3 players for our example: AcmeCorp, FireFox web browser, and Hacker.

AcmeCorp is a legitimate company and wants to create a website https://acmecorp.com. AcmeCorp wants use a TLS certificate on their website https://acmecorp.com/. The website uses Apache Webserver. Apache Webserver needs two files to serve acmecorp.com over TLS. The two files required will be acme.cert and acme.key, which are the TLS certificate and private key respectively. The acme.cert contains a public key which can be extracted.

FireFox webbrowser is used by a real human customer. FireFox web browser visits https://acmecorp.com. FireFox receives acme.cert during TLS handshake. FireFox extracts public key from acme.cert and saves it as acme.pub. FireFox encrypts all information with acme.pub before sending it to acmecorp.com.

Hacker wants to steal information between FireFox and https://acmecorp.com. Hacker has the files hacker.cert and hacker.key, which are TLS certificate and private key respectively. The hacker.cert will have almost identical information to acme.cert, except the public key included in the hacker.cert is different from the public key acme.cert. The hacker.key can be used to decrypt information that's been encrypted by the public key in hacker.cert. Hacker wants to intercept transmissions from acmecorp.com and replace the contents of acme.cert with contents of hacker.cert.

As it stands now, it is very easy for Hacker to intercept transmissions from acmecorp.com to FireFox and replace the contents of acme.cert with the contents of hacker.cert. There is no way for FireFox to know if such modifications took place while acme.cert was in transit. If FireFox uses the public key from hacker.cert, then Hacker will be able to decrypt all of FireFox's transmissions using hacker.key.

Solution​


The goal of a Certificate Authority is to provide client applications the ability to identify whether TLS certificates were tampered with or altered while in-transit from the server to the client application.

AcmeCorp can offer FireFox a way to verify whether the contents of acme.cert was modified by having a trusted third party called a Certificate Authority create the acme.cert on behalf of AcmeCorp. The TLS certificate creation process for acmecorp.com becomes:

TLS Creation Process​

  1. AcmeCorp owns the domain acmecorp.com.
  2. AcmeCorp uses OpenSSL to create a private key and a CSR. The CSR has a public key, a SAN/CN of acmecorp.com and all the meta information to create a TLS certificate for the domain acmecorp.com.
  3. AcmeCorp gives the CSR to a CA.
  4. CA sees that the CSR is for the domain acmecorp.com.
  5. CA does DNS checks to ensure AcmeCorp does own the domain acmecorp.com. If checks fail, then abort process.
  6. CA creates a temporary file called temp-cert.pem based on the information of the CSR.
  7. CA creates a TLS certificate file and digitally signs the TLS certificate with a command like MakeTLSCert(outfile: 'acmecorp.cert', infile:'temp-cert.pem', hash:'sha256', cakey:'ca.key'). My understanding of this step is weak, but i'm guessing it is broken down into these steps: 7.1. hash the contents of temp-cert.pem with sha256 and call the result a message digest. 7.2. encrypt the message digest with CA's private key ca.key and call the result the CA digital signature. 7.3. concatenate the temp-cert.pem and the CA digital signature and call this the acmecorp.cert, which is the TLS certificate.
  8. CA gives acme.cert to AcmeCorp.

Now AcmeCorp can use acme.cert and acme.key with Apache web server to serve https://acmecorp.com over TLS.

If a Hacker tries to perform steps 1 to 8, the hacker will fail at step 5. That is, a CA will see that the hacker does not own the DNS records for acmecorp.com. Therefore, the CA will not issue a certificate that has the CA's digital signature.

Next, these are the steps that FireFox will use to identify a legitimate TLS certificate, that is, differentiate between acme.cert and hacker.cert by inspecting the contents:

TLS verification​


FireFox comes bundled with the Public Key of reputable CA. Let's say FireFox has the public key of the reputable CA used in the steps above and it has the file name ca.pub. When FireFox visits https://acmecorp.com, the following happens:

  1. FireFox receives TLS certificate.
  2. FireFox extracts public key from TLS certificate.
  3. FireFox asks if public key can be trusted. The next step and onwards are meant to answer this question.
  4. FireFox sees a CA digital signature in the TLS certificate.
  5. In step 6 of the TLS creation process, temp-cert.pem is the first half of the TLS certificate, and the digital signature is the second half. Hence: 5.1 FireFox uses the ca.pub to decrypt the digital signature which yields a message digest (note, only ca.pub can decrypt information encrypted by ca.key). We now have the message digest that made by the CA. 5.2 FireFox uses the ca.pub to sha256 hash temp-cert.pem of TLS certificate to create another message digest.
  6. FireFox compares the message digest of step 5.1 and step 5.2 to make sure they are the same. If they are not the same, then it means the TLS certificate was modified while in transit from acmecorp.com to Firefox.

Final Questions​


Did I mis-understand anything? Specifically:

  1. Did I mis-understand the main goal(s) of a Certificate Authority?
  2. Did I mis-understand how the Certificate Authority achieves its goals?
  3. Does anything I've said change between TLS1.2 vs. TLS1.3? I think everything I've said so far applies to TLS1.2 . If I were to guess how this applies to TLS1.3, it is that public keys in TLS certificates are used for generating symmetric keys in the Diffie-Hellman algorithm as opposed to being used for encrypting information. Hence, the function of CA digital signatures to allow FireFox a way to verify TLS certificates coming from the server were not tampered with still applies...because incorrect public keys means you are generating the wrong symmetric keys which a hacker can exploit. Is that correct?

Login To add answer/comment

ESLint no muestra errores en archivos .vue y está ignorando archivos de prueba en un proyecto Vue

Quiero implementar ESLint (v 9.3.0) en mi proyecto Vue, pero no está mostrando los errores (con error lens) en mis archivos .vue; además, también está arrojando errores de mis archivos de prueba ('./src/testing/**/*.test.js'). ¿Qué necesito hacer para lograr lo que quiero?

Este es mi código:

Code:
import globals from 'globals';
import pluginJs from '@eslint/js';
import pluginVue from 'eslint-plugin-vue';

export default [
  {
    languageOptions: { globals: globals.browser },
    ignores: ['./src/testing/**/*.test.js'],
    rules: { 'no-unused-vars': 'error', semi: ['warn', 'always'] },
  },
  pluginJs.configs.recommended,
  ...pluginVue.configs[('flat/essential', 'flat/recommended')],
];

Estas son mis dependencias de desarrollo:

Code:
  "devDependencies": {
    "@eslint/js": "^9.3.0",
    "@quasar/vite-plugin": "^1.7.0",
    "@vitejs/plugin-vue": "^5.0.4",
    "@vitest/coverage-v8": "^1.6.0",
    "@vitest/ui": "^1.6.0",
    "cross-env": "^7.0.3",
    "eslint": "^9.3.0",
    "eslint-config-standard": "^17.1.0",
    "eslint-plugin-import": "^2.29.1",
    "eslint-plugin-n": "^16.6.2",
    "eslint-plugin-promise": "^6.1.1",
    "eslint-plugin-vue": "^9.26.0",
    "globals": "^15.2.0",
    "husky": "^9.0.11",
    "prettier": "3.2.5",
    "sass": "^1.33.0",
    "vite": "^5.2.0",
    "vitest": "^1.6.0"
  }

Esta es la documentación que estoy usando como referencia: https://eslint.org/docs/latest/use/configure/ignore

Agradezco cualquier ayuda de antemano. ¡Déjenme saber si necesitan más asistencia o modificaciones!

How can I frame an example block?

In src blocks, I can use LaTeX packages to make them look nice. For example, LaTeX's minted package lets me put a nice frame around my code blocks. The syntax is

Code:
#+ATTR_LATEX: :options frame=single
#+begin_src python
<Your Code Here>
#+end_stc python

But the same does not work with an example block. How can the same – that is, a box around my example – be achieved in an example block? I don't mind if this uses minted or not.
Top