📄 simplesignapplet.java
字号:
* Manages status messages displayed on the status bar. And error messages * shown on a MessageBox. * * @param code * @param statusString */ private void setStatus(int code, String statusString) { if (code == ERROR) { pwd.setText(""); Toolkit.getDefaultToolkit().beep(); JOptionPane.showMessageDialog(null, statusString, "Error!", JOptionPane.ERROR_MESSAGE); code = 0; statusString = ""; } progressBar.setValue(code); progressBar.setString(statusString); } /** * This triggers the PCSC wrapper stuff; a {@link PCSCHelper} class * is used to detect reader and token presence, trying also to provide a * candidate PKCS#11 cryptoki for it; detection is bypassed if an * applet parameter forcing cryptoki selection is provided. * * @return true if a token with corresponding candidate cryptoki * was detected. * @throws IOException */ private boolean detectCardAndCriptoki() throws IOException { CardInfo ci = null; boolean cardPresent = false; log.println("\n\n========= DETECTING CARD ==========="); log.println("Resetting cryptoki name"); setCryptokiLib(null); if (getParameter("cryptokilib") != null){ log.println("Getting cryptoki name from Applet parameter 'cryptokilib': "+getParameter("cryptokilib")); setCryptokiLib(getParameter("cryptokilib")); } else { log.println("Trying to detect card via PCSC ..."); // JNIUtils jni = new JNIUtils(); // jni.loadLibrary("OCFPCSC1"); // jni.loadLibrary("pkcs11wrapper"); PCSCHelper pcsc = new PCSCHelper(true); List cards = pcsc.findCards(); cardPresent = !cards.isEmpty(); if (cardPresent) { ci = (CardInfo) cards.get(0); log.println("\n\nFor signing we will use card: '" + ci.getProperty("description") + "' with criptoki '" + ci.getProperty("lib") + "'"); setCryptokiLib(ci.getProperty("lib")); } else log.println("Sorry, no card detected!"); } log.println("================================="); return ((ci != null) || (getCryptokiLib() != null)); } /** * Inserire qui la descrizione del metodo. Data di creazione: (10.05.01 * 14.28.07) * * @param newCertificate * byte */ private void setCertificate(byte[] newCertificate) { certificate = newCertificate; } /** * Sets the native PKCS#11 implementation to use. * * @param newCryptokiLib * java.lang.String name of the native library */ private void setCryptokiLib(java.lang.String newCryptokiLib) { cryptokiLib = newCryptokiLib; log.println("Using cryptoki:\t" + getCryptokiLib()); } /** * Sets the digest. * * @param newDigest * byte[] containing the digest value to set. */ public void setDigest(byte[] newDigest) { digest = newDigest; } /** * Sets the encrypted digest. * * @param newEncryptedDigest * byte[] containing the encrypted digest value to set.. */ public void setEncryptedDigest(byte[] newEncryptedDigest) { encryptedDigest = newEncryptedDigest; } /** * The label to use to retrieve signer - related objects * on the token. * * @param newSignerLabel * java.lang.String the signer identifier on the token. */ private void setSignerLabel(java.lang.String newSignerLabel) { signerLabel = newSignerLabel; log.println("Using signer:\t" + getSignerLabel() + "\n"); } /** * Calculates the MD5 digest of {@link #bytesToSign} ()authenticated attributes. */ public void digest() { try { log.println("\nGenerating digest ...\n"); java.security.MessageDigest md5 = java.security.MessageDigest .getInstance("MD5"); md5.update(this.bytesToSign); setDigest(md5.digest()); log.println("data:\n" + formatAsHexString(this.bytesToSign)); log.println("digest:\n" + formatAsHexString(digest)); log.println("Done."); } catch (Exception ex) { log.println(ex.toString()); } } /** * Triggers the digest encryption on the token, using services * provided by {@link PKCS11Signer} class. * Different criteria can be used to find relevant objects on the key: the default * implementation here tries to act in order to build an italian legal-value document. * A Certificate carrying an KeyUsage extension of non-repudiation marked critical is * searched; if found the corresponding private key is used to sign. A real-world application * should consent the user the certificate for signing. * * @throws CertificateException */ public void sign() throws CertificateException { if (getDigest() == null) log.println("ERRORE, Digest non impostato"); else { PKCS11Signer helper = null; String signerLabel = getSignerLabel(); try { helper = new PKCS11Signer(getCryptokiLib(),PKCS11Constants.CKM_RSA_PKCS, log); helper.openSession(pwd.getPassword()); long privateKeyHandle = -1L; long certHandle = -1; byte[] encDigestBytes = null; byte[] certBytes = null; switch (OBJECT_SEARCH_CRITERION) { case SEARCH_BY_PRIVATE_KEY: log.println("Searching objects from signature key ..."); if (signerLabel != null) //using labels for searching objects. privateKeyHandle = helper .findSignatureKeyFromLabel(signerLabel); else //Using first private key found privateKeyHandle = helper.findSignatureKey(); if (privateKeyHandle > 0) { encDigestBytes = helper.signDataSinglePart( privateKeyHandle, getDigest()); certHandle = helper .findCertificateFromSignatureKeyHandle(privateKeyHandle); certBytes = helper.getDEREncodedCertificate(certHandle); } else log.println("\nNo private key found on token!"); break; case SEARCH_BY_CERTIFICATE_KEY_USAGE: log .println("Searching objects from certificate key usage ..."); certHandle = helper .findCertificateWithNonRepudiationCritical(); if (certHandle > 0) { privateKeyHandle = helper .findSignatureKeyFromCertificateHandle(certHandle); if (privateKeyHandle > 0) encDigestBytes = helper.signDataSinglePart( privateKeyHandle, getDigest()); else log .println("\nNo private key corrisponding to certificate found on token!"); certBytes = helper.getDEREncodedCertificate(certHandle); } else log .println("\nNo certificate with required extension found on token!. "); break; default: log.println("Object search criterion not found."); break; } log.println("\nEncrypted digest:\n" + formatAsHexString(encDigestBytes)); log.println("\nDER encoded Certificate:\n" + formatAsHexString(certBytes)); setEncryptedDigest(encDigestBytes); setCertificate(certBytes); } catch (TokenException e) { log.println("sign() Error: " + e); //log.println(PKCS11Helper.decodeError(e.getCode())); //log.println(PKCS11Helper.decodeError(e.getCode())); } catch (IOException ioe) { log.println(ioe); } catch (UnsatisfiedLinkError ule) { log.println(ule); } finally { if (helper != null) { try { helper.closeSession(); log.println("Sign session Closed."); } catch (PKCS11Exception e2) { log.println("Error closing session: " + e2); } try { helper.libFinalize(); log.println("Lib finalized."); } catch (Throwable e1) { // TODO Auto-generated catch block log.println("Error finalizing criptoki: " + e1); } } helper = null; System.gc(); } } } /** * Called to start the applet. You never need to call this method directly, * it is called when the applet's document is visited. * * @see #init * @see #stop * @see #destroy */ public void start() { super.start(); log.println("Starting applet ..."); // insert any code to be run when the applet starts here } /** * Called to stop the applet. It is called when the applet's document is no * longer on the screen. It is guaranteed to be called before destroy() is * called. You never need to call this method directly. * * @see #init * @see #start * @see #destroy */ public void stop() { super.stop(); log.println("stopping..."); // insert any code to be run when the applet is stopped here } String formatAsHexString(byte[] bytes) { 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) % 16 == 0 ? "\n" : " "); } return s; } public java.lang.String getBaseHttpUrl() { return baseHttpUrl; } public void setBaseHttpUrl(java.lang.String baseHttpUrl) { this.baseHttpUrl = baseHttpUrl; }}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -