public void xx() { try { PublicKey pubKey = key; // FileInputStream sigfis = new FileInputStream(args[1]); byte[] sigToVerify = (byte[]) objIn.readObject(); // sigfis.read(sigToVerify); // sigfis.close(); Signature sig = Signature.getInstance("SHA1withDSA", "SUN"); sig.initVerify(pubKey); FileInputStream datafis = (FileInputStream) objIn.readObject(); BufferedInputStream bufin = new BufferedInputStream(datafis); byte[] buffer = new byte[1024]; int len; while (bufin.available() != 0) { len = bufin.read(buffer); sig.update(buffer, 0, len); } ; bufin.close(); boolean verifies = sig.verify(sigToVerify); System.out.println("signature verifies: " + verifies); } catch (Exception e) { System.err.println("Caught exception " + e.toString()); } }
/* * Encrypt private key using Password-based encryption (PBE) * as defined in PKCS#5. * * NOTE: Currently pbeWithSHAAnd3-KeyTripleDES-CBC algorithmID is * used to derive the key and IV. * * @return encrypted private key encoded as EncryptedPrivateKeyInfo */ private byte[] encryptPrivateKey(byte[] data, char[] password) throws IOException, NoSuchAlgorithmException, UnrecoverableKeyException { byte[] key = null; try { // create AlgorithmParameters AlgorithmParameters algParams = getAlgorithmParameters("PBEWithSHA1AndDESede"); // Use JCE SecretKey skey = getPBEKey(password); Cipher cipher = Cipher.getInstance("PBEWithSHA1AndDESede"); cipher.init(Cipher.ENCRYPT_MODE, skey, algParams); byte[] encryptedKey = cipher.doFinal(data); // wrap encrypted private key in EncryptedPrivateKeyInfo // as defined in PKCS#8 AlgorithmId algid = new AlgorithmId(pbeWithSHAAnd3KeyTripleDESCBC_OID, algParams); EncryptedPrivateKeyInfo encrInfo = new EncryptedPrivateKeyInfo(algid, encryptedKey); key = encrInfo.getEncoded(); } catch (Exception e) { UnrecoverableKeyException uke = new UnrecoverableKeyException("Encrypt Private Key failed: " + e.getMessage()); uke.initCause(e); throw uke; } return key; }
/** * Performs a handshake for key exchange between two people. This method must be called by both * people to ensure that the agreement has been reached on both ends. * * @param otherKey the serialized string version of the public key for the other person. Must not * be null. */ public void handShake(String otherKey) { if (DEBUG) { System.out.println("Performing handshake..."); } try { byte[] otherPubBytes = new Base64().decode(otherKey); ByteArrayInputStream bais = new ByteArrayInputStream(otherPubBytes); ObjectInputStream ois = new ObjectInputStream(bais); KeyAgreement keyAgree = KeyAgreement.getInstance("DiffieHellman"); keyAgree.init(privKey); Key otherPub = (Key) ois.readObject(); keyAgree.doPhase(otherPub, true); msgKey = keyAgree.generateSecret("DESede"); cipher = Cipher.getInstance("DESede"); mac = Mac.getInstance("HmacSHA512"); if (DEBUG) { System.out.println("Handshake completed"); } } catch (Exception e) { System.out.println("Could not complete handshake..."); System.out.println("Agreement not confirmed"); if (DEBUG) { e.printStackTrace(); } } }
/** * Sets the public parameters to the ones given in string parameter * * @param params must be of the form g p l, where g, p, and l are the public parameters for DH key * exchange */ public void setPubParams(String params) { String[] parts = params.split(" "); BigInteger g = new BigInteger(parts[0]); BigInteger p = new BigInteger(parts[1]); int l = Integer.parseInt(parts[2]); KeyPair keyPair = getKeyPair(g, p, l); this.pubKey = keyPair.getPublic(); this.privKey = keyPair.getPrivate(); ByteArrayOutputStream baos = null; ObjectOutputStream oos = null; try { baos = new ByteArrayOutputStream(); oos = new ObjectOutputStream(baos); oos.writeObject(pubKey); byte[] pubKeyBytes = baos.toByteArray(); this.strPubKey = new Base64().encodeToString(pubKeyBytes); oos.close(); baos.close(); } catch (Exception e) { if (DEBUG) { System.out.println("Not persisted"); e.printStackTrace(); } } }
private static byte[] gcmDecrypt(byte[] key, byte[] cipherText, byte[] aad, byte[] iv) throws AEADBadTagException { byte[] plainText = new byte[cipherText.length - BLOCK_SIZE]; try { SecretKeySpec keySpec = new SecretKeySpec(key, ALGORITHM); GCMParameterSpec gcmSpec = new GCMParameterSpec(GCM_TAG_LENGTH * 8, iv); Cipher cipher = Cipher.getInstance(ALGORITHM + "/" + MODE + "/NoPadding"); cipher.init(Cipher.DECRYPT_MODE, keySpec, gcmSpec); if (aad != null && aad.length != 0) { cipher.updateAAD(aad); } // store internally until decryptFinal is called cipher.doFinal(cipherText, 0, cipherText.length, plainText, 0); } catch (AEADBadTagException e) { System.out.println(e.getMessage()); throw e; } catch (Exception e) { System.out.println(e.getMessage()); } return plainText; }
private static byte[] gcmEncrypt(byte[] key, byte[] plainText, byte[] aad, byte[] iv) { byte[] cipherText = new byte[plainText.length + 16]; try { SecretKeySpec keySpec = new SecretKeySpec(key, ALGORITHM); GCMParameterSpec gcmSpec = new GCMParameterSpec(GCM_TAG_LENGTH * 8, iv); Cipher cipher = Cipher.getInstance(ALGORITHM + "/" + MODE + "/NoPadding"); cipher.init(Cipher.ENCRYPT_MODE, keySpec, gcmSpec); if (aad != null && aad.length != 0) { cipher.updateAAD(aad); } // if has more than one blocks, test cipher.update if (plainText.length > 16) { cipher.update(plainText, 0, 16, cipherText, 0); cipher.doFinal(plainText, 16, plainText.length - 16, cipherText, 16); } else { // doFinal(byte[] input, int inputOffset, int inputLen, byte[] output, int outputOffset) cipher.doFinal(plainText, 0, plainText.length, cipherText, 0); } } catch (Exception e) { System.out.println(e.getMessage()); } return cipherText; }
public void run() { try { ObjectInputStream ois = new ObjectInputStream(s.getInputStream()); ObjectOutputStream oos = new ObjectOutputStream(s.getOutputStream()); BigInteger bg = dhSpec.getG(); BigInteger bp = dhSpec.getP(); oos.writeObject(bg); oos.writeObject(bp); KeyPairGenerator kpg = KeyPairGenerator.getInstance("DH"); kpg.initialize(1024); KeyPair kpa = (KeyPair) ois.readObject(); KeyAgreement dh = KeyAgreement.getInstance("DH"); KeyPair kp = kpg.generateKeyPair(); oos.writeObject(kp); dh.init(kp.getPrivate()); Key pk = dh.doPhase(kpa.getPublic(), true); MessageDigest sha256 = MessageDigest.getInstance("SHA-256"); byte[] rawbits = sha256.digest(dh.generateSecret()); Cipher c = Cipher.getInstance(CIPHER_MODE); SecretKey key = new SecretKeySpec(rawbits, 0, 16, "AES"); byte ivbits[] = (byte[]) ois.readObject(); IvParameterSpec iv = new IvParameterSpec(ivbits); c.init(Cipher.DECRYPT_MODE, key, iv); Mac m = Mac.getInstance("HmacSHA1"); SecretKey mackey = new SecretKeySpec(rawbits, 16, 16, "HmacSHA1"); m.init(mackey); byte ciphertext[], cleartext[], mac[]; try { while (true) { ciphertext = (byte[]) ois.readObject(); mac = (byte[]) ois.readObject(); if (Arrays.equals(mac, m.doFinal(ciphertext))) { cleartext = c.update(ciphertext); System.out.println(ct + " : " + new String(cleartext, "UTF-8")); } else { // System.exit(1); System.out.println(ct + "error"); } } } catch (EOFException e) { cleartext = c.doFinal(); System.out.println(ct + " : " + new String(cleartext, "UTF-8")); System.out.println("[" + ct + "]"); } finally { if (ois != null) ois.close(); if (oos != null) oos.close(); } } catch (Exception e) { e.printStackTrace(); } }
public boolean shareAESkey() { try { Envelope message = null, e = null; // Generate AES key KeyGenerator keyGen = KeyGenerator.getInstance("AES"); AESkey = keyGen.generateKey(); keyGen = KeyGenerator.getInstance("HmacSHA1"); HMACkey = keyGen.generateKey(); byte[] keyBytes = AESkey.getEncoded(); byte[] hashBytes = HMACkey.getEncoded(); System.out.println("AES key generated"); System.out.println("HMAC key generated"); System.out.println("Begin Encryption..."); // Encrypt message w/ provided public key Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding"); cipher.init(Cipher.ENCRYPT_MODE, pubKey); byte[] cipherBytes = cipher.doFinal(keyBytes); byte[] cipherBytes1 = cipher.doFinal(hashBytes); System.out.println("Encryption Complete"); message = new Envelope("SKEY"); message.addObject(cipherBytes); // Add AESkey to message message.addObject(cipherBytes1); message.addObject(nonce); nonce++; byte[] messageBytes = Envelope.toByteArray(message); output.writeObject(messageBytes); byte[] inCipherBytes = (byte[]) input.readObject(); // Decrypt response cipher = Cipher.getInstance("AES"); cipher.init(Cipher.DECRYPT_MODE, AESkey); byte[] responseBytes = cipher.doFinal(inCipherBytes); Envelope response = Envelope.getEnvelopefromBytes(responseBytes); // If server indicates success, return the member list if (response.getMessage().equals("OK") && (Integer) response.getObjContents().get(0) == nonce) { return true; } else { return false; } } catch (Exception e) { System.err.println("Error: " + e.getMessage()); e.printStackTrace(System.err); return false; } }
public static byte[] decode(byte[] paramArrayOfByte1, byte[] paramArrayOfByte2) { SecretKeySpec localSecretKeySpec = new SecretKeySpec(paramArrayOfByte2, "AES"); try { Cipher localCipher = Cipher.getInstance("AES/ECB/PKCS5Padding"); localCipher.init(Cipher.DECRYPT_MODE, localSecretKeySpec); byte[] arrayOfByte = localCipher.doFinal(paramArrayOfByte1); return arrayOfByte; } catch (Exception localException) { localException.printStackTrace(); } return null; }
private long addCertificateToKeychain(String alias, Certificate cert) { byte[] certblob = null; long returnValue = 0; try { certblob = cert.getEncoded(); returnValue = _addItemToKeychain(alias, true, certblob, null); } catch (Exception e) { e.printStackTrace(); } return returnValue; }
/* * Generate PBE key */ private SecretKey getPBEKey(char[] password) throws IOException { SecretKey skey = null; try { PBEKeySpec keySpec = new PBEKeySpec(password); SecretKeyFactory skFac = SecretKeyFactory.getInstance("PBE"); skey = skFac.generateSecret(keySpec); } catch (Exception e) { IOException ioe = new IOException("getSecretKey failed: " + e.getMessage()); ioe.initCause(e); throw ioe; } return skey; }
// decrypts string public String decrypt(String toDecrypt) { try { // see the above comment for rant, replacing Encoder with Decoder... kthxbye // note: "above comment" no longer exists byte[] decoded = Base64.decode(toDecrypt); // decrypt byte[] bytes = decryptionCipher.doFinal(decoded); return new String(bytes, "ASCII"); } catch (Exception e) { System.out.println("Decryption Error: " + e); e.printStackTrace(); } return null; }
/** * Generates the private RSA key from the given information paramter. The info must be RSA private * information and of the form "privMod privExp" * * @param info must be RSA private information and of the form "privMod privExp" */ public void genRSAPrivKey(String info) { try { String[] parts = info.split(" "); BigInteger mod = new BigInteger(parts[0]); BigInteger exp = new BigInteger(parts[1]); KeySpec ks = (KeySpec) new RSAPrivateKeySpec(mod, exp); KeyFactory kf = KeyFactory.getInstance("RSA"); privRSAKey = kf.generatePrivate(ks); } catch (Exception e) { if (DEBUG) { System.out.println("Could not generate the RSA private key"); e.printStackTrace(); } } }
/* * Generate PBE Algorithm Parameters */ private AlgorithmParameters getAlgorithmParameters(String algorithm) throws IOException { AlgorithmParameters algParams = null; // create PBE parameters from salt and iteration count PBEParameterSpec paramSpec = new PBEParameterSpec(getSalt(), iterationCount); try { algParams = AlgorithmParameters.getInstance(algorithm); algParams.init(paramSpec); } catch (Exception e) { IOException ioe = new IOException("getAlgorithmParameters failed: " + e.getMessage()); ioe.initCause(e); throw ioe; } return algParams; }
public static byte[] decode64(byte[] paramArrayOfByte) { SecretKeySpec localSecretKeySpec = new SecretKeySpec(BaseSecretKey, "AES"); try { // byte[] arrayOfByte1 = Base64.decodeBase64(paramArrayOfByte); byte[] arrayOfByte1 = Base64.decode(paramArrayOfByte, Base64.DEFAULT); Cipher localCipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); localCipher.init(Cipher.DECRYPT_MODE, localSecretKeySpec); byte[] arrayOfByte2 = localCipher.doFinal(arrayOfByte1); return arrayOfByte2; } catch (Exception localException) { localException.printStackTrace(); } return null; }
/** * 对字符串加密 * * @param source String 要加密的字符串 * @return byte[] 已加密的字节 */ public byte[] encrypt(String source) { try { // Encode the string into bytes using utf-8 // byte[] utf8 = new sun.misc.BASE64Decoder().decodeBuffer(str); // Encrypt byte[] enc = ecipher.doFinal(source.getBytes()); // Encode bytes to base64 to get a string // return new sun.misc.BASE64Encoder().encode(enc); return enc; } catch (Exception e) { e.printStackTrace(); } return null; }
static void getBytes(String inPath) { Scanner scan = new Scanner(inPath); fileType = scan.next(); // save the file name for reconstruction later filePath = inPath; // assign global var file = new File(filePath); // new file to encrypt Path path = Paths.get(filePath); // return the path for the file try { plainText = Files.readAllBytes(path); // attempts to read the bytes from path } // some sort of runtime error here, null size buffer error catch (Exception e) { e.printStackTrace(); } finally { scan.close(); } }
/** * Encrypts the given msg and returns the ciphertext for the encryted message * * @param msg != null * @return the encrypted message or null if encryption fails */ public String encryptMsg(String msg) { try { cipher.init(Cipher.ENCRYPT_MODE, msgKey); mac.init(msgKey); byte[] c1 = cipher.doFinal(msg.getBytes()); String c1Str = new Base64().encodeToString(c1); byte[] m = mac.doFinal(c1); String mStr = new Base64().encodeToString(m); return (c1Str + "::::" + mStr).replace("\r\n", "_").replace("\r", "-").replace("\n", "~"); } catch (Exception e) { System.out.println("Could not encrypt the message"); if (DEBUG) { e.printStackTrace(); } return null; } }
public void run() { try { BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(file), charset)); if (outputFile != null) { bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outputFile), charset)); } String line; while ((line = br.readLine()) != null) { filePosition += line.length() + 2; line = line.trim(); if (!line.startsWith("#")) { String[] sides = split(line); if ((sides != null) && !sides[0].equals("key")) { if (searchPHI) { // Search the decrypted PHI for the searchText sides[0] = decrypt(sides[0]); if (sides[0].indexOf(searchText) != -1) { output(sides[0] + " = " + sides[1] + "\n"); } } else { // Search the trial ID for the searchText if (sides[1].indexOf(searchText) != -1) { sides[0] = decrypt(sides[0]); output(sides[0] + " = " + sides[1] + "\n"); } } } } } br.close(); if (bw != null) { bw.flush(); bw.close(); } } catch (Exception e) { append("\n\n" + e.getClass().getName() + ": " + e.getMessage() + "\n"); } append("\nDone.\n"); setMessage("Ready..."); }
/** * Constructs an RSA key pair and returns the public key or null if the key pair could not be * generated * * @return the RSA public key generated from the construction of the key pair or null if the key * pair could not be generated */ public Key getRSAPair() { try { SecureRandom random = new SecureRandom(); KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA"); generator.initialize(1024, random); KeyPair pair = generator.generateKeyPair(); PublicKey pubKey = pair.getPublic(); PrivateKey privKey = pair.getPrivate(); privRSAKey = privKey; pubRSAKey = pubKey; return pubKey; } catch (Exception e) { if (DEBUG) { System.out.println("Could not get the RSA pair"); e.printStackTrace(); } return null; } }
/** * Decrypts the given String and returns the decrypted message if the message is verified to come * from the correct sender, or null otherwise * * @param encryptedMsg != null * @param nonce must be the nonce sent to the sender to use in the encryption of the message * @return the decrypted message or null if the message is not verified */ public String decryptMsgNonce(String encryptedMsg) { try { cipher.init(Cipher.DECRYPT_MODE, msgKey); mac.init(msgKey); encryptedMsg = encryptedMsg.replace("~", "\n").replace("-", "\r").replace("_", "\r\n"); String[] encMsgParts = encryptedMsg.split("::::"); String encMsg = encMsgParts[0]; String checkM = encMsgParts[1]; byte[] encBytes = new Base64().decode(encMsg); byte[] message = cipher.doFinal(encBytes); byte[] m = mac.doFinal(encBytes); String mStr = new Base64().encodeToString(m); if (mStr.equals(checkM)) { String mess = new String(message); String[] parts = mess.split(":::"); String msg = parts[0]; int n = Integer.parseInt(parts[1]); if (nonceSet.contains(n)) { nonceSet.remove(n); return msg; } else { if (DEBUG) { System.out.println("Nonces don't match..."); System.out.println("Expected: " + nonceSet.toString() + ", Actual: " + n); } return null; } } else { if (DEBUG) { System.out.println("MACs don't match..."); } return null; } } catch (Exception e) { System.out.println("Could not decrypt"); if (DEBUG) { e.printStackTrace(); } } return null; }
/** * Decrypts the given encrypted message using reverse RSA, meaning that it uses the public key to * decrypt, and returns the decrypte message or null if the message could not be decrypted * * @param encMsg != null and encrypted with either this object or a similar object that has the * proper decryption parameters * @return the string representation of the message that was decrypted or null if the message * could not be decrypted */ public String decryptRSA(String encMsg) { try { encMsg = encMsg.replace("::", "\n").replace("~", "\r").replace("_", "\r\n"); Cipher cipher = Cipher.getInstance("RSA"); cipher.init(Cipher.DECRYPT_MODE, pubRSAKey); String result = ""; for (int i = 0; i < encMsg.length() / 178; i++) { String subMsg = encMsg.substring(i * 178, Math.min((i + 1) * 178, encMsg.length())); byte[] msgBytes = cipher.doFinal(new Base64().decode(subMsg)); result += new String(msgBytes); } return result; } catch (Exception e) { System.out.println("Could not decrypt the message with RSA"); if (DEBUG) { e.printStackTrace(); } return null; } }
/** * Encrypts the given message using reverse RSA (encrypts with the private key) and returns the * ciphertext of the message in String form or null if the message could not be encrypted * * @param msg != null * @return ciphertext form of the message made from RSA encryption or null if the message could * not be encrypted */ public String encryptRSA(String msg) { try { Cipher cipher = Cipher.getInstance("RSA"); cipher.init(Cipher.ENCRYPT_MODE, privRSAKey); byte[] msgBytes = msg.getBytes(); String result = ""; for (int i = 0; i < (int) Math.ceil(msgBytes.length * 1.0 / 100); i++) { byte[] c = cipher.doFinal( Arrays.copyOfRange(msgBytes, i * 100, Math.min((i + 1) * 100, msgBytes.length))); result += new Base64().encodeToString(c); } return result.replace("\r\n", "_").replace("\r", "~").replace("\n", "::"); } catch (Exception e) { System.out.println("Could not encrypt the message with RSA"); if (DEBUG) { e.printStackTrace(); } return null; } }
/** * Creates a new MsgEncrypt object with the given parameters * * @param g != null, must satisfy DH key exchange * @param p != null, must satisfy DH key exchange * @param l must satisfy DH key exchange */ private MsgEncrypt(BigInteger g, BigInteger p, int l) { KeyPair keyPair = getKeyPair(g, p, l); this.pubKey = keyPair.getPublic(); this.privKey = keyPair.getPrivate(); ByteArrayOutputStream baos = null; ObjectOutputStream oos = null; try { baos = new ByteArrayOutputStream(); oos = new ObjectOutputStream(baos); oos.writeObject(pubKey); byte[] pubKeyBytes = baos.toByteArray(); this.strPubKey = new Base64().encodeToString(pubKeyBytes); oos.close(); baos.close(); } catch (Exception e) { if (DEBUG) { System.out.println("Not persisted"); e.printStackTrace(); } } }
private CryptUtils(String passwd) { try { char[] chars = new char[passwd.length()]; for (int i = 0; i < chars.length; i++) chars[i] = passwd.charAt(i); PBEKeySpec pbeKeySpec = new PBEKeySpec(chars); SecretKeyFactory keyFac = SecretKeyFactory.getInstance("PBEWithMD5AndDES"); SecretKey pbeKey = keyFac.generateSecret(pbeKeySpec); // Create PBE encode Cipher encodeCipher = Cipher.getInstance("PBEWithMD5AndDES"); // Salt byte[] salt = { (byte) 0xc7, (byte) 0x73, (byte) 0x21, (byte) 0x8c, (byte) 0x7e, (byte) 0xc8, (byte) 0xee, (byte) 0x99 }; // Iteration count int count = 20; // Create PBE parameter set PBEParameterSpec encodePbeParamSpec = new PBEParameterSpec(salt, count); // Initialize PBE encode Cipher with key and parameters encodeCipher.init(Cipher.ENCRYPT_MODE, pbeKey, encodePbeParamSpec); // Create PBE decode Cipher decodeCipher = Cipher.getInstance("PBEWithMD5AndDES"); // Create PBE parameter set PBEParameterSpec decodePbeParamSpec = new PBEParameterSpec(salt, count); // Initialize PBE decode Cipher with key and parameters decodeCipher.init(Cipher.DECRYPT_MODE, pbeKey, decodePbeParamSpec); } catch (NoSuchPaddingException ex) { } catch (Exception ex) { ex.printStackTrace(); } }
public Cifra(byte[] chave) { try { SecretKey key = new SecretKeySpec(chave, "AES"); // Initialization Vector para CBC byte[] iv = { 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16 }; IvParameterSpec ivSpec = new IvParameterSpec(iv); encrypt = Cipher.getInstance("AES/CBC/PKCS5Padding"); encrypt.init(Cipher.ENCRYPT_MODE, key, ivSpec); decrypt = Cipher.getInstance("AES/CBC/PKCS5Padding"); decrypt.init(Cipher.DECRYPT_MODE, key, ivSpec); } catch (InvalidKeyException ex) { Logger.getLogger(Cifra.class.getName()).log(Level.SEVERE, null, ex); } catch (NoSuchAlgorithmException ex) { Logger.getLogger(Cifra.class.getName()).log(Level.SEVERE, null, ex); } catch (NoSuchPaddingException ex) { Logger.getLogger(Cifra.class.getName()).log(Level.SEVERE, null, ex); } catch (Exception e) { e.printStackTrace(); } }
/* * parse Algorithm Parameters */ private AlgorithmParameters parseAlgParameters(DerInputStream in) throws IOException { AlgorithmParameters algParams = null; try { DerValue params; if (in.available() == 0) { params = null; } else { params = in.getDerValue(); if (params.tag == DerValue.tag_Null) { params = null; } } if (params != null) { algParams = AlgorithmParameters.getInstance("PBE"); algParams.init(params.toByteArray()); } } catch (Exception e) { IOException ioe = new IOException("parseAlgParameters failed: " + e.getMessage()); ioe.initCause(e); throw ioe; } return algParams; }
public EncryDes() { try { // Create the key,"hshundsun2008"为随即初始化密文 String passPhrase = "hshundsun2008"; /* 生成秘钥 */ KeySpec keySpec = new DESKeySpec(passPhrase.getBytes()); SecretKey key = SecretKeyFactory.getInstance("DES").generateSecret(keySpec); // SecretKeySpec key = new // SecretKeySpec(passPhrase.getBytes(),"DES"); /* 初始化加解密实例 */ ecipher = Cipher.getInstance(key.getAlgorithm()); dcipher = Cipher.getInstance(key.getAlgorithm()); // Prepare the parameter to the ciphers // AlgorithmParameterSpec paramSpec = new PBEParameterSpec(salt, // iterationCount); // Create the ciphers ecipher.init(Cipher.ENCRYPT_MODE, key); dcipher.init(Cipher.DECRYPT_MODE, key); } catch (Exception e) { e.printStackTrace(); } }
/** * Decrypts the given String and returns the decrypted message if the message is verified to come * from the correct sender, or null otherwise * * @param encryptedMsg != null * @return the decrypted message or null if the message is not verified */ public String decryptMsg(String encryptedMsg) { try { cipher.init(Cipher.DECRYPT_MODE, msgKey); mac.init(msgKey); encryptedMsg = encryptedMsg.replace("~", "\n").replace("-", "\r").replace("_", "\r\n"); String[] encMsgParts = encryptedMsg.split("::::"); String encMsg = encMsgParts[0]; String checkM = encMsgParts[1]; byte[] encBytes = new Base64().decode(encMsg); byte[] message = cipher.doFinal(encBytes); byte[] m = mac.doFinal(encBytes); String mStr = new Base64().encodeToString(m); if (mStr.equals(checkM)) return new String(message); if (DEBUG) { System.out.println("MACs don't match..."); } } catch (Exception e) { System.out.println("Could not decrypt"); if (DEBUG) { e.printStackTrace(); } } return null; }
/* * The previous caller failed for some reason, report back the * Exception. We won't worry about Error's. * * Locked by SSLEngine.this. */ void checkThrown() throws SSLException { synchronized (thrownLock) { if (thrown != null) { String msg = thrown.getMessage(); if (msg == null) { msg = "Delegated task threw Exception/Error"; } /* * See what the underlying type of exception is. We should * throw the same thing. Chain thrown to the new exception. */ Exception e = thrown; thrown = null; if (e instanceof RuntimeException) { throw (RuntimeException) new RuntimeException(msg).initCause(e); } else if (e instanceof SSLHandshakeException) { throw (SSLHandshakeException) new SSLHandshakeException(msg).initCause(e); } else if (e instanceof SSLKeyException) { throw (SSLKeyException) new SSLKeyException(msg).initCause(e); } else if (e instanceof SSLPeerUnverifiedException) { throw (SSLPeerUnverifiedException) new SSLPeerUnverifiedException(msg).initCause(e); } else if (e instanceof SSLProtocolException) { throw (SSLProtocolException) new SSLProtocolException(msg).initCause(e); } else { /* * If it's SSLException or any other Exception, * we'll wrap it in an SSLException. */ throw (SSLException) new SSLException(msg).initCause(e); } } } }