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

📄 simplesignapplet.java

📁 java 实现的签名方案
💻 JAVA
📖 第 1 页 / 共 3 页
字号:
            digest();            this.attrPrintout = retrieveAuthenticatedAttributesPrintout();            displayDataToSign();            dataLoaded = true;        }                    return dataLoaded;    }    /**     * Implements the HTTP GET request that returns the message to sign.     *      * @return the message content to sign.     */    private String retrieveTextToSign() {        //StringBuffer buf = null;        String result = null;        try {            //   Create a URL for the desired page            String base = (getBaseHttpUrl()!=null)?getBaseHttpUrl():DEFAULT_BASE_HTTP_URL;            String parms = "?" + URLEncoder.encode("retrieve", "UTF-8") + "="                    + URLEncoder.encode("DATA", "UTF-8");            URL url = new URL(base + parms);            result = httpGet(url);        } catch (MalformedURLException e) {            log.println(e);        } catch (IOException e) {            log.println(e);        }        return result;    }    /**     * Implements the HTTP GET request that returns the data to digest and encrypt..     *      * @return the "authenticated attributes" bytes.     */    private byte[] retrieveBytesToSign() {        //StringBuffer buf = null;        byte[] result = null;        try {            //   Create a URL for the desired page            String base = (getBaseHttpUrl()!=null)?getBaseHttpUrl():DEFAULT_BASE_HTTP_URL;            String parms = "?"                    + URLEncoder.encode("retrieve", "UTF-8")                    + "="                    + URLEncoder.encode("ENCODED_AUTHENTICATED_ATTRIBUTES",                            "UTF-8");            URL url = new URL(base + parms);            String data = httpGet(url);            if (data != null) {                log.println("Decoding...");                String base64Bytes = data;                sun.misc.BASE64Decoder decoder = new sun.misc.BASE64Decoder();                result = decoder.decodeBuffer(base64Bytes);                log.println("Data decoded.");            }        } catch (MalformedURLException e) {            log.println(e);        } catch (IOException e) {            log.println(e);        }        return result;    }    /**     * Implements the HTTP GET request that returns the textual representation     * of the current "authenticated attributes". This is requested to the server     * because the applet is not equipped with the BouncyCastle classes required to decode     * the "authenticated attributes". The current digest is used as on the server a key to     * retrive the printout.     *      * @return the authenticated attributes textual dump.     */    private String retrieveAuthenticatedAttributesPrintout() {        //StringBuffer buf = null;        String result = null;        try {            //   Create a URL for the desired page            sun.misc.BASE64Encoder encoder = new sun.misc.BASE64Encoder();            String base64Hash = encoder.encode(getDigest());            String base = (getBaseHttpUrl()!=null)?getBaseHttpUrl():DEFAULT_BASE_HTTP_URL;            String parms = "?"                    + URLEncoder.encode("retrieve", "UTF-8")                    + "="                    + URLEncoder.encode("AUTHENTICATED_ATTRIBUTES_PRINTOUT",                            "UTF-8");            parms += "&" + URLEncoder.encode("encodedhash", "UTF-8") + "="                    + URLEncoder.encode(base64Hash, "UTF-8");            URL url = new URL(base + parms);            log.println(this.getDocumentBase().getHost());            log.println(this.getDocumentBase().getPath());            result = httpGet(url);        } catch (MalformedURLException e) {            log.println(e);        } catch (IOException e) {            log.println(e);        }        return result;    }    /**     * Generic implementation of a HTTP GET; used from the data retrieval methods.     *      * @param url the url to GET.     * @return the result of the GET method.     * @throws IOException     *      * @see #retrieveTextToSign()     * @see #retrieveBytesToSign()     * @see #retrieveAuthenticatedAttributesPrintout()     */    private String httpGet(URL url) throws IOException {        String result = null;        if ("http".equals(url.getProtocol())) {            log.println("Getting attributes printout from: " + url);            InputStream in = url.openStream();            byte[] buffer = new byte[1024];            ByteArrayOutputStream baos = new ByteArrayOutputStream();            int bytesRead = 0;            while ((bytesRead = in.read(buffer, 0, buffer.length)) >= 0) {                baos.write(buffer, 0, bytesRead);            }            in.close();            result = baos.toString();            log.println("Got data.");        }        return result;    }    /**     * Implements of the HTTP POST that sends the encrypted digest and     * the signer certificate to the server.     *      * @return an <code>int</code> result code of {@link SimpleSignApplet#POST_ERROR}     * if the POST was not completed, {@link SimpleSignApplet#POST_OK_VERIFY_ERROR} if      * the POST was ok but there was a signature verification error,      * {@link SimpleSignApplet#POST_OK_VERIFY_OK} if all was ok and the CMS message file was      * written on the server filesystem.     */    private int sendSignatureAndCertificate() {                int resultCode = POST_ERROR;        try {            log.println("POSTing certificate and signature...");            sun.misc.BASE64Encoder encoder = new sun.misc.BASE64Encoder();            String base64Certificate = encoder.encode(getCertificate());            String base64Signature = encoder.encode(getEncryptedDigest());            // Construct data            String data = URLEncoder.encode("certificate", "UTF-8") + "="                    + URLEncoder.encode(base64Certificate, "UTF-8");            data += "&" + URLEncoder.encode("signature", "UTF-8") + "="                    + URLEncoder.encode(base64Signature, "UTF-8");            // Send data            URL url = new URL((getBaseHttpUrl()!=null)?getBaseHttpUrl():DEFAULT_BASE_HTTP_URL);            URLConnection conn = url.openConnection();            conn.setDoOutput(true);            OutputStreamWriter wr = new OutputStreamWriter(conn                    .getOutputStream());            wr.write(data);            wr.flush();            // Get the response            BufferedReader rd = new BufferedReader(new InputStreamReader(conn                    .getInputStream()));            String line;            if ((line = rd.readLine()) != null) {                // Process line...                log.println("POST result: " + line);                if (line.startsWith("OK")) resultCode = POST_OK_VERIFY_OK;                else if (line.startsWith("ERROR")) resultCode = POST_OK_VERIFY_ERROR;            }            wr.close();            rd.close();        } catch (Exception e) {            log.println("Error POSTing data: " + e);        }                return resultCode;    }    /**     * Initializes the applet; the applet accepts as optional parameters the     * label of the signer on the token, and the url of the running servlet     * to use for CMS operations. Another parameter can force the cryptoki      * library to use.     *      * @see #start     * @see #stop     * @see #destroy     */    public void init() {        super.init();        //card detected when signing.        //detectCardAndCriptoki();        if (getParameter("signerlabel") != null)            setSignerLabel(getParameter("signerlabel"));                if (getParameter("dataurl") != null)                    setBaseHttpUrl(getParameter("dataurl"));        getContentPane().setLayout(new BorderLayout());        log = System.out;        log.println("Initializing PKCS11TestApplet ...");        dataArea = new JTextArea();        //dataArea.setText();        JScrollPane dataScrollPane = new JScrollPane(dataArea);        getContentPane().add(dataScrollPane, BorderLayout.CENTER);        pwd.setPreferredSize(new Dimension(50, 20));        pwd.addActionListener(this);        pwd.setEnabled(false);        loadButton = new JButton("Load Data");        loadButton.addActionListener(this);        JPanel southPanel = new JPanel();        southPanel.setLayout(new BoxLayout(southPanel, BoxLayout.Y_AXIS));        JPanel controlsPanel = new JPanel();        JPanel statusPanel = new JPanel();        statusPanel.setLayout(new BoxLayout(statusPanel, BoxLayout.X_AXIS));        controlsPanel.add(pwd);        controlsPanel.add(loadButton);        /*         * if (debug) { controlsPanel.add(enc); controlsPanel.add(dec);         *          * controlsPanel.add(vff); controlsPanel.add(v); }         */        progressBar = new JProgressBar();        progressBar.setStringPainted(true);        initStatus(RESET, SIGN_DONE);        setStatus(RESET, "Press 'Load Data' to retrieve data from server.");        statusPanel.add(progressBar);        southPanel.add(controlsPanel);        southPanel.add(statusPanel);        getContentPane().add(southPanel, BorderLayout.SOUTH);        /*         * getContentPane().add( southPanel, debug ? BorderLayout.SOUTH :         * BorderLayout.CENTER);         */        //retrive data to sign from html form.        //retriveEncodedDigestFromForm();    }    /**     * Shows on the text area of the applet the message content and     * the current authenticated attributes dump (that includes the      * timestamp that will be signed).     *      */    private void displayDataToSign() {        String contentText = "The text you are about to sign is between 'START' and 'END' lines:\n"                + "================START============\n"                + this.textToSign                + "\n================ END ============\n";        String attrText = "You are also about to sign a set informations (Authenticated Attributes),\n"                + "including UTC time taken from server. These informations are detailed below:\n\n"                + this.attrPrintout;        this.dataArea.setText(contentText + attrText);    }    /**     * Initializes the status bar, extabilishing the value range.     *      * @param min minimum value for the status bar.     * @param max maximum value for the status bar.     */    private void initStatus(int min, int max) {        progressBar.setMinimum(min);        progressBar.setMaximum(max);        setStatus(min, "");    }    /**

⌨️ 快捷键说明

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