📄 clitest.java
字号:
PKCSObjectIdentifiers.data, msg, "BC"); byte[] rawDigest = null; byte[] dInfoBytes = null; byte[] paddedBytes = null; if (!digestOnToken) { rawDigest = applyDigest(digestAlg, bytesToSign); System.out.println("Raw digest bytes:\n" + formatAsString(rawDigest, " ", WRAP_AFTER)); System.out.println("Encapsulating in a DigestInfo..."); dInfoBytes = encapsulateInDigestInfo(digestAlg, rawDigest); System.out.println("DigestInfo bytes:\n" + formatAsString(dInfoBytes, " ", WRAP_AFTER)); System.out.println("Adding Pkcs1 padding..."); paddedBytes = applyPkcs1Padding(128, dInfoBytes); System.out.println("Padded DigestInfo bytes:\n" + formatAsString(paddedBytes, " ", WRAP_AFTER)); } byte[] signedBytes = null; byte[] certBytes = null; System.out .println("============ Encrypting with pkcs11 token ============"); long mechanism = -1L; if (CMSSignedDataGenerator.ENCRYPTION_RSA.equals(encryptionAlg)) if (digestOnToken) { if (CMSSignedDataGenerator.DIGEST_MD5.equals(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) { PKCS11Signer signAgent = new PKCS11Signer(getCryptokiLib(), System.out); System.out .println("Finding a token supporting required mechanism and " + "containing a suitable" + "certificate..."); long t = signAgent.findSuitableToken(mechanism); // if suitable token found if (t != -1L) { signAgent.setMechanism(mechanism); signAgent.setTokenHandle(t); signAgent.openSession(readPassword()); /* * sign using the first key found on token * * long privateKeyHandle = signAgent.findSignatureKey(); * * if(privateKeyHandle > 0){ signedBytes = * signAgent.signDataSinglePart(privateKeyHandle, digest); * long certHandle = * signAgent.findCertificateFromSignatureKeyHandle(privateKeyHandle); * certBytes = * signAgent.getDEREncodedCertificate(certHandle); * * }else System.out.println("\nNo private key found on * token!"); * */ // trying a legal value signature finding suitable objects // on // token long certHandle = signAgent .findCertificateWithNonRepudiationCritical(); long privateKeyHandle = signAgent .findSignatureKeyFromCertificateHandle(certHandle); if (privateKeyHandle > 0) { if (!digestOnToken) { //Here we could provide padded bytes or DigestInfo // bytes; //but with padded bytes and Infocamere CNS //signDataSinglePart fails! (CKR_FUNCTION_FAILED). signedBytes = signAgent.signDataSinglePart( privateKeyHandle, dInfoBytes); } else /* * signedBytes = signAgent.signDataMultiplePart( * privateKeyHandle, new ByteArrayInputStream( * bytesToSign)); */ signedBytes = signAgent.signDataSinglePart( privateKeyHandle, bytesToSign); certBytes = signAgent .getDEREncodedCertificate(certHandle); } else System.out .println("\nNo suitable private key and certificate on token!"); signAgent.closeSession(); System.out.println("Sign session Closed."); signAgent.libFinalize(); System.out.println("Criptoki library finalized."); }//suitable token found } else System.out.println("Mechanism currently not supported"); if ((certBytes != null) && (signedBytes != null)) { System.out.println("======== Encryption completed ========="); System.out.println("\nBytes:\n" + formatAsString(bytesToSign, " ", WRAP_AFTER)); if (dInfoBytes != null) System.out.println("DigestInfo bytes:\n" + formatAsString(dInfoBytes, " ", WRAP_AFTER)); System.out.println("Encryption result:\n" + formatAsString(signedBytes, " ", WRAP_AFTER) + "\n"); //get Certificate java.security.cert.CertificateFactory cf = java.security.cert.CertificateFactory .getInstance("X.509"); java.io.ByteArrayInputStream bais = new java.io.ByteArrayInputStream( certBytes); java.security.cert.X509Certificate javaCert = (java.security.cert.X509Certificate) cf .generateCertificate(bais); // Decription PublicKey pubKey = javaCert.getPublicKey(); try { System.out.println("Decrypting..."); Cipher c = Cipher.getInstance("RSA/ECB/PKCS1PADDING", "BC"); c.init(Cipher.DECRYPT_MODE, pubKey); byte[] decBytes = c.doFinal(signedBytes); System.out .println("Decrypted bytes (should match DigestInfo bytes):\n" + formatAsString(decBytes, " ", WRAP_AFTER)); } 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 (NoSuchProviderException e) { // TODO Auto-generated catch block e.printStackTrace(); } signerGenerator.setCertificate(javaCert); signerGenerator.setSignedBytes(signedBytes); certList.add(javaCert); } else signerGenerator = null; } catch (Exception e) { System.out.println(e); } catch (Throwable e) { System.out.println(e); } return signerGenerator; } /** * 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 wrapAfter) { int n, x; String w = new String(); String s = new String(); String separator = null; for (n = 0; n < bytes.length; n++) { x = (int) (0x000000FF & bytes[n]); w = Integer.toHexString(x).toUpperCase(); if (w.length() == 1) w = "0" + w; if ((n % wrapAfter) == (wrapAfter - 1)) separator = "\n"; else separator = byteSeparator; s = s + w + ((n + 1 == bytes.length) ? "" : separator); } // for return s; } /** * Uses the {@link PasswordMasker}class to securely read characters from * the console; it's a pity that java language does not includes this in its * standard set of features. * * @return the characters read. * @throws IOException * @throws InterruptedException */ char[] readPassword() throws IOException, InterruptedException { System.out.println("Getting password ...\n"); char[] password = null; System.out .println("N.B.: If you are not running the example from the console, password hiding could not work well;"); //N.B:: //Sotto Eclipse, con JLine la password viene comunque mostrata, //mentre la soluzione pure java non funziona correttamente. //implementazione pure java PrintWriter output_ = null; BufferedReader input_ = null; try { //output_ = new PrintWriter(new // FileWriter("SignAndVerify_output.txt"), true); 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)); } String answer = "STARTVALUE"; while (answer != null && !answer.equals("") && !answer.equals("N") && !answer.equals("Y")) { output_.println("Do you want to enable password hiding? [Y]"); output_ .println("IF YOU ANSWER 'N' PASSWORD WILL BE VISIBLE WHILE YOU TYPE IT!!!!"); output_.flush(); answer = input_.readLine().toUpperCase(); if (answer == null || "".equals(answer)) answer = "Y"; output_.flush(); } if (answer.equals("N")) { output_.print("Enter user-PIN (VISIBLE) and press [return key]: "); output_.flush(); password = input_.readLine().toCharArray(); } else { //Versione sicura, funziona male in Eclipse password = PasswordMasker .readConsoleSecure("Enter user-PIN (hidden) and press [return key]: "); } // implementazione JLine, NON pure java! // System.out // .println("This is an alternative implementation for password hiding, // using JLine project and JNI.\n" + // "See source code.\n"); // // // ConsoleReader creader = new ConsoleReader(); // // String prompt = "Enter user-PIN and press [return key]: "; // password = creader.readLine(prompt, new // Character('*')).toCharArray(); // creader.setEchoCharacter(null); // return password; } private byte[] applyDigest(String digestAlg, byte[] bytes) throws NoSuchAlgorithmException { System.out.println("Applying digest algorithm..."); MessageDigest md = MessageDigest.getInstance(digestAlg); md.update(bytes); return md.digest(); } private byte[] encapsulateInDigestInfo(String digestAlg, byte[] digestBytes) throws IOException { byte[] bcDigestInfoBytes = null; ByteArrayOutputStream bOut = new ByteArrayOutputStream(); DEROutputStream dOut = new DEROutputStream(bOut); DERObjectIdentifier digestObjId = new DERObjectIdentifier(digestAlg); AlgorithmIdentifier algId = new AlgorithmIdentifier(digestObjId, null); DigestInfo dInfo = new DigestInfo(algId, digestBytes); dOut.writeObject(dInfo); return bOut.toByteArray(); } private byte[] applyPkcs1Padding(int resultLength, byte[] srcBytes) { int paddingLength = resultLength - srcBytes.length; byte[] dstBytes = new byte[resultLength]; dstBytes[0] = 0x00; dstBytes[1] = 0x01; for (int i = 2; i < (paddingLength - 1); i++) { dstBytes[i] = (byte) 0xFF; } dstBytes[paddingLength - 1] = 0x00; for (int i = 0; i < srcBytes.length; i++) { dstBytes[paddingLength + i] = srcBytes[i]; } return dstBytes; } public boolean isForcingCryptoki() { return forcingCryptoki; }}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -