⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 cmsservlet.java

📁 java 实现的签名方案
💻 JAVA
📖 第 1 页 / 共 2 页
字号:
                    SignerInfoGeneratorItem s = new SignerInfoGeneratorItem(                            gen, attrPrintout);                    //save generator and printout                    this.signerInfoGeneratorTable.put(storeKey, s);                } catch (NoSuchAlgorithmException e) {                    // TODO Auto-generated catch block                    System.out.println(e);                }                out.print(base64Encode(bytesToSign));            } else if (retrieve.equals("AUTHENTICATED_ATTRIBUTES_PRINTOUT")) {                String base64Hash = (String) request                        .getParameter("encodedhash");                if (base64Hash != null) {                    sun.misc.BASE64Decoder decoder = new sun.misc.BASE64Decoder();                    byte[] hash = decoder.decodeBuffer(base64Hash);                    SignerInfoGeneratorItem s = (SignerInfoGeneratorItem) this.signerInfoGeneratorTable                            .get(formatAsString(hash, ""));                    out.print(s.getAttrPrintout());                }            } else                out.println("Error: value '" + retrieve                        + "' for required parameter 'retrive' not expected.");        } else            out.println("Error: required parameter 'retrive' not found.");        out.flush();        System.out                .println("==================== DO GET METHOD END=========================");    }    /**      * Implementation of the POST method; builds the CMS message; see {@link CMSServlet} for details.     * @see CMSServlet      */    protected void doPost(HttpServletRequest request,            HttpServletResponse response) throws ServletException, IOException {        System.out                .println("==================== DO POST METHOD START =========================");        String base64Certificate = (String) request.getParameter("certificate");        String base64Signature = (String) request.getParameter("signature");        PrintWriter out = response.getWriter();        if ((base64Certificate != null) && (base64Signature != null)) {            sun.misc.BASE64Decoder decoder = new sun.misc.BASE64Decoder();            byte[] sigBytes = decoder.decodeBuffer(base64Signature);            byte[] certBytes = decoder.decodeBuffer(base64Certificate);            String storeKey = deriveStoreKey(sigBytes, certBytes);            ExternalSignatureSignerInfoGenerator info = retriveSignerInfoGenerator(storeKey);            if (info != null) {                CMSSignedData signedData =  buildCMSSignedData(info, sigBytes, certBytes);                out.print("OK-SignedData built -");                if (signedData!=null) {                    String filePath=System.getProperty("user.home")                    + System.getProperty("file.separator")                    + storeKey+".txt.p7m";                    saveFile(signedData, filePath);                    out.print(" saved to file: '"+filePath+"'");                }else                    out.print(" file NOT saved!");                                            }        } else            out.print("ERROR-certificate or signature not available.");        out.flush();        System.out                .println("==================== DO POST METHOD END =========================");    }    /**     * DER decoding function for digest info data.     *      * @param encoding der encoded bytes     * @return the digest as byte[].     * @throws IOException if encoding is not a DigestInfo     */    private byte[] derDecode(byte[] encoding) throws IOException {        if (encoding[0] != (DERTags.CONSTRUCTED | DERTags.SEQUENCE)) {            throw new IOException("not a digest info object");        }        ByteArrayInputStream bIn = new ByteArrayInputStream(encoding);        DERInputStream dIn = new DERInputStream(bIn);        return new DigestInfo((ASN1Sequence) dIn.readObject()).getDigest();    }    /**     * Formats a byte[] as an hexadecimal String, interleaving bytes with     * a separator string.     *      * @param bytes the byte[] to format.     * @param byteSeparator the string to be used to separate bytes.     *      * @return the formatted string.     */    public String formatAsString(byte[] bytes, String byteSeparator) {        int n, x;        String w = new String();        String s = new String();        for (n = 0; n < bytes.length; n++) {            x = (int) (0x000000FF & bytes[n]);            w = Integer.toHexString(x).toUpperCase();            if (w.length() == 1)                w = "0" + w;            s = s + w + ((n + 1 == bytes.length) ? "" : byteSeparator);        } // for        return s;    }    /**     * Converts the provided <code>certBytes</code> in a <code>java.security.cert.X509Certificate</code>,     * gets from it the signer public key, and uses it to decrypt <code>sigBytes</code>.     * The decryption result is returned as a formatted exadecimal string; see {@link CMSServlet} for details.     *      * @param sigBytes signature bytes     * @param certBytes certificate bytes     * @return the decryption of sigBytes using the RSA/ECB/PKCS1PADDING Algorithm.     */    private String deriveStoreKey(byte[] sigBytes, byte[] certBytes) {        String key = null;        java.security.cert.CertificateFactory cf;        try {            cf = java.security.cert.CertificateFactory.getInstance("X.509");            java.io.ByteArrayInputStream bais1 = new java.io.ByteArrayInputStream(                    certBytes);            java.security.cert.X509Certificate javaCert = (java.security.cert.X509Certificate) cf                    .generateCertificate(bais1);            PublicKey pubKey = javaCert.getPublicKey();            try {                System.out                        .println("Deriving store key from signature and certificate.");                System.out                        .println("N.B.:This serves also as signature verification!");                Cipher c = Cipher.getInstance("RSA/ECB/PKCS1PADDING", "BC");                c.init(Cipher.DECRYPT_MODE, pubKey);                byte[] decBytes = derDecode(c.doFinal(sigBytes));                key = formatAsString(decBytes, "");            } catch (NoSuchAlgorithmException e1) {                // TODO Auto-generated catch block                e1.printStackTrace();            } catch (NoSuchPaddingException e1) {                // TODO Auto-generated catch block                e1.printStackTrace();            } catch (InvalidKeyException e2) {                // TODO Auto-generated catch block                e2.printStackTrace();            } catch (IllegalStateException e) {                // TODO Auto-generated catch block                e.printStackTrace();            } catch (IllegalBlockSizeException e) {                // TODO Auto-generated catch block                e.printStackTrace();            } catch (BadPaddingException e) {                // TODO Auto-generated catch block                e.printStackTrace();            } catch (IOException e) {                // TODO Auto-generated catch block                e.printStackTrace();            } catch (NoSuchProviderException e) {                // TODO Auto-generated catch block                e.printStackTrace();            }        } catch (CertificateException e) {            // TODO Auto-generated catch block            e.printStackTrace();        }        return key;    }    /**     * Gets the <code>ExternalSignatureSignerInfoGenerator</code> generator which originally produced the given <code>storeKey</code>.     *      * @param storeKey     * @return the {@link ExternalSignatureSignerInfoGenerator} associated with the<code>storeKey</code>     */    private ExternalSignatureSignerInfoGenerator retriveSignerInfoGenerator(            String storeKey) {        System.out.println("Retrieving signerInfoGenerator.");        System.out.println("Retrieving signerInfoGenerator using key: "                + storeKey);        ExternalSignatureSignerInfoGenerator info = ((SignerInfoGeneratorItem) this.signerInfoGeneratorTable                .get(storeKey)).getSig();        if (info != null)            System.out.println("Generator found. Signature is verified.");        else            System.out                    .println("Generator not found! Signature is NOT verified!");        //remove infos from store        this.signerInfoGeneratorTable.remove(storeKey);        return info;    }    /**     * Builds the CMS signed data message.     *      * @param infoGen the {@link ExternalSignatureSignerInfoGenerator} wrapping signer informations     * @param sigBytes the digest encrypted with signer private key.     * @param certBytes the signer certificate.     * @return the {@link CMSSignedData} message.     */    private CMSSignedData buildCMSSignedData(            ExternalSignatureSignerInfoGenerator infoGen, byte[] sigBytes,            byte[] certBytes) {        CMSSignedData result = null;        System.out.println("building CMSSignedData.");        CMSProcessable msg = new CMSProcessableByteArray(DATA.getBytes());        //questa versione del generatore 

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -