List of usage examples for javax.crypto KeyGenerator generateKey
public final SecretKey generateKey()
From source file:org.apache.pdfbox.pdmodel.encryption.PublicKeySecurityHandler.java
private DERObject createDERForRecipient(byte[] in, X509Certificate cert) throws IOException, GeneralSecurityException { String s = "1.2.840.113549.3.2"; AlgorithmParameterGenerator algorithmparametergenerator = AlgorithmParameterGenerator.getInstance(s); AlgorithmParameters algorithmparameters = algorithmparametergenerator.generateParameters(); ByteArrayInputStream bytearrayinputstream = new ByteArrayInputStream( algorithmparameters.getEncoded("ASN.1")); ASN1InputStream asn1inputstream = new ASN1InputStream(bytearrayinputstream); DERObject derobject = asn1inputstream.readObject(); KeyGenerator keygenerator = KeyGenerator.getInstance(s); keygenerator.init(128);//from w w w . j av a 2 s. c o m SecretKey secretkey = keygenerator.generateKey(); Cipher cipher = Cipher.getInstance(s); cipher.init(1, secretkey, algorithmparameters); byte[] abyte1 = cipher.doFinal(in); DEROctetString deroctetstring = new DEROctetString(abyte1); KeyTransRecipientInfo keytransrecipientinfo = computeRecipientInfo(cert, secretkey.getEncoded()); DERSet derset = new DERSet(new RecipientInfo(keytransrecipientinfo)); AlgorithmIdentifier algorithmidentifier = new AlgorithmIdentifier(new DERObjectIdentifier(s), derobject); EncryptedContentInfo encryptedcontentinfo = new EncryptedContentInfo(PKCSObjectIdentifiers.data, algorithmidentifier, deroctetstring); EnvelopedData env = new EnvelopedData(null, derset, encryptedcontentinfo, null); ContentInfo contentinfo = new ContentInfo(PKCSObjectIdentifiers.envelopedData, env); return contentinfo.getDERObject(); }
From source file:org.cesecore.keys.token.SoftCryptoToken.java
@Override public void generateKey(final String algorithm, final int keysize, final String alias) throws NoSuchAlgorithmException, NoSuchProviderException, KeyStoreException, CryptoTokenOfflineException, InvalidKeyException, InvalidAlgorithmParameterException, SignatureException, CertificateException, IOException, NoSuchPaddingException, IllegalBlockSizeException { if (StringUtils.isNotEmpty(alias)) { // Soft crypto tokens must do very special things for secret keys, since PKCS#12 keystores are ot designed to hold // symmetric keys, we wrap the symmetric key with an RSA key and store it in properties // Generate the key KeyGenerator generator = KeyGenerator.getInstance(algorithm, getEncProviderName()); generator.init(keysize);//from w w w .java2s. c o m Key key = generator.generateKey(); // Wrap it // Find wrapping key PublicKey pubK = null; try { pubK = getPublicKey("symwrap"); } catch (CryptoTokenOfflineException e) { // No such key, generate it generateKeyPair("2048", "symwrap"); pubK = getPublicKey("symwrap"); } Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding", getEncProviderName()); cipher.init(Cipher.WRAP_MODE, pubK); byte[] out = cipher.wrap(key); String str = new String(Hex.encode(out)); Properties prop = getProperties(); prop.setProperty(alias, str); setProperties(prop); } else { log.debug("Trying to generate keys with empty alias."); } }
From source file:org.opensafety.hishare.util.implementation.EncryptionImpl.java
public String createPassword() throws CryptographyException { KeyGenerator kgen; try {//from w w w. j a va 2 s .co m kgen = KeyGenerator.getInstance(keyGenerator); } catch (NoSuchAlgorithmException e) { throw new CryptographyException(e.getMessage()); } kgen.init(passwordLength); SecretKey skey = kgen.generateKey(); byte[] raw = skey.getEncoded(); return new String(Hex.encodeHex(raw)); }
From source file:test.unit.be.fedict.eid.idp.protocol.saml2.SAML2Test.java
@Test public void testAttributEncryptionSymmetric() throws Exception { // Setup/*from ww w. jav a 2s.c om*/ String algorithm = EncryptionConstants.ALGO_ID_BLOCKCIPHER_AES128; KeyGenerator kgen = KeyGenerator.getInstance("AES"); kgen.init(128); SecretKey key = kgen.generateKey(); Encrypter encrypter = Saml2Util.getEncrypter(algorithm, key); // Operate: encrypt EncryptedAttribute encTarget; XMLObject encObject = null; try { encObject = encrypter.encrypt(getAttribute()); } catch (EncryptionException e) { fail("Object encryption failed: " + e); } // Verify LOG.debug(Saml2Util.domToString(Saml2Util.marshall(encObject), true)); assertNotNull("Encrypted object was null", encObject); assertTrue("Encrypted object was not an instance of the expected type", encObject instanceof EncryptedAttribute); encTarget = (EncryptedAttribute) encObject; assertEquals("Type attribute", EncryptionConstants.TYPE_ELEMENT, encTarget.getEncryptedData().getType()); assertEquals("Algorithm attribute", algorithm, encTarget.getEncryptedData().getEncryptionMethod().getAlgorithm()); assertNotNull("KeyInfo", encTarget.getEncryptedData().getKeyInfo()); assertEquals("Number of EncryptedKeys", 0, encTarget.getEncryptedData().getKeyInfo().getEncryptedKeys().size()); assertFalse("EncryptedData ID attribute was empty", DatatypeHelper.isEmpty(encTarget.getEncryptedData().getID())); // Setup Decrypter decrypter = Saml2Util.getDecrypter(key); // Operate: decrypt SAMLObject decryptedTarget = null; try { decryptedTarget = decrypter.decrypt(encTarget); } catch (DecryptionException e) { fail("Error on decryption of encrypted SAML 2 type to element: " + e); } // Verify assertNotNull("Decrypted target was null", decryptedTarget); assertTrue("Decrypted target was not the expected type", decryptedTarget instanceof Attribute); LOG.debug(Saml2Util.domToString(Saml2Util.marshall(decryptedTarget), true)); }
From source file:org.apache.ws.security.message.token.BSTKerberosTest.java
/** * A test for encryption using a direct reference to a Kerberos token *//*from w ww. jav a 2 s. c o m*/ @org.junit.Test public void testKerberosEncryptionDRCreation() throws Exception { Document doc = SOAPUtil.toSOAPPart(SOAPUtil.SAMPLE_SOAP_MSG); WSSecHeader secHeader = new WSSecHeader(); secHeader.insertSecurityHeader(doc); BinarySecurity bst = new BinarySecurity(doc); bst.setValueType(AP_REQ); bst.setEncodingType(BASE64_NS); KeyGenerator keyGen = KeyGenerator.getInstance("AES"); keyGen.init(128); SecretKey key = keyGen.generateKey(); byte[] keyData = key.getEncoded(); bst.setToken(keyData); bst.setID("Id-" + bst.hashCode()); WSSecurityUtil.prependChildElement(secHeader.getSecurityHeader(), bst.getElement()); WSSecEncrypt builder = new WSSecEncrypt(); builder.setSymmetricEncAlgorithm(WSConstants.AES_128); builder.setSymmetricKey(key); builder.setEncryptSymmKey(false); builder.setCustomReferenceValue(AP_REQ); builder.setEncKeyId(bst.getID()); Document encryptedDoc = builder.build(doc, crypto, secHeader); if (LOG.isDebugEnabled()) { String outputString = org.apache.ws.security.util.XMLUtils.PrettyDocumentToString(encryptedDoc); LOG.debug(outputString); } }
From source file:org.apache.ws.security.message.token.BSTKerberosTest.java
/** * A test for signing using a direct reference to a Kerberos token *//*from ww w .ja v a2s .c om*/ @org.junit.Test public void testKerberosSignatureDRCreation() throws Exception { Document doc = SOAPUtil.toSOAPPart(SOAPUtil.SAMPLE_SOAP_MSG); WSSecHeader secHeader = new WSSecHeader(); secHeader.insertSecurityHeader(doc); BinarySecurity bst = new BinarySecurity(doc); bst.setValueType(AP_REQ); bst.setEncodingType(BASE64_NS); KeyGenerator keyGen = KeyGenerator.getInstance("AES"); keyGen.init(128); SecretKey key = keyGen.generateKey(); byte[] keyData = key.getEncoded(); bst.setToken(keyData); bst.setID("Id-" + bst.hashCode()); WSSecurityUtil.prependChildElement(secHeader.getSecurityHeader(), bst.getElement()); WSSecSignature sign = new WSSecSignature(); sign.setSignatureAlgorithm(SignatureMethod.HMAC_SHA1); sign.setKeyIdentifierType(WSConstants.CUSTOM_SYMM_SIGNING); sign.setCustomTokenValueType(AP_REQ); sign.setCustomTokenId(bst.getID()); sign.setSecretKey(keyData); Document signedDoc = sign.build(doc, crypto, secHeader); if (LOG.isDebugEnabled()) { String outputString = org.apache.ws.security.util.XMLUtils.PrettyDocumentToString(signedDoc); LOG.debug(outputString); } }
From source file:test.unit.be.fedict.eid.idp.protocol.saml2.SAML2Test.java
@Test public void testAttributEncryptionAsymmetric2() throws Exception { // Setup//from ww w .ja v a 2 s . co m String algorithm = EncryptionConstants.ALGO_ID_BLOCKCIPHER_AES128; KeyGenerator kgen = KeyGenerator.getInstance("AES"); kgen.init(128); SecretKey key = kgen.generateKey(); KeyPair keyPair = generateKeyPair(); Encrypter encrypter = Saml2Util.getEncrypter(algorithm, key, keyPair.getPublic()); // Operate: encrypt EncryptedAttribute encTarget; XMLObject encObject = null; try { encObject = encrypter.encrypt(getAttribute()); } catch (EncryptionException e) { fail("Object encryption failed: " + e); } // Verify LOG.debug(Saml2Util.domToString(Saml2Util.marshall(encObject), true)); assertNotNull("Encrypted object was null", encObject); assertTrue("Encrypted object was not an instance of the expected type", encObject instanceof EncryptedAttribute); encTarget = (EncryptedAttribute) encObject; assertEquals("Type attribute", EncryptionConstants.TYPE_ELEMENT, encTarget.getEncryptedData().getType()); assertEquals("Algorithm attribute", algorithm, encTarget.getEncryptedData().getEncryptionMethod().getAlgorithm()); assertNotNull("KeyInfo", encTarget.getEncryptedData().getKeyInfo()); assertEquals(1, encTarget.getEncryptedData().getKeyInfo().getRetrievalMethods().size()); assertEquals(XMLConstants.XMLENC_NS + EncryptedKey.DEFAULT_ELEMENT_LOCAL_NAME, encTarget.getEncryptedData().getKeyInfo().getRetrievalMethods().get(0).getType()); assertEquals("Number of EncryptedKeys", 1, encTarget.getEncryptedKeys().size()); assertEquals(EncryptionConstants.ALGO_ID_KEYTRANSPORT_RSA15, encTarget.getEncryptedKeys().get(0).getEncryptionMethod().getAlgorithm()); assertFalse("EncryptedData ID attribute was empty", DatatypeHelper.isEmpty(encTarget.getEncryptedData().getID())); // Setup Decrypter decrypter = Saml2Util.getDecrypter(keyPair.getPrivate()); // Operate: decrypt SAMLObject decryptedTarget = null; try { decryptedTarget = decrypter.decrypt(encTarget); } catch (DecryptionException e) { fail("Error on decryption of encrypted SAML 2 type to element: " + e); } // Verify assertNotNull("Decrypted target was null", decryptedTarget); assertTrue("Decrypted target was not the expected type", decryptedTarget instanceof Attribute); LOG.debug(Saml2Util.domToString(Saml2Util.marshall(decryptedTarget), true)); }
From source file:org.apache.ws.security.message.token.BSTKerberosTest.java
/** * A test for signing using a KeyIdentifier to a Kerberos token *///from ww w.ja va2s . c o m @org.junit.Test public void testKerberosSignatureKICreation() throws Exception { Document doc = SOAPUtil.toSOAPPart(SOAPUtil.SAMPLE_SOAP_MSG); WSSecHeader secHeader = new WSSecHeader(); secHeader.insertSecurityHeader(doc); BinarySecurity bst = new BinarySecurity(doc); bst.setValueType(AP_REQ); bst.setEncodingType(BASE64_NS); KeyGenerator keyGen = KeyGenerator.getInstance("AES"); keyGen.init(128); SecretKey key = keyGen.generateKey(); byte[] keyData = key.getEncoded(); bst.setToken(keyData); bst.setID("Id-" + bst.hashCode()); WSSecurityUtil.prependChildElement(secHeader.getSecurityHeader(), bst.getElement()); WSSecSignature sign = new WSSecSignature(); sign.setSignatureAlgorithm(SignatureMethod.HMAC_SHA1); sign.setKeyIdentifierType(WSConstants.CUSTOM_KEY_IDENTIFIER); sign.setCustomTokenValueType(WSConstants.WSS_KRB_KI_VALUE_TYPE); byte[] digestBytes = WSSecurityUtil.generateDigest(keyData); sign.setCustomTokenId(Base64.encode(digestBytes)); sign.setSecretKey(keyData); Document signedDoc = sign.build(doc, crypto, secHeader); if (LOG.isDebugEnabled()) { String outputString = org.apache.ws.security.util.XMLUtils.PrettyDocumentToString(signedDoc); LOG.debug(outputString); } }
From source file:org.apache.ws.security.message.token.BSTKerberosTest.java
/** * A test for encryption using a Key Identifier to a Kerberos token *//*from w w w . j a va 2 s .co m*/ @org.junit.Test public void testKerberosEncryptionKICreation() throws Exception { Document doc = SOAPUtil.toSOAPPart(SOAPUtil.SAMPLE_SOAP_MSG); WSSecHeader secHeader = new WSSecHeader(); secHeader.insertSecurityHeader(doc); BinarySecurity bst = new BinarySecurity(doc); bst.setValueType(AP_REQ); bst.setEncodingType(BASE64_NS); KeyGenerator keyGen = KeyGenerator.getInstance("AES"); keyGen.init(128); SecretKey key = keyGen.generateKey(); byte[] keyData = key.getEncoded(); bst.setToken(keyData); bst.setID("Id-" + bst.hashCode()); WSSecurityUtil.prependChildElement(secHeader.getSecurityHeader(), bst.getElement()); WSSecEncrypt builder = new WSSecEncrypt(); builder.setSymmetricEncAlgorithm(WSConstants.AES_128); builder.setSymmetricKey(key); builder.setEncryptSymmKey(false); builder.setCustomReferenceValue(WSConstants.WSS_KRB_KI_VALUE_TYPE); byte[] digestBytes = WSSecurityUtil.generateDigest(keyData); builder.setEncKeyId(Base64.encode(digestBytes)); Document encryptedDoc = builder.build(doc, crypto, secHeader); if (LOG.isDebugEnabled()) { String outputString = org.apache.ws.security.util.XMLUtils.PrettyDocumentToString(encryptedDoc); LOG.debug(outputString); } }
From source file:org.atricore.idbus.capabilities.sso.support.core.encryption.XmlSecurityEncrypterImpl.java
private SecretKey generateDataEncryptionKey() { try {/*from w ww . j a v a 2s. com*/ logger.debug("using uri algorithm [" + getSymmetricKeyAlgorithmURI() + "]"); String jceAlgorithmName = JCEMapper.getJCEKeyAlgorithmFromURI(getSymmetricKeyAlgorithmURI()); int keyLength = JCEMapper.getKeyLengthFromURI(getSymmetricKeyAlgorithmURI()); logger.debug("generating key with algorithm [" + jceAlgorithmName + ":" + keyLength + "]"); KeyGenerator keyGenerator = KeyGenerator.getInstance(jceAlgorithmName); keyGenerator.init(keyLength); return keyGenerator.generateKey(); } catch (NoSuchAlgorithmException e) { logger.error(e.getMessage(), e); } return null; }