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

📄 guitest.java

📁 java 实现的签名方案
💻 JAVA
📖 第 1 页 / 共 2 页
字号:
					//Create a new sign task.					task = new DigestSignTask(getCryptokiLib(),							getSignerLabel(), log);					//Create a timer.					//NOTE: we define an action listener on the fly while					// passing					// an instance of it to the Timer constructor.					timer = new Timer(ONE_SECOND,							new java.awt.event.ActionListener() {								public void actionPerformed(										java.awt.event.ActionEvent evt) {									setStatus(task.getCurrent(), task											.getMessage());									if (task.done()) {										timer.stop();										progressBar.setValue(progressBar												.getMinimum());										if (task.getCurrent() == DigestSignTask.SIGN_DONE) {											Toolkit.getDefaultToolkit().beep();											setEncryptedDigest(task													.getEncryptedDigest());											setCertificate(task													.getCertificate());											try {												closeSignature();											} catch (CertificateException e) {												log														.println("Error closing signature process:\n"																+ e);											}										}										enableControls(true);									}								}//end of actionPerformed definition							});//end of ActionListener definition and Timer					// constructor call.					//disable text area modification.					this.f.setEnabled(false);					this.dataArea.setEditable(false);					openSignature(CMSSignedDataGenerator.DIGEST_SHA1,							CMSSignedDataGenerator.ENCRYPTION_RSA, this.makeDigestOnToken);					//this launches the signing thread (see task above)					sign();				}//end of if( detect...			}			if (e.getSource() == f) {				log.println("Loading file...");				String filePath = System.getProperty("user.home")						+ System.getProperty("file.separator");				JFileChooser fc = new JFileChooser(new File(filePath));				//Show dialog; this method does not return until dialog is				// closed				if (fc.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) {					// Get the selected file					File file = fc.getSelectedFile();					String typeDesc = fc.getTypeDescription(file);					try {						if (isTextFile(file)) {							FileReader fr = new FileReader(file									.getAbsolutePath());							this.dataArea.read(fr, null);							fr.close();							log.println("File: '" + file.getAbsolutePath()									+ "' loaded.");							this.setFileToSign(file);						} else {							JOptionPane.showMessageDialog(null,									"This does not appears as a text file!",									"Error loading file.",									JOptionPane.ERROR_MESSAGE);							log									.println("This does not appears as a text file!");						}					} catch (IOException ioe) {						System.err.println(ioe);					}				}			}			if (e.getSource() == c) {				log.println("Saving signer certificate");				String filePath = System.getProperty("user.home")						+ System.getProperty("file.separator");				JFileChooser fc = new JFileChooser(new File(filePath));				// Show dialog; this method does not return until dialog is				// closed				fc.showSaveDialog(this);				// Get the selected file				File file = fc.getSelectedFile();				FileOutputStream fos = new FileOutputStream(file);				fos.write(getCertificate());				fos.flush();				fos.close();				log.println("Signer certificate saved to: "						+ file.getAbsolutePath());			}			if (e.getSource() == s) {				log.println("Building  CMSSignedData...");				CMSSignedData cms = buildCMSSignedData();				log.println("Saving signed message");				String dirPath = System.getProperty("user.home");				if (this.getFileToSign() != null) {					dirPath = this.getFileToSign().getParent();				}				dirPath = dirPath + System.getProperty("file.separator");				JFileChooser fc = new JFileChooser(new File(dirPath));				String p7mFilePath = (this.getFileToSign() != null) ? this						.getFileToSign().getAbsolutePath()						+ ".p7m" : dirPath + "guitest.txt.p7m";				fc.setSelectedFile(new File(p7mFilePath));				// Show dialog; this method does not return until dialog is				// closed				fc.showSaveDialog(this);				// Get the selected file				File file = fc.getSelectedFile();				FileOutputStream fos = new FileOutputStream(file);				fos.write(cms.getEncoded());				fos.flush();				fos.close();				log.println("Signed message saved to: "						+ file.getAbsolutePath());			}		} catch (Exception ex) {			log.println(ex.toString());		} finally {			pwd.setText("");		}	}	/**	 * Tests if a file is a text file; this method probably works only in a	 * unicode system (fixme).	 * 	 * @param f	 * @return	 * @throws IOException	 */	private boolean isTextFile(File f) throws IOException {		//Used for its canDisplay(char) method;		Font testFont = new Font("Courier", Font.PLAIN, 10);		FileReader fr = new FileReader(f.getAbsolutePath());		int charRead = 0;		boolean isText = true;		while (((charRead = fr.read()) != -1) && isText)			isText = Character.isISOControl((char) charRead)					|| testFont.canDisplay((char) charRead);		fr.close();		return isText;	}	/**	 * Takes text from data area and digests it.	 * 	 * @throws NoSuchAlgorithmException	 * @throws UnsupportedEncodingException	 */	private void prepareDigestFromTextArea() throws NoSuchAlgorithmException,			UnsupportedEncodingException {		log.println("\nCalculating digest ...\n");		java.security.MessageDigest md5 = java.security.MessageDigest				.getInstance("MD5");		md5.update(dataArea.getText().getBytes("UTF8"));		byte[] digest = md5.digest();		log.println("digest:\n" + formatAsHexString(digest));		log.println("Done.");		setEncodedDigest(encodeFromBytes(digest));	}	/**	 * Decodes a base64 String in a normal Unicode string.	 * 	 * @param s	 * @return	 */	public String decode(String s) {		try {			byte[] bytes = decodeToBytes(s);			if (bytes != null)				return new String(bytes, "UTF8");		} catch (java.io.UnsupportedEncodingException e) {			log.println("Errore di encoding: " + e);		}		return null;	}	/**	 * Converts a base64 String in a byte array.	 * 	 * @param s	 * @return	 */	public byte[] decodeToBytes(String s) {		byte[] stringBytes = null;		try {			sun.misc.BASE64Decoder decoder = new sun.misc.BASE64Decoder();			stringBytes = decoder.decodeBuffer(s);		} catch (java.io.IOException e) {			log.println("Errore di io: " + e);		}		return stringBytes;	}	/**	 * Enables GUI controls.	 * 	 * @param enable	 *            boolean	 */	private void enableControls(boolean enable) {		pwd.setEnabled(enable);		if (isDebugMode()) {		}	}	/**	 * Encodes a String into its base64 encoding version.	 * 	 * @param s	 * @return	 */	public String encode(String s) {		try {			return encodeFromBytes(s.getBytes("UTF8"));		} catch (java.io.UnsupportedEncodingException e) {			log.println("Errore di encoding: " + e);		}		return null;	}	/**	 * Creates the base64 encoding of a byte array.	 * 	 * @param bytes	 * @return	 */	public String encodeFromBytes(byte[] bytes) {		String encString = null;		sun.misc.BASE64Encoder encoder = new sun.misc.BASE64Encoder();		encString = encoder.encode(bytes);		return encString;	}	/**	 * Returns information about this applet.	 * 	 * @return a string of information about this applet	 */	public String getAppletInfo() {		return "SignApplet\n" + "\n" + "This type was created in VisualAge.\n"				+ "";	}	/**	 * Returns the signer's certificate.	 * 	 * @return byte	 */	public byte[] getCertificate() {		return certificate;	}	/**	 * Returns the cryptoki library name.	 * 	 * @return java.lang.String	 */	private java.lang.String getCryptokiLib() {		return cryptokiLib;	}	/**	 * Returns the base64 encoding of the digest.	 * 	 * @return the base64 encoding.	 */	public String getEncodedDigest() {		return this.encodedDigest;	}	/**	 * Gets the digest encrypted with the private key of the signer.	 * 	 * @return	 */	public byte[] getEncryptedDigest() {		return encryptedDigest;	}	/**	 * Returns the label identifiyng the signer objects on the token.	 * 	 * @return	 */	private java.lang.String getSignerLabel() {		return signerLabel;	}	/**	 * Resets the progress bar status.	 * 	 * @param min	 * @param max	 */	private void initStatus(int min, int max) {		progressBar.setMinimum(min);		progressBar.setMaximum(max);		setStatus(min, "");	}	/**	 * Tests if the program is in debug mode	 * 	 * @return boolean	 */	private boolean isDebugMode() {		return debug;	}	/**	 * Sets the signer certificate	 * 	 * @param newCertificate	 */	private void setCertificate(byte[] newCertificate) {		certificate = newCertificate;	}	/**	 * Sets the cryptoki library name.	 * 	 * @param newCryptokiLib	 */	private void setCryptokiLib(java.lang.String newCryptokiLib) {		cryptokiLib = newCryptokiLib;	}	/**	 * Sets the base64 encoded digest.	 * 	 * @param data	 */	public void setEncodedDigest(String data) {		this.encodedDigest = data;	}	/**	 * Sets the private-key encrypted digest	 * 	 * @param newEncryptedDigest	 */	public void setEncryptedDigest(byte[] newEncryptedDigest) {		encryptedDigest = newEncryptedDigest;	}	/**	 * Sets the label identifiyng the signer objects on the token.	 * 	 * @param newSignerLabel	 */	private void setSignerLabel(java.lang.String newSignerLabel) {		signerLabel = newSignerLabel;	}	/**	 * Sets the current status of the program (shown in the progress bar and	 * with alerts in case of error.	 * 	 * @param code	 * @param statusString	 */	private void setStatus(int code, String statusString) {		if (code == DigestSignTask.ERROR) {			pwd.setText("");			Toolkit.getDefaultToolkit().beep();			JOptionPane.showMessageDialog(null, statusString, "Errore!",					JOptionPane.ERROR_MESSAGE);			code = 0;			statusString = "";		}		progressBar.setValue(code);		progressBar.setString(statusString);	}	/**	 * Starts a signing task in a separate thread.	 * 	 * @param digestOnToken	 *            if true, the cryptoki - card takes care of digesting; raw	 *            bytes to sign are passed to cryptoki functions.	 */	public void sign() {		if (!this.makeDigestOnToken && getEncodedDigest() == null)			setStatus(ERROR, "Digest non impostato");		else {			enableControls(false);			if (!this.makeDigestOnToken)				task.setDigest(decodeToBytes(getEncodedDigest()));			else				task.setDataStream(new ByteArrayInputStream(this.bytesToSign));			long mechanism = -1L;			if (CMSSignedDataGenerator.ENCRYPTION_RSA.equals(this.encAlg))				if (this.makeDigestOnToken) {					if (CMSSignedDataGenerator.DIGEST_MD5							.equals(this.digestAlg))						mechanism = PKCS11Constants.CKM_MD5_RSA_PKCS;					else if (CMSSignedDataGenerator.DIGEST_SHA1							.equals(digestAlg))						mechanism = PKCS11Constants.CKM_SHA1_RSA_PKCS;				} else					mechanism = PKCS11Constants.CKM_RSA_PKCS;			if (mechanism == -1L)				setStatus(ERROR, "Impossibile determinare il meccanismo!");			else {				task.setMechanism(mechanism);				task.setPassword(pwd.getPassword());				task.go();				timer.start();			}		}	}	/**	 * Converts a byte array in its exadecimal representation.	 * 	 * @param bytes	 * @return	 */	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;	}	/**	 * 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.	 * 	 * @return true if a token with corresponding candidate cryptoki was	 *         detected.	 * @throws IOException	 */	private boolean detectCardAndCriptoki() throws IOException {		CardInfo ci = null;		boolean cardPresent = false;		PCSCHelper pcsc = new PCSCHelper(true);		java.util.List cards = pcsc.findCards();		cardPresent = !cards.isEmpty();		if (!isForcingCryptoki()) {			log.println("\n\n========= DETECTING CARD ===========");			log.println("Trying to detect card via PCSC ...");			log.println("Resetting cryptoki name");			setCryptokiLib(null);			if (cardPresent) {				ci = (CardInfo) cards.get(0);				setCryptokiLib(ci.getProperty("lib"));				log.println("\n\nFor signing we will use card: '"						+ ci.getProperty("description") + "' with criptoki '"						+ ci.getProperty("lib") + "'");			} else				log.println("Sorry, no card detected!");		} else			System.out					.println("\n\nFor signing we are forcing use of cryptoki: '"							+ getCryptokiLib() + "'");		log.println("=================================");		return (getCryptokiLib() != null);	}	public File getFileToSign() {		return fileToSign;	}	public void setFileToSign(File fileToSign) {		this.fileToSign = fileToSign;	}}

⌨️ 快捷键说明

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