List of usage examples for javax.crypto Cipher getBlockSize
public final int getBlockSize()
From source file:cn.usually.common.pay.union.sdk.SecureUtil.java
/** * //from w w w .j ava 2s. c om * @param publicKey * @param plainData * @return * @throws Exception */ public byte[] encryptedData(PublicKey publicKey, byte[] plainData) throws Exception { try { Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding", new org.bouncycastle.jce.provider.BouncyCastleProvider()); cipher.init(Cipher.ENCRYPT_MODE, publicKey); int blockSize = cipher.getBlockSize(); int outputSize = cipher.getOutputSize(plainData.length); int leavedSize = plainData.length % blockSize; int blocksSize = leavedSize != 0 ? plainData.length / blockSize + 1 : plainData.length / blockSize; byte[] raw = new byte[outputSize * blocksSize]; int i = 0; while (plainData.length - i * blockSize > 0) { if (plainData.length - i * blockSize > blockSize) { cipher.doFinal(plainData, i * blockSize, blockSize, raw, i * outputSize); } else { cipher.doFinal(plainData, i * blockSize, plainData.length - i * blockSize, raw, i * outputSize); } i++; } return raw; } catch (Exception e) { throw new Exception(e.getMessage()); } }
From source file:org.apache.ws.security.message.WSEncryptBody.java
/** * Builds the SOAP envelope with encrypted Body and adds encrypted key. * <p/>/*w ww .j a v a2s .com*/ * This function performs several steps: * <p/> * <ul> * <li> First step: set the encoding namespace in the SOAP:Envelope </li> * <li> Second step: generate a symmetric key (session key) for * the selected symmetric encryption algorithm, and set the cipher * into encryption mode. * </li> * <li> Third step: get the data to encrypt. * We always encrypt the complete first child element of * the SOAP Body element * </li> * <li> Forth step: encrypt data, and set neccessary attributes in * <code>xenc:EncryptedData</code> * </li> * <li> Fifth step: get the certificate that contains the public key for * the public key algorithm that will encrypt the generated symmetric * (session) key. Up to now we support RSA 1-5 as public key * algorithm. * </li> * <li> Sixth step: setup the <code>wsse:Security</code> header block </li> * </ul> * * @param doc the SOAP envelope as <code>Document</code> with * plaintext Body * @param crypto an instance of the Crypto API to handle keystore and * Certificates * @return the SOAP envelope with encrypted Body as <code>Document * </code> * @throws WSSecurityException * @deprecated replaced by * {@link WSSecEncrypt#build(Document, Crypto, WSSecHeader)} */ public Document build(Document doc, Crypto crypto) throws WSSecurityException { doDebug = log.isDebugEnabled(); if (keyIdentifierType == WSConstants.EMBEDDED_KEYNAME || keyIdentifierType == WSConstants.EMBED_SECURITY_TOKEN_REF) { return buildEmbedded(doc); } long t0 = 0, t1 = 0, t2 = 0, t3 = 0; if (tlog.isDebugEnabled()) { t0 = System.currentTimeMillis(); } if (doDebug) { log.debug("Beginning Encryption..."); } /* * Second step: generate a symmetric key (session key) for * this alogrithm, and set the cipher into encryption mode. */ // This variable is made a classs attribute :: SecretKey symmetricKey = null; this.encryptionKey = this.symmetricKey; if (encryptionKey == null) { KeyGenerator keyGen = getKeyGenerator(); this.encryptionKey = keyGen.generateKey(); } Vector encDataRefs = doEncryption(doc, this.encryptionKey); if (tlog.isDebugEnabled()) { t1 = System.currentTimeMillis(); } /* * At this point data is encrypted with the symmetric key and can be * referenced via the above Id */ /* * Fifth step: get the certificate that contains the public key for the * public key algorithm that will encrypt * the generated symmetric (session) key. * Up to now we support RSA 1-5 as public key algorithm */ X509Certificate remoteCert = null; if (useThisCert != null) { remoteCert = useThisCert; } else { X509Certificate[] certs = crypto.getCertificates(user); if (certs == null || certs.length <= 0) { throw new WSSecurityException(WSSecurityException.FAILURE, "noUserCertsFound", new Object[] { user, "encryption" }); } remoteCert = certs[0]; } if (tlog.isDebugEnabled()) { t2 = System.currentTimeMillis(); } Cipher cipher = WSSecurityUtil.getCipherInstance(keyEncAlgo); try { cipher.init(Cipher.ENCRYPT_MODE, remoteCert); } catch (InvalidKeyException e) { throw new WSSecurityException(WSSecurityException.FAILED_ENCRYPTION, null, null, e); } byte[] encKey = this.encryptionKey.getEncoded(); if (doDebug) { log.debug("cipher blksize: " + cipher.getBlockSize() + ", symm key length: " + encKey.length); } if (cipher.getBlockSize() < encKey.length) { throw new WSSecurityException(WSSecurityException.FAILURE, "unsupportedKeyTransp", new Object[] { "public key algorithm too weak to encrypt symmetric key" }); } byte[] encryptedKey = null; try { encryptedKey = cipher.doFinal(encKey); } catch (IllegalStateException e1) { throw new WSSecurityException(WSSecurityException.FAILED_ENCRYPTION, null, null, e1); } catch (IllegalBlockSizeException e1) { throw new WSSecurityException(WSSecurityException.FAILED_ENCRYPTION, null, null, e1); } catch (BadPaddingException e1) { throw new WSSecurityException(WSSecurityException.FAILED_ENCRYPTION, null, null, e1); } Text keyText = WSSecurityUtil.createBase64EncodedTextNode(doc, encryptedKey); /* * Now we need to setup the wsse:Security header block * 1) get (or create) the wsse:Security header block * 2) create the xenc:EncryptedKey element. This already includes * the ExcrpytionMethod element with attributes that define * the key transport encryption algorithm * 3) Generate ds:KeyInfo element, this wraps the wsse:SecurityTokenReference * 4) set up the SecurityTokenReference, either with KeyIdentifier or * X509IssuerSerial. The SecTokenRef defines how to get to security * token used to encrypt the session key (this security token usually * contains a public key) * 5) Create the CipherValue element structure and insert the encrypted * session key * 6) The last step sets up the reference list that pints to the encrypted * data that was encrypted with this encrypted session key :-) */ Element wsseSecurity = insertSecurityHeader(doc); Element xencEncryptedKey = createEncryptedKey(doc, keyEncAlgo); if (parentNode == null) { WSSecurityUtil.prependChildElement(wsseSecurity, xencEncryptedKey); } else { WSSecurityUtil.prependChildElement(parentNode, xencEncryptedKey); } SecurityTokenReference secToken = new SecurityTokenReference(doc); switch (keyIdentifierType) { case WSConstants.X509_KEY_IDENTIFIER: secToken.setKeyIdentifier(remoteCert); // build a key id class?? break; case WSConstants.SKI_KEY_IDENTIFIER: secToken.setKeyIdentifierSKI(remoteCert, crypto); break; case WSConstants.THUMBPRINT_IDENTIFIER: secToken.setKeyIdentifierThumb(remoteCert); break; case WSConstants.ISSUER_SERIAL: XMLX509IssuerSerial data = new XMLX509IssuerSerial(doc, remoteCert); X509Data x509Data = new X509Data(doc); x509Data.add(data); secToken.setX509IssuerSerial(x509Data); break; case WSConstants.BST_DIRECT_REFERENCE: Reference ref = new Reference(doc); String certUri = wssConfig.getIdAllocator().createId("EncCertId-", remoteCert); ref.setURI("#" + certUri); BinarySecurity bstToken = null; bstToken = new X509Security(doc); ((X509Security) bstToken).setX509Certificate(remoteCert); bstToken.setID(certUri); ref.setValueType(bstToken.getValueType()); secToken.setReference(ref); WSSecurityUtil.prependChildElement(wsseSecurity, bstToken.getElement()); break; default: throw new WSSecurityException(WSSecurityException.FAILURE, "unsupportedKeyId"); } KeyInfo keyInfo = new KeyInfo(doc); keyInfo.addUnknownElement(secToken.getElement()); xencEncryptedKey.appendChild(keyInfo.getElement()); Element xencCipherValue = createCipherValue(doc, xencEncryptedKey); xencCipherValue.appendChild(keyText); createDataRefList(doc, xencEncryptedKey, encDataRefs); log.debug("Encryption complete."); if (tlog.isDebugEnabled()) { t3 = System.currentTimeMillis(); tlog.debug("EncryptBody: symm-enc " + (t1 - t0) + " cert " + (t2 - t1) + " key-encrypt " + (t3 - t2)); } return doc; }
From source file:org.openhab.binding.km200.internal.KM200Comm.java
/** * This function does the encoding for a new message to the device * *///from w w w . j a va 2 s. com public byte[] encodeMessage(String data) { byte[] encryptedDataB64 = null; try { // --- create cipher byte[] bdata = data.getBytes(device.getCharSet()); final Cipher cipher = Cipher.getInstance("AES/ECB/NoPadding"); cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(device.getCryptKeyPriv(), "AES")); logger.debug("Create padding.."); int bsize = cipher.getBlockSize(); logger.debug("Add Padding and Encrypt AES.."); final byte[] encryptedData = cipher.doFinal(addZeroPadding(bdata, bsize, device.getCharSet())); logger.debug("Encrypt B64.."); try { encryptedDataB64 = Base64.encodeBase64(encryptedData); } catch (Exception e) { logger.error("Base64encoding not possible: {}", e.getMessage()); } return encryptedDataB64; } catch (UnsupportedEncodingException | GeneralSecurityException e) { // failure to authenticate logger.error("Exception on encoding: {}", e); return null; } }
From source file:org.cesecore.keys.token.BaseCryptoToken.java
/** * This method extracts a PrivateKey from the keystore and wraps it, using a symmetric encryption key * * @param privKeyTransform - transformation algorithm * @param spec - transformation algorithm spec (e.g: IvParameterSpec for CBC mode) * @param encryptionKeyAlias - alias of the symmetric key that will encrypt the private key * @param privateKeyAlias - alias for the PrivateKey to be extracted * @return byte[] with the encrypted extracted key * @throws NoSuchAlgorithmException if privKeyTransform is null, empty, in an invalid format, or if no Provider supports a CipherSpi * implementation for the specified algorithm. * @throws NoSuchPaddingException if privKeyTransform contains a padding scheme that is not available. * @throws NoSuchProviderException if BouncyCastle is not registered in the security provider list. * @throws InvalidKeyException if the encryption key derived from encryptionKeyAlias was invalid. * @throws IllegalBlockSizeException if the Cipher created using privKeyTransform is a block cipher, no padding has been requested, and the length * of the encoding of the key to be wrapped is not a multiple of the block size. * @throws CryptoTokenOfflineException if Crypto Token is not available or connected, or key with alias does not exist. * @throws InvalidAlgorithmParameterException if spec id not valid or supported. * @throws PrivateKeyNotExtractableException if the key is not extractable, does not exist or encryption fails *///w w w .ja v a 2s . c o m public byte[] extractKey(String privKeyTransform, AlgorithmParameterSpec spec, String encryptionKeyAlias, String privateKeyAlias) throws NoSuchAlgorithmException, NoSuchPaddingException, NoSuchProviderException, InvalidKeyException, IllegalBlockSizeException, CryptoTokenOfflineException, PrivateKeyNotExtractableException, InvalidAlgorithmParameterException { if (doPermitExtractablePrivateKey()) { // get encryption key Key encryptionKey = getKey(encryptionKeyAlias); // get private key to wrap PrivateKey privateKey = getPrivateKey(privateKeyAlias); if (privateKey == null) { throw new PrivateKeyNotExtractableException( "Extracting key with alias '" + privateKeyAlias + "' return null."); } // since SUN PKCS11 Provider does not implements WRAP_MODE, // ENCRYPT_MODE with encoded private key will be used instead, giving the same result Cipher c = null; c = Cipher.getInstance(privKeyTransform, getEncProviderName()); if (spec == null) { c.init(Cipher.ENCRYPT_MODE, encryptionKey); } else { c.init(Cipher.ENCRYPT_MODE, encryptionKey, spec); } // wrap key byte[] encryptedKey; try { byte[] data = privateKey.getEncoded(); if (StringUtils.containsIgnoreCase(privKeyTransform, "NoPadding")) { // We must add PKCS7/PKCS5 padding ourselves to the data final PKCS7Padding padding = new PKCS7Padding(); // Calculate the number of pad bytes needed final int rem = data.length % c.getBlockSize(); final int padlen = c.getBlockSize() - rem; if (log.isDebugEnabled()) { log.debug("Padding key data with " + padlen + " bytes, using PKCS7/5Padding. Total len: " + (data.length + padlen)); } byte[] newdata = Arrays.copyOf(data, data.length + padlen); padding.addPadding(newdata, data.length); data = newdata; } encryptedKey = c.doFinal(data); } catch (BadPaddingException e) { throw new PrivateKeyNotExtractableException( "Extracting key with alias '" + privateKeyAlias + "' failed."); } return encryptedKey; } else { final String msg = intres.getLocalizedMessage("token.errornotextractable", privateKeyAlias, encryptionKeyAlias); throw new PrivateKeyNotExtractableException(msg); } }
From source file:com.charabia.SmsViewActivity.java
@Override public void onActivityResult(int reqCode, int resultCode, Intent data) { super.onActivityResult(reqCode, resultCode, data); switch (reqCode) { case SMS_KEY_CONTACT: if (resultCode == RESULT_OK) { Uri uri = data.getData();/* ww w . jav a2 s . c om*/ ContentResolver cr = getContentResolver(); Cursor cursor = cr.query(uri, new String[] { Contacts.LOOKUP_KEY }, null, null, null); String lookup = null; if (cursor.moveToFirst()) { lookup = cursor.getString(0); } cursor.close(); if (lookup == null) { Toast.makeText(this, R.string.unexpected_error, Toast.LENGTH_LONG).show(); return; } cursor = cr.query(Data.CONTENT_URI, new String[] { Phone.NUMBER }, Data.MIMETYPE + "=? AND " + Data.LOOKUP_KEY + "=?", new String[] { Phone.CONTENT_ITEM_TYPE, lookup }, null); ArrayList<String> options = new ArrayList<String>(); while (cursor.moveToNext()) { options.add(cursor.getString(0)); } cursor.close(); final String[] phoneList = options.toArray(new String[0]); Builder builder = new AlertDialog.Builder(this); builder.setTitle(R.string.send_invit_on_phone); builder.setItems(phoneList, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialogInterface, int i) { keypair = tools.loadKeyPair(); RSAPublicKey pubKey = (RSAPublicKey) keypair.getPublic(); byte[] encoded = pubKey.getModulus().toByteArray(); byte[] data = new byte[3 + encoded.length]; data[0] = Tools.MAGIC[0]; data[1] = Tools.MAGIC[1]; data[2] = Tools.PUBLIC_KEY_TYPE; System.arraycopy(encoded, 0, data, 3, encoded.length); tools.sendData(phoneList[i], Tools.INVITATION, "", data); } }); builder.create().show(); } else { Toast.makeText(this, R.string.error_create_key, Toast.LENGTH_LONG).show(); } break; case IntentIntegrator.REQUEST_CODE: if (resultCode == RESULT_OK) { try { String contents = data.getStringExtra("SCAN_RESULT"); @SuppressWarnings("unused") String format = data.getStringExtra("SCAN_RESULT_FORMAT"); // Handle successful scan // TODO: add more tests control String[] infos = contents.split("\n"); Cipher rsaCipher = Cipher.getInstance(Tools.RSA_CIPHER_ALGO); if (mode == MODE_ESCLAVE) { // Save key and show crypted key on QRCode key = tools.generateKeyAES().getEncoded(); KeyFactory keyFact = KeyFactory.getInstance("RSA"); PublicKey pubkey = keyFact.generatePublic( new RSAPublicKeySpec(new BigInteger(infos[1]), new BigInteger(infos[2]))); rsaCipher.init(Cipher.ENCRYPT_MODE, pubkey); int blockSize = rsaCipher.getBlockSize(); int nbBlock = key.length / blockSize; int reste = key.length % blockSize; byte[] cryptedKey = new byte[(nbBlock + 1) * rsaCipher.getOutputSize(blockSize)]; int offset = 0; for (int i = 0; i < nbBlock; i++) { offset += rsaCipher.doFinal(key, i * blockSize, blockSize, cryptedKey, offset); } rsaCipher.doFinal(key, nbBlock * blockSize, reste, cryptedKey, offset); IntentIntegrator.shareText(SmsViewActivity.this, prefPhoneNumber + "\n" + Base64.encodeToString(cryptedKey, Base64.NO_WRAP)); } else { // We have read crypted key, so decode it rsaCipher.init(Cipher.DECRYPT_MODE, keypair.getPrivate()); byte[] cryptedData = Base64.decode(infos[1], Base64.NO_WRAP); int blockSize = rsaCipher.getBlockSize(); int nbBlock = cryptedData.length / blockSize; int offset = 0; byte[] tempKey = new byte[(nbBlock + 1) * blockSize]; for (int i = 0; i < nbBlock; i++) { offset += rsaCipher.doFinal(cryptedData, i * blockSize, blockSize, tempKey, offset); } key = new byte[offset]; System.arraycopy(tempKey, 0, key, 0, offset); } phoneNumber = infos[0]; // store the key // TODO dialog to confirm add contact in mode SLAVE try { new Tools(this).updateOrCreateContactKey(phoneNumber, key); } catch (NoContactException e) { e.printStackTrace(); // propose to add contact Intent newIntent = new Intent(Intents.SHOW_OR_CREATE_CONTACT); newIntent.setData(Uri.fromParts("tel", phoneNumber, null)); startActivityForResult(newIntent, ADD_CONTACT); return; } Toast.makeText(this, getString(R.string.contact_added) + "\n" + phoneNumber, Toast.LENGTH_LONG) .show(); } catch (Exception e) { e.printStackTrace(); Toast.makeText(this, R.string.error_create_key, Toast.LENGTH_LONG).show(); } } else { // TODO: string Toast.makeText(this, R.string.fail_reading_tag, Toast.LENGTH_LONG).show(); } break; case ADD_CONTACT: try { tools.updateOrCreateContactKey(phoneNumber, key); Toast.makeText(this, getString(R.string.contact_added) + "\n" + phoneNumber, Toast.LENGTH_LONG) .show(); } catch (NoContactException e) { e.printStackTrace(); Toast.makeText(this, R.string.error_create_key, Toast.LENGTH_LONG).show(); } break; } }
From source file:com.skplanet.syruppay.token.SyrupPayTokenBuilderTest.java
_ERROR() throws Exception { final String keyFactorySalt = "65594821073030071593"; Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding", "SunJCE"); SecretKeySpec secretKeySpec;//w ww . ja v a 2 s . c o m try { KeySpec spec = new PBEKeySpec("7244798e1fab1a9175f752a8a7e12beafe2cd27b208f9f2f7ab43173358153fc5eae2499afa66f7386d74cb8cf4765133c513ae2e6acd521acde4f80d747".toCharArray(), keyFactorySalt.getBytes(), 1, 256); SecretKeyFactory secretKeyFactory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1"); SecretKey secretKey = secretKeyFactory.generateSecret(spec); secretKeySpec = new SecretKeySpec(secretKey.getEncoded(), "AES"); } catch (Exception e) { throw e; } cipher.init(Cipher.DECRYPT_MODE, secretKeySpec, new IvParameterSpec(new byte[cipher.getBlockSize()])); System.out.println(new String(cipher.doFinal(Base64.decodeBase64("yMvtcFwlhwBg22GF-biF4A".getBytes())), "UTF-8")); }
From source file:org.apache.xml.security.stax.impl.processor.output.XMLEncryptOutputProcessor.java
/** * Override this method to return a different AbstractInternalEncryptionOutputProcessor instance * which will write out the KeyInfo contents in the EncryptedData. *//*from w w w.j a v a 2 s . c o m*/ protected AbstractInternalEncryptionOutputProcessor createInternalEncryptionOutputProcessor( EncryptionPartDef encryptionPartDef, XMLSecStartElement startElement, String encoding, final OutboundSecurityToken keyWrappingToken) throws XMLStreamException, XMLSecurityException { final AbstractInternalEncryptionOutputProcessor processor = new AbstractInternalEncryptionOutputProcessor( encryptionPartDef, startElement, encoding) { @Override protected void createKeyInfoStructure(OutputProcessorChain outputProcessorChain) throws XMLStreamException, XMLSecurityException { if (keyWrappingToken == null) { // Do not write out a KeyInfo element return; } final String encryptionKeyTransportAlgorithm = getSecurityProperties() .getEncryptionKeyTransportAlgorithm(); PublicKey pubKey = keyWrappingToken.getPublicKey(); Key secretKey = keyWrappingToken.getSecretKey(encryptionKeyTransportAlgorithm); if (pubKey == null && secretKey == null) { // Do not write out a KeyInfo element return; } createStartElementAndOutputAsEvent(outputProcessorChain, XMLSecurityConstants.TAG_dsig_KeyInfo, true, null); List<XMLSecAttribute> attributes = new ArrayList<XMLSecAttribute>(1); String keyId = IDGenerator.generateID("EK"); attributes.add(createAttribute(XMLSecurityConstants.ATT_NULL_Id, keyId)); createStartElementAndOutputAsEvent(outputProcessorChain, XMLSecurityConstants.TAG_xenc_EncryptedKey, true, attributes); attributes = new ArrayList<XMLSecAttribute>(1); attributes.add( createAttribute(XMLSecurityConstants.ATT_NULL_Algorithm, encryptionKeyTransportAlgorithm)); createStartElementAndOutputAsEvent(outputProcessorChain, XMLSecurityConstants.TAG_xenc_EncryptionMethod, false, attributes); final String encryptionKeyTransportDigestAlgorithm = getSecurityProperties() .getEncryptionKeyTransportDigestAlgorithm(); final String encryptionKeyTransportMGFAlgorithm = getSecurityProperties() .getEncryptionKeyTransportMGFAlgorithm(); if (XMLSecurityConstants.NS_XENC11_RSAOAEP.equals(encryptionKeyTransportAlgorithm) || XMLSecurityConstants.NS_XENC_RSAOAEPMGF1P.equals(encryptionKeyTransportAlgorithm)) { byte[] oaepParams = getSecurityProperties().getEncryptionKeyTransportOAEPParams(); if (oaepParams != null) { createStartElementAndOutputAsEvent(outputProcessorChain, XMLSecurityConstants.TAG_xenc_OAEPparams, false, null); createCharactersAndOutputAsEvent(outputProcessorChain, Base64.encodeBase64String(oaepParams)); createEndElementAndOutputAsEvent(outputProcessorChain, XMLSecurityConstants.TAG_xenc_OAEPparams); } if (encryptionKeyTransportDigestAlgorithm != null) { attributes = new ArrayList<XMLSecAttribute>(1); attributes.add(createAttribute(XMLSecurityConstants.ATT_NULL_Algorithm, encryptionKeyTransportDigestAlgorithm)); createStartElementAndOutputAsEvent(outputProcessorChain, XMLSecurityConstants.TAG_dsig_DigestMethod, true, attributes); createEndElementAndOutputAsEvent(outputProcessorChain, XMLSecurityConstants.TAG_dsig_DigestMethod); } if (encryptionKeyTransportMGFAlgorithm != null) { attributes = new ArrayList<XMLSecAttribute>(1); attributes.add(createAttribute(XMLSecurityConstants.ATT_NULL_Algorithm, encryptionKeyTransportMGFAlgorithm)); createStartElementAndOutputAsEvent(outputProcessorChain, XMLSecurityConstants.TAG_xenc11_MGF, true, attributes); createEndElementAndOutputAsEvent(outputProcessorChain, XMLSecurityConstants.TAG_xenc11_MGF); } } createEndElementAndOutputAsEvent(outputProcessorChain, XMLSecurityConstants.TAG_xenc_EncryptionMethod); createKeyInfoStructureForEncryptedKey(outputProcessorChain, keyWrappingToken); createStartElementAndOutputAsEvent(outputProcessorChain, XMLSecurityConstants.TAG_xenc_CipherData, false, null); createStartElementAndOutputAsEvent(outputProcessorChain, XMLSecurityConstants.TAG_xenc_CipherValue, false, null); //encrypt the symmetric session key with the public key from the receiver: String jceid = JCEAlgorithmMapper.translateURItoJCEID(encryptionKeyTransportAlgorithm); if (jceid == null) { throw new XMLSecurityException("algorithms.NoSuchMap", new Object[] { encryptionKeyTransportAlgorithm }); } try { Cipher cipher = Cipher.getInstance(jceid); AlgorithmParameterSpec algorithmParameterSpec = null; if (XMLSecurityConstants.NS_XENC11_RSAOAEP.equals(encryptionKeyTransportAlgorithm) || XMLSecurityConstants.NS_XENC_RSAOAEPMGF1P.equals(encryptionKeyTransportAlgorithm)) { String jceDigestAlgorithm = "SHA-1"; if (encryptionKeyTransportDigestAlgorithm != null) { jceDigestAlgorithm = JCEAlgorithmMapper .translateURItoJCEID(encryptionKeyTransportDigestAlgorithm); } PSource.PSpecified pSource = PSource.PSpecified.DEFAULT; byte[] oaepParams = getSecurityProperties().getEncryptionKeyTransportOAEPParams(); if (oaepParams != null) { pSource = new PSource.PSpecified(oaepParams); } MGF1ParameterSpec mgfParameterSpec = new MGF1ParameterSpec("SHA-1"); if (encryptionKeyTransportMGFAlgorithm != null) { String jceMGFAlgorithm = JCEAlgorithmMapper .translateURItoJCEID(encryptionKeyTransportMGFAlgorithm); mgfParameterSpec = new MGF1ParameterSpec(jceMGFAlgorithm); } algorithmParameterSpec = new OAEPParameterSpec(jceDigestAlgorithm, "MGF1", mgfParameterSpec, pSource); } if (pubKey != null) { cipher.init(Cipher.WRAP_MODE, pubKey, algorithmParameterSpec); } else { cipher.init(Cipher.WRAP_MODE, secretKey, algorithmParameterSpec); } String tokenId = outputProcessorChain.getSecurityContext() .get(XMLSecurityConstants.PROP_USE_THIS_TOKEN_ID_FOR_ENCRYPTION); SecurityTokenProvider<OutboundSecurityToken> securityTokenProvider = outputProcessorChain .getSecurityContext().getSecurityTokenProvider(tokenId); final OutboundSecurityToken securityToken = securityTokenProvider.getSecurityToken(); Key sessionKey = securityToken .getSecretKey(getSecurityProperties().getEncryptionSymAlgorithm()); if (pubKey != null) { int blockSize = cipher.getBlockSize(); if (blockSize > 0 && blockSize < sessionKey.getEncoded().length) { throw new XMLSecurityException("stax.unsupportedKeyTransp"); } } byte[] encryptedEphemeralKey = cipher.wrap(sessionKey); createCharactersAndOutputAsEvent(outputProcessorChain, new Base64(76, new byte[] { '\n' }).encodeToString(encryptedEphemeralKey)); } catch (NoSuchPaddingException e) { throw new XMLSecurityException(e); } catch (NoSuchAlgorithmException e) { throw new XMLSecurityException(e); } catch (InvalidKeyException e) { throw new XMLSecurityException(e); } catch (IllegalBlockSizeException e) { throw new XMLSecurityException(e); } catch (InvalidAlgorithmParameterException e) { throw new XMLSecurityException(e); } createEndElementAndOutputAsEvent(outputProcessorChain, XMLSecurityConstants.TAG_xenc_CipherValue); createEndElementAndOutputAsEvent(outputProcessorChain, XMLSecurityConstants.TAG_xenc_CipherData); createEndElementAndOutputAsEvent(outputProcessorChain, XMLSecurityConstants.TAG_xenc_EncryptedKey); createEndElementAndOutputAsEvent(outputProcessorChain, XMLSecurityConstants.TAG_dsig_KeyInfo); } protected void createKeyInfoStructureForEncryptedKey(OutputProcessorChain outputProcessorChain, OutboundSecurityToken securityToken) throws XMLStreamException, XMLSecurityException { SecurityTokenConstants.KeyIdentifier keyIdentifier = getSecurityProperties() .getEncryptionKeyIdentifier(); X509Certificate[] x509Certificates = securityToken.getX509Certificates(); if (x509Certificates == null) { if (securityToken.getPublicKey() != null && SecurityTokenConstants.KeyIdentifier_KeyValue.equals(keyIdentifier)) { createStartElementAndOutputAsEvent(outputProcessorChain, XMLSecurityConstants.TAG_dsig_KeyInfo, true, null); XMLSecurityUtils.createKeyValueTokenStructure(this, outputProcessorChain, securityToken.getPublicKey()); createEndElementAndOutputAsEvent(outputProcessorChain, XMLSecurityConstants.TAG_dsig_KeyInfo); } return; } if (!SecurityTokenConstants.KeyIdentifier_NoKeyInfo.equals(keyIdentifier)) { createStartElementAndOutputAsEvent(outputProcessorChain, XMLSecurityConstants.TAG_dsig_KeyInfo, true, null); if (keyIdentifier == null || SecurityTokenConstants.KeyIdentifier_IssuerSerial.equals(keyIdentifier)) { XMLSecurityUtils.createX509IssuerSerialStructure(this, outputProcessorChain, x509Certificates); } else if (SecurityTokenConstants.KeyIdentifier_KeyValue.equals(keyIdentifier)) { XMLSecurityUtils.createKeyValueTokenStructure(this, outputProcessorChain, x509Certificates); } else if (SecurityTokenConstants.KeyIdentifier_SkiKeyIdentifier.equals(keyIdentifier)) { XMLSecurityUtils.createX509SubjectKeyIdentifierStructure(this, outputProcessorChain, x509Certificates); } else if (SecurityTokenConstants.KeyIdentifier_X509KeyIdentifier.equals(keyIdentifier)) { XMLSecurityUtils.createX509CertificateStructure(this, outputProcessorChain, x509Certificates); } else if (SecurityTokenConstants.KeyIdentifier_X509SubjectName.equals(keyIdentifier)) { XMLSecurityUtils.createX509SubjectNameStructure(this, outputProcessorChain, x509Certificates); } else { throw new XMLSecurityException("stax.unsupportedToken", new Object[] { keyIdentifier }); } createEndElementAndOutputAsEvent(outputProcessorChain, XMLSecurityConstants.TAG_dsig_KeyInfo); } } }; processor.getAfterProcessors().add(XMLEncryptOutputProcessor.class.getName()); return processor; }
From source file:org.apache.xml.security.encryption.XMLCipher.java
/** * Decrypt an EncryptedData element to a byte array * * When passed in an EncryptedData node, returns the decryption * as a byte array./* ww w. j av a 2 s .com*/ * * Does not modify the source document * @param element * @return the bytes resulting from the decryption * @throws XMLEncryptionException */ public byte[] decryptToByteArray(Element element) throws XMLEncryptionException { if (log.isDebugEnabled()) { log.debug("Decrypting to ByteArray..."); } if (cipherMode != DECRYPT_MODE) { log.error("XMLCipher unexpectedly not in DECRYPT_MODE..."); } EncryptedData encryptedData = factory.newEncryptedData(element); if (key == null) { KeyInfo ki = encryptedData.getKeyInfo(); if (ki != null) { try { // Add a EncryptedKey resolver ki.registerInternalKeyResolver( new EncryptedKeyResolver(encryptedData.getEncryptionMethod().getAlgorithm(), kek)); key = ki.getSecretKey(); } catch (KeyResolverException kre) { if (log.isDebugEnabled()) { log.debug(kre); } } } if (key == null) { log.error("XMLCipher::decryptElement called without a key and unable to resolve"); throw new XMLEncryptionException("encryption.nokey"); } } // Obtain the encrypted octets XMLCipherInput cipherInput = new XMLCipherInput(encryptedData); byte[] encryptedBytes = cipherInput.getBytes(); // Now create the working cipher String jceAlgorithm = JCEMapper.translateURItoJCEID(encryptedData.getEncryptionMethod().getAlgorithm()); if (log.isDebugEnabled()) { log.debug("JCE Algorithm = " + jceAlgorithm); } Cipher c; 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); } // Calculate the IV length and copy out // For now, we only work with Block ciphers, so this will work. // This should probably be put into the JCE mapper. int ivLen = c.getBlockSize(); byte[] ivBytes = new byte[ivLen]; // You may be able to pass the entire piece in to IvParameterSpec // and it will only take the first x bytes, but no way to be certain // that this will work for every JCE provider, so lets copy the // necessary bytes into a dedicated array. System.arraycopy(encryptedBytes, 0, ivBytes, 0, ivLen); IvParameterSpec iv = new IvParameterSpec(ivBytes); try { c.init(cipherMode, key, iv); } catch (InvalidKeyException ike) { throw new XMLEncryptionException("empty", ike); } catch (InvalidAlgorithmParameterException iape) { throw new XMLEncryptionException("empty", iape); } try { return c.doFinal(encryptedBytes, ivLen, encryptedBytes.length - ivLen); } catch (IllegalBlockSizeException ibse) { throw new XMLEncryptionException("empty", ibse); } catch (BadPaddingException bpe) { throw new XMLEncryptionException("empty", bpe); } }