xmlcipher.java

来自「JAVA 所有包」· Java 代码 · 共 1,715 行 · 第 1/5 页

JAVA
1,715
字号
        try {            encryptedBytes =                c.doFinal(serializedOctets.getBytes("UTF-8"));            if (logger.isLoggable(java.util.logging.Level.FINE))                                     logger.log(java.util.logging.Level.FINE, "Expected cipher.outputSize = " +                Integer.toString(c.getOutputSize(                    serializedOctets.getBytes().length)));            if (logger.isLoggable(java.util.logging.Level.FINE))                                     logger.log(java.util.logging.Level.FINE, "Actual cipher.outputSize = " +                Integer.toString(encryptedBytes.length));        } catch (IllegalStateException ise) {            throw new XMLEncryptionException("empty", ise);        } catch (IllegalBlockSizeException ibse) {            throw new XMLEncryptionException("empty", ibse);        } catch (BadPaddingException bpe) {            throw new XMLEncryptionException("empty", bpe);        } catch (UnsupportedEncodingException uee) {		   	throw new XMLEncryptionException("empty", uee);		}		// Now build up to a properly XML Encryption encoded octet stream		// IvParameterSpec iv;		byte[] iv = c.getIV();		byte[] finalEncryptedBytes = 			new byte[iv.length + encryptedBytes.length];		System.arraycopy(iv, 0, finalEncryptedBytes, 0,						 iv.length);		System.arraycopy(encryptedBytes, 0, finalEncryptedBytes, 						 iv.length,						 encryptedBytes.length);        String base64EncodedEncryptedOctets = Base64.encode(finalEncryptedBytes);        if (logger.isLoggable(java.util.logging.Level.FINE))                                     logger.log(java.util.logging.Level.FINE, "Encrypted octets:\n" + base64EncodedEncryptedOctets);        if (logger.isLoggable(java.util.logging.Level.FINE))                                     logger.log(java.util.logging.Level.FINE, "Encrypted octets length = " +            base64EncodedEncryptedOctets.length());		try {			CipherData cd = _ed.getCipherData();			CipherValue cv = cd.getCipherValue();			// cv.setValue(base64EncodedEncryptedOctets.getBytes());			cv.setValue(base64EncodedEncryptedOctets);			if (contentMode) {				_ed.setType(					new URI(EncryptionConstants.TYPE_CONTENT).toString());			} else {				_ed.setType(					new URI(EncryptionConstants.TYPE_ELEMENT).toString());			}			EncryptionMethod method =				_factory.newEncryptionMethod(new URI(_algorithm).toString());			_ed.setEncryptionMethod(method);		} catch (URI.MalformedURIException mfue) {			throw new XMLEncryptionException("empty", mfue);		}        return (_ed);    }       public EncryptedData encryptData(Document context, byte [] serializedOctets, boolean contentMode) throws            /* XMLEncryption */ Exception {        logger.log(java.util.logging.Level.FINE, "Encrypting element...");        if (null == context)            logger.log(java.util.logging.Level.SEVERE, "Context document unexpectedly null...");        if (null == serializedOctets)            logger.log(java.util.logging.Level.SEVERE, "Canonicalized Data is unexpectedly null...");        if (_cipherMode != ENCRYPT_MODE)            logger.log(java.util.logging.Level.FINE, "XMLCipher unexpectedly not in ENCRYPT_MODE...");                _contextDocument = context;                if (_algorithm == null) {            throw new XMLEncryptionException("XMLCipher instance without transformation specified");        }                       logger.log(java.util.logging.Level.FINE, "Serialized octets:\n" + serializedOctets);                byte[] encryptedBytes = null;                // Now create the working cipher if none was created already        Cipher c;        if (_contextCipher == null) {            String jceAlgorithm =                    JCEMapper.translateURItoJCEID(_algorithm);                        logger.log(java.util.logging.Level.FINE, "alg = " + jceAlgorithm);                        try {                if (_requestedJCEProvider == null)                    c = Cipher.getInstance(jceAlgorithm);                else                    c = Cipher.getInstance(jceAlgorithm, _requestedJCEProvider);            } catch (NoSuchAlgorithmException nsae) {                throw new XMLEncryptionException("empty", nsae);            } catch (NoSuchProviderException nspre) {                throw new XMLEncryptionException("empty", nspre);            } catch (NoSuchPaddingException nspae) {                throw new XMLEncryptionException("empty", nspae);            }        } else {            c = _contextCipher;        }        // Now perform the encryption                try {            // Should internally generate an IV            // todo - allow user to set an IV            c.init(_cipherMode, _key);        } catch (InvalidKeyException ike) {            throw new XMLEncryptionException("empty", ike);        }                try {            encryptedBytes =                    c.doFinal(serializedOctets);                        logger.log(java.util.logging.Level.FINE, "Expected cipher.outputSize = " +                    Integer.toString(c.getOutputSize(                    serializedOctets.length)));            logger.log(java.util.logging.Level.FINE, "Actual cipher.outputSize = " +                    Integer.toString(encryptedBytes.length));        } catch (IllegalStateException ise) {            throw new XMLEncryptionException("empty", ise);        } catch (IllegalBlockSizeException ibse) {            throw new XMLEncryptionException("empty", ibse);        } catch (BadPaddingException bpe) {            throw new XMLEncryptionException("empty", bpe);        } catch (Exception uee) {            throw new XMLEncryptionException("empty", uee);        }                // Now build up to a properly XML Encryption encoded octet stream        // IvParameterSpec iv;                byte[] iv = c.getIV();        byte[] finalEncryptedBytes =                new byte[iv.length + encryptedBytes.length];        System.arraycopy(iv, 0, finalEncryptedBytes, 0,                iv.length);        System.arraycopy(encryptedBytes, 0, finalEncryptedBytes,                iv.length,                encryptedBytes.length);                String base64EncodedEncryptedOctets = Base64.encode(finalEncryptedBytes);                logger.log(java.util.logging.Level.FINE, "Encrypted octets:\n" + base64EncodedEncryptedOctets);        logger.log(java.util.logging.Level.FINE, "Encrypted octets length = " +                base64EncodedEncryptedOctets.length());                try {            CipherData cd = _ed.getCipherData();            CipherValue cv = cd.getCipherValue();            // cv.setValue(base64EncodedEncryptedOctets.getBytes());            cv.setValue(base64EncodedEncryptedOctets);                        if (contentMode) {                _ed.setType(                        new URI(EncryptionConstants.TYPE_CONTENT).toString());            } else {                _ed.setType(                        new URI(EncryptionConstants.TYPE_ELEMENT).toString());            }            EncryptionMethod method =                    _factory.newEncryptionMethod(new URI(_algorithm).toString());            _ed.setEncryptionMethod(method);        } catch (URI.MalformedURIException mfue) {            throw new XMLEncryptionException("empty", mfue);        }        return (_ed);    }    /**     * Returns an <code>EncryptedData</code> interface. Use this operation if     * you want to load an <code>EncryptedData</code> structure from a DOM 	 * structure and manipulate the contents      *     * @param context the context <code>Document</code>.     * @param element the <code>Element</code> that will be loaded     * @throws XMLEncryptionException     * @return     */    public EncryptedData loadEncryptedData(Document context, Element element) 		throws XMLEncryptionException {        if (logger.isLoggable(java.util.logging.Level.FINE))                                     logger.log(java.util.logging.Level.FINE, "Loading encrypted element...");        if(null == context)            logger.log(java.util.logging.Level.SEVERE, "Context document unexpectedly null...");        if(null == element)            logger.log(java.util.logging.Level.SEVERE, "Element unexpectedly null...");        if(_cipherMode != DECRYPT_MODE)            logger.log(java.util.logging.Level.SEVERE, "XMLCipher unexpectedly not in DECRYPT_MODE...");        _contextDocument = context;        _ed = _factory.newEncryptedData(element);		return (_ed);    }    /**     * Returns an <code>EncryptedKey</code> interface. Use this operation if     * you want to load an <code>EncryptedKey</code> structure from a DOM 	 * structure and manipulate the contents.     *     * @param context the context <code>Document</code>.     * @param element the <code>Element</code> that will be loaded     * @return     * @throws XMLEncryptionException     */    public EncryptedKey loadEncryptedKey(Document context, Element element) 		throws XMLEncryptionException {        if (logger.isLoggable(java.util.logging.Level.FINE))                                     logger.log(java.util.logging.Level.FINE, "Loading encrypted key...");        if(null == context)            logger.log(java.util.logging.Level.SEVERE, "Context document unexpectedly null...");        if(null == element)            logger.log(java.util.logging.Level.SEVERE, "Element unexpectedly null...");        if(_cipherMode != UNWRAP_MODE && _cipherMode != DECRYPT_MODE)            if (logger.isLoggable(java.util.logging.Level.FINE))                                     logger.log(java.util.logging.Level.FINE, "XMLCipher unexpectedly not in UNWRAP_MODE or DECRYPT_MODE...");        _contextDocument = context;        _ek = _factory.newEncryptedKey(element);		return (_ek);    }    /**     * Returns an <code>EncryptedKey</code> interface. Use this operation if     * you want to load an <code>EncryptedKey</code> structure from a DOM 	 * structure and manipulate the contents.	 *	 * Assumes that the context document is the document that owns the element     *     * @param element the <code>Element</code> that will be loaded     * @return     * @throws XMLEncryptionException     */    public EncryptedKey loadEncryptedKey(Element element) 		throws XMLEncryptionException {		return (loadEncryptedKey(element.getOwnerDocument(), element));    }    /**     * Encrypts a key to an EncryptedKey structure	 *	 * @param doc the Context document that will be used to general DOM	 * @param key Key to encrypt (will use previously set KEK to 	 * perform encryption     * @return     * @throws XMLEncryptionException     */    public EncryptedKey encryptKey(Document doc, Key key) throws            XMLEncryptionException {        if (logger.isLoggable(java.util.logging.Level.FINE))                                     logger.log(java.util.logging.Level.FINE, "Encrypting key ...");        if(null == key)             logger.log(java.util.logging.Level.SEVERE, "Key unexpectedly null...");        if(_cipherMode != WRAP_MODE)            if (logger.isLoggable(java.util.logging.Level.FINE))                                     logger.log(java.util.logging.Level.FINE, "XMLCipher unexpectedly not in WRAP_MODE...");		if (_algorithm == null) {			throw new XMLEncryptionException("XMLCipher instance without transformation specified");		}		_contextDocument = doc;		byte[] encryptedBytes = null;		Cipher c;		if (_contextCipher == null) {			// Now create the working cipher			String jceAlgorithm =				JCEMapper.translateURItoJCEID(_algorithm);			if (logger.isLoggable(java.util.logging.Level.FINE))                                     logger.log(java.util.logging.Level.FINE, "alg = " + jceAlgorithm);			try {			    if (_requestedJCEProvider == null)				c = Cipher.getInstance(jceAlgorithm);                            else                                c = Cipher.getInstance(jceAlgorithm, _requestedJCEProvider);			} catch (NoSuchAlgorithmException nsae) {				throw new XMLEncryptionException("empty", nsae);			} catch (NoSuchProviderException nspre) {				throw new XMLEncryptionException("empty", nspre);			} catch (NoSuchPaddingException nspae) {				throw new XMLEncryptionException("empty", nspae);			}		} else {			c = _contextCipher;		}		// Now perform the encryption		try {			// Should internally generate an IV			// todo - allow user to set an IV			c.init(Cipher.WRAP_MODE, _key);			encryptedBytes = c.wrap(key);		} catch (InvalidKeyException ike) {			throw new XMLEncryptionException("empty", ike);		} catch (IllegalBlockSizeException ibse) {			throw new XMLEncryptionException("empty", ibse);		}        String base64EncodedEncryptedOctets = Base64.encode(encryptedBytes);        if (logger.isLoggable(java.util.logging.Level.FINE))                                     logger.log(java.util.logging.Level.FINE, "Encrypted key octets:\n" + base64EncodedEncryptedOctets);        if (logger.isLoggable(java.util.logging.Level.FINE))                                     logger.log(java.util.logging.Level.FINE, "Encrypted key octets length = " +            base64EncodedEncryptedOctets.length());		CipherValue cv = _ek.getCipherData().getCipherValue();		cv.setValue(base64EncodedEncryptedOctets);        try {            EncryptionMethod method = _factory.newEncryptionMethod(                new URI(_algorithm).toString());            _ek.setEncryptionMethod(method);        } catch (URI.MalformedURIException mfue) {            throw new XMLEncryptionException("empty", mfue);        }		return _ek;		    }	/**	 * Decrypt a key from a passed in EncryptedKey structure	 *	 * @param encryptedKey Previously loaded EncryptedKey that needs	 * to be decrypted.	 * @param algorithm Algorithm for the decryption	 * @return a key corresponding to the give type     * @throws XMLEncryptionException	 */	public Key decryptKey(EncryptedKey encryptedKey, String algorithm) throws

⌨️ 快捷键说明

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