📄 clitest.java
字号:
* //CMSSignedDataGenerator gen = new CMSSignedDataGenerator(); * EncryptedDigestCMSSignedDataGenerator gen = new * EncryptedDigestCMSSignedDataGenerator(); * * //gen.addSigner( // origKP.getPrivate(), // origCert, // * CMSSignedDataGenerator.DIGEST_SHA1); * gen.addSigner(CMSSignedDataGenerator.DIGEST_MD5); // N.B.:Questo metodo * viene eseguito durante il processo di // generazione della firma. // * gen.addCertificatesAndCRLs(certs); * * CMSSignedData s = gen.generate(msg, true, "BC"); * * * * //Verifica firma CertStore certs = s.getCertificatesAndCRLs("Collection", * "BC"); SignerInformationStore signers = s.getSignerInfos(); Collection c = * signers.getSigners(); * * Iterator it = c.iterator(); * * while (it.hasNext()) { SignerInformation signer = (SignerInformation) * it.next(); Collection certCollection = certs.getCertificates(signer * .getSID()); * * Iterator certIt = certCollection.iterator(); X509Certificate cert = * (X509Certificate) certIt.next(); * * if (signer.verify(cert, "BC")) System.out.println("OK!"); else * System.out.println("Failure!"); } * * String filePath = "D:/bc117.txt.p7m"; System.out.println("SAVING FILE TO: " + * filePath); * * FileOutputStream fos = new FileOutputStream(filePath); * fos.write(s.getEncoded()); fos.flush(); fos.close(); } catch (Exception * ex) { System.out.println(ex); } } * * public void testSHA1WithRSAEncapsulated() { try { ArrayList certList = * new ArrayList(); CMSProcessable msg = //new * CMSProcessableByteArray("Hello World!".getBytes()); new * CMSProcessableByteArray(msgBytes); * * certList.add(origCert); certList.add(signCert); * * CertStore certs = CertStore.getInstance("Collection", new * CollectionCertStoreParameters(certList), "BC"); * * //CMSSignedDataGenerator gen = new CMSSignedDataGenerator(); * EncryptedDigestCMSSignedDataGenerator gen = new * EncryptedDigestCMSSignedDataGenerator(); * * gen.addSigner(origKP.getPrivate(), origCert, * //CMSSignedDataGenerator.DIGEST_SHA1); * CMSSignedDataGenerator.DIGEST_MD5); * * //indispensabile sesi usa CMSSignedDataGenerator invece di // * EncryptedDigestCMSSignedDataGenerator * //gen.addCertificatesAndCRLs(certs); * * CMSSignedData s = gen.generate(msg, true, "BC"); * * ByteArrayInputStream bIn = new ByteArrayInputStream(s.getEncoded()); * ASN1InputStream aIn = new ASN1InputStream(bIn); * * s = new CMSSignedData(ContentInfo.getInstance(aIn.readObject())); * * certs = s.getCertificatesAndCRLs("Collection", "BC"); * * SignerInformationStore signers = s.getSignerInfos(); Collection c = * signers.getSigners(); Iterator it = c.iterator(); * * while (it.hasNext()) { SignerInformation signer = (SignerInformation) * it.next(); Collection certCollection = certs.getCertificates(signer * .getSID()); * * Iterator certIt = certCollection.iterator(); X509Certificate cert = * (X509Certificate) certIt.next(); * * if (signer.verify(cert, "BC")) { String filePath = "D:/bc117.txt.p7m"; * System.out.println("OK - SAVING FILE TO: " + filePath); * * FileOutputStream fos = new FileOutputStream(filePath); * fos.write(s.getEncoded()); fos.flush(); fos.close(); } else * System.out.println("Failure!"); } } catch (Exception ex) { * System.out.println(ex); } } */ /* * public byte[] readCertFile(String filePath) throws java.io.IOException { * * System.out.println("reading certificate from file: " + filePath); * * FileInputStream fis = new FileInputStream(filePath); * * byte[] buffer = new byte[1024]; ByteArrayOutputStream baos = new * ByteArrayOutputStream(); int bytesRead = 0; while ((bytesRead = * fis.read(buffer, 0, buffer.length)) >= 0) { baos.write(buffer, 0, * bytesRead); } fis.close(); System.out.println("FINISHED\n"); return * baos.toByteArray(); } */ /* * public void testSCProvider() { try { ArrayList certList = new * ArrayList(); CMSProcessable msg = //new CMSProcessableByteArray("Hello * World!".getBytes()); new CMSProcessableByteArray(msgBytes); * * certList.add(origCert); certList.add(signCert); * * CertStore certs = CertStore.getInstance("Collection", new * CollectionCertStoreParameters(certList), "BC"); * * CMSSignedDataGenerator gen = new CMSSignedDataGenerator(); * //EncryptedDigestCMSSignedDataGenerator gen = new // * EncryptedDigestCMSSignedDataGenerator(); * * gen.addSigner(origKP.getPrivate(), origCert, * //CMSSignedDataGenerator.DIGEST_SHA1); * CMSSignedDataGenerator.DIGEST_MD5); * * gen.addCertificatesAndCRLs(certs); * * CMSSignedData s = gen.generate(msg, true, "SMARTCARD"); * * ByteArrayInputStream bIn = new ByteArrayInputStream(s.getEncoded()); * ASN1InputStream aIn = new ASN1InputStream(bIn); * * s = new CMSSignedData(ContentInfo.getInstance(aIn.readObject())); * * certs = s.getCertificatesAndCRLs("Collection", "BC"); * * SignerInformationStore signers = s.getSignerInfos(); Collection c = * signers.getSigners(); Iterator it = c.iterator(); * * while (it.hasNext()) { SignerInformation signer = (SignerInformation) * it.next(); Collection certCollection = certs.getCertificates(signer * .getSID()); * * Iterator certIt = certCollection.iterator(); X509Certificate cert = * (X509Certificate) certIt.next(); * * if (signer.verify(cert, "BC")) { String filePath = "D:/bc117.txt.p7m"; * System.out.println("OK - SAVING FILE TO: " + filePath); * * FileOutputStream fos = new FileOutputStream(filePath); * fos.write(s.getEncoded()); fos.flush(); fos.close(); } else * System.out.println("Failure!"); } } catch (Exception ex) { * System.out.println(ex); } } */ /** * Test (possibly multiple) digital signatures using PKCS#11 tokens. After * correct verification of all signatures, the CMS signed message is saved * on the filesystem under the users's home directory. * */ public void testExternalSignature() { try { System.out .println("=================================================="); System.out .println("========= CMS (PKCS7) Signed message test ========\n\n"); System.out.print("The test message to sign is:\t"); ByteArrayOutputStream baos = new ByteArrayOutputStream(); baos.write(this.msgBytes); System.out.println(baos.toString()); System.out.print("As exadecimal string:\t\t"); System.out.println(formatAsString(this.msgBytes, " ", WRAP_AFTER)); System.out.println(); CMSProcessable msg = new CMSProcessableByteArray(this.msgBytes); //questa versione del generatore � priva della classe interna // per // la generazione delle SignerInfo, che � stata promossa a // classe a // s�. ExternalSignatureCMSSignedDataGenerator gen = new ExternalSignatureCMSSignedDataGenerator(); //Conterr� la lista dei certificati; come minimo dovr� //contenere i certificati dei firmatari; opzionale, ma // consigliabile, //l'aggiunta dei certificati root per completare le catene di // certificazione. ArrayList certList = new ArrayList(); ExternalSignatureSignerInfoGenerator sig = null; String answer = "STARTVALUE"; String prompt = "Do you want to sign this message?\n" + baos.toString() + "\nType Y or N:"; int i = 0; BufferedReader input_; PrintWriter output_; { try { output_ = new PrintWriter(System.out, true); input_ = new BufferedReader( new InputStreamReader(System.in)); } catch (Throwable thr) { thr.printStackTrace(); output_ = new PrintWriter(System.out, true); input_ = new BufferedReader( new InputStreamReader(System.in)); } } while (!answer.equals("N")) { while (!answer.equals("N") && !answer.equals("Y")) { output_.print(prompt); output_.flush(); answer = input_.readLine().toUpperCase(); output_.flush(); } if (answer.equals("Y")) { System.out.println("========================"); System.out.println("ADDING SIGNATURE " + i); if (detectCardAndCriptoki()) { System.out.println("Starting signing process."); //System.out // .println("Applying SHA1 digest with RSA // encryption."); sig = getSignerInfoGenerator(msg, this.digestAlg, this.encAlg, this.makeDigestOnToken, //digest // on // token? certList); if (sig != null) gen.addSignerInf(sig); }//if card detected prompt = "Add another signature?\n" + "\nType Y or N:"; answer = "STARTVALUE"; } i++; } if (certList.size() != 0) { //Per passare i certificati al generatore li si incapsula // in un // CertStore. CertStore store = CertStore.getInstance("Collection", new CollectionCertStoreParameters(certList), "BC"); System.out.println("Adding certificates ... "); gen.addCertificatesAndCRLs(store); //Finalmente, si pu� creare il l'oggetto CMS. System.out.println("Generating CMSSignedData "); CMSSignedData s = gen.generate(msg, true); //Verifica System.out .println("\nStarting CMSSignedData verification ... "); //recupero dal CMS la lista dei certificati CertStore certs = s.getCertificatesAndCRLs("Collection", "BC"); //Recupero i firmatari. SignerInformationStore signers = s.getSignerInfos(); Collection c = signers.getSigners(); System.out.println(c.size() + " signers found."); Iterator it = c.iterator(); //ciclo tra tutti i firmatari i = 0; while (it.hasNext()) { SignerInformation signer = (SignerInformation) it.next(); Collection certCollection = certs.getCertificates(signer .getSID()); if (certCollection.size() == 1) { //Iterator certIt = certCollection.iterator(); //X509Certificate cert = (X509Certificate) // certIt.next(); X509Certificate cert = (X509Certificate) certCollection .toArray()[0]; System.out.println(i + ") Verifiying signature from:\n" + cert.getSubjectDN()); /* * System.out.println("Certificate follows:"); * System.out.println("===================================="); * System.out.println(cert); * System.out.println("===================================="); */ if (signer.verify(cert, "BC")) { System.out.println("SIGNATURE " + i + " OK!"); } else System.err.println("SIGNATURE " + i + " Failure!"); } else System.out .println("There is not exactly one certificate for this signer!"); i++; } //writing CMS file to user's home directory String filePath = System.getProperty("user.home") + System.getProperty("file.separator") + "ciao.txt.p7m"; System.out.println("\nSAVING FILE TO: " + filePath); FileOutputStream fos = new FileOutputStream(filePath); fos.write(s.getEncoded()); fos.flush(); fos.close(); } } catch (Exception ex) { System.err.println("EXCEPTION:\n" + ex); } } /** * Implements a single signature, returning the * {@link ExternalSignatureSignerInfoGenerator}that encapsulates all signer * informations. * * * @param msg * the content to sign * @param certList * the list which the signer certificate is to be added to. * @return the <code>ExternalSignatureSignerInfoGenerator</code> * containing all signer informations. */ ExternalSignatureSignerInfoGenerator getSignerInfoGenerator( CMSProcessable msg, String digestAlg, String encryptionAlg, boolean digestOnToken, ArrayList certList) { //Il SignerInfoGenerator � molto simile alla versione standard // SignerInf; la differenza maggiore //� la presenza del metodo generateBytesToSign() che permette di // esternalizzare la firma. //Il nuovo metodo toSignerInfo() (senza parametri) restituisce un // signerInfo che usa il digest crittato //e certificati precedentemente impostati dall'esterno. //Il digest crittato � ora una variabile del generatore, // impostabile dall'esterno. ExternalSignatureSignerInfoGenerator signerGenerator = new ExternalSignatureSignerInfoGenerator( digestAlg, encryptionAlg); try { System.out.println("Calculating bytes to sign ..."); byte[] bytesToSign = signerGenerator.getBytesToSign(
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -