List of usage examples for javax.crypto SecretKey getEncoded
public byte[] getEncoded();
From source file:org.apache.ws.security.message.token.BSTKerberosTest.java
/** * A test for encryption using a Key Identifier to a Kerberos token *///w ww .j a v a 2s. com @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.apache.ws.security.message.token.KerberosTest.java
/** * Test using the KerberosSecurity class to retrieve a service ticket from a KDC, wrap it * in a BinarySecurityToken, and use the session key to sign the SOAP Body. *//*from ww w . java 2 s .co m*/ @org.junit.Test @org.junit.Ignore public void testKerberosSignature() throws Exception { Document doc = SOAPUtil.toSOAPPart(SOAPUtil.SAMPLE_SOAP_MSG); WSSecHeader secHeader = new WSSecHeader(); secHeader.insertSecurityHeader(doc); KerberosSecurity bst = new KerberosSecurity(doc); bst.retrieveServiceTicket("alice", null, "bob@service.ws.apache.org"); 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.setCustomTokenId(bst.getID()); sign.setCustomTokenValueType(WSConstants.WSS_GSS_KRB_V5_AP_REQ); SecretKey secretKey = bst.getSecretKey(); sign.setSecretKey(secretKey.getEncoded()); Document signedDoc = sign.build(doc, null, secHeader); if (LOG.isDebugEnabled()) { String outputString = org.apache.ws.security.util.XMLUtils.PrettyDocumentToString(signedDoc); LOG.debug(outputString); } // Configure the Validator WSSConfig wssConfig = WSSConfig.getNewInstance(); KerberosTokenValidator validator = new KerberosTokenValidator(); validator.setContextName("bob"); validator.setServiceName("bob@service.ws.apache.org"); // validator.setKerberosTokenDecoder(new KerberosTokenDecoderImpl()); wssConfig.setValidator(WSSecurityEngine.BINARY_TOKEN, validator); WSSecurityEngine secEngine = new WSSecurityEngine(); secEngine.setWssConfig(wssConfig); List<WSSecurityEngineResult> results = secEngine.processSecurityHeader(doc, null, null, null); WSSecurityEngineResult actionResult = WSSecurityUtil.fetchActionResult(results, WSConstants.BST); BinarySecurity token = (BinarySecurity) actionResult.get(WSSecurityEngineResult.TAG_BINARY_SECURITY_TOKEN); assertTrue(token != null); Principal principal = (Principal) actionResult.get(WSSecurityEngineResult.TAG_PRINCIPAL); assertTrue(principal instanceof KerberosPrincipal); assertTrue(principal.getName().contains("alice")); }
From source file:com.kk.dic.action.Upload.java
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); out = response.getWriter();//from w ww. j ava 2 s .c o m Connection con; PreparedStatement pstm = null; String fname = ""; String keyword = ""; String cd = ""; String a = (String) request.getSession().getAttribute("email"); System.out.println("User Name : " + a); try { boolean isMultipartContent = ServletFileUpload.isMultipartContent(request); if (!isMultipartContent) { return; } FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); out.print("one"); try { List<FileItem> fields = upload.parseRequest(request); Iterator<FileItem> it = fields.iterator(); if (!it.hasNext()) { return; } while (it.hasNext()) { FileItem fileItem = it.next(); if (fileItem.getFieldName().equals("name")) { fname = fileItem.getString(); System.out.println("File Name" + fname); } else if (fileItem.getFieldName().equals("keyword")) { keyword = fileItem.getString(); System.out.println("File Keyword" + keyword); } else { } boolean isFormField = fileItem.isFormField(); if (isFormField) { } else { out.print("one"); try { con = Dbconnection.getConnection(); pstm = con.prepareStatement( "insert into files (file, keyword, filetype, filename, CDate, owner, size, data, frank, file_key)values(?,?,?,?,?,?,?,?,?,?)"); out.println("getD " + fileItem.getName()); String str = getStringFromInputStream(fileItem.getInputStream()); // secretkey generating KeyGenerator keyGen = KeyGenerator.getInstance("AES"); keyGen.init(128); SecretKey secretKey = keyGen.generateKey(); System.out.println("secret key:" + secretKey); //converting secretkey to String byte[] be = secretKey.getEncoded();//encoding secretkey String skey = Base64.encode(be); System.out.println("converted secretkey to string:" + skey); String cipher = new encryption().encrypt(str, secretKey); System.out.println(str); //for get extension from given file String b = fileItem.getName().substring(fileItem.getName().lastIndexOf('.')); System.out.println("File Extension" + b); pstm.setBinaryStream(1, fileItem.getInputStream()); pstm.setString(2, keyword); pstm.setString(3, b); pstm.setString(4, fname); pstm.setDate(5, getCurrentDate()); pstm.setString(6, a); pstm.setLong(7, fileItem.getSize()); pstm.setString(8, cipher); pstm.setString(9, "0"); pstm.setString(10, skey); /*Cloud Start*/ File f = new File("D:/" + fileItem.getName()); out.print("<br/>" + f.getName()); FileWriter fw = new FileWriter(f); fw.write(cipher); fw.close(); Ftpcon ftpcon = new Ftpcon(); ftpcon.upload(f, fname); /*Cloud End*/ int i = pstm.executeUpdate(); if (i == 1) { response.sendRedirect("upload.jsp?msg=success"); } else { response.sendRedirect("upload.jsp?msgg=failed"); } con.close(); } catch (Exception e) { out.println(e); } } } } catch (Exception ex) { out.print(ex); Logger.getLogger(Upload.class.getName()).log(Level.SEVERE, null, ex); } } finally { out.close(); } }
From source file:org.openengsb.itests.util.AbstractRemoteTestHelper.java
protected String encryptMessage(String secureRequest, SecretKey sessionKey) throws EncryptionException, InterruptedException, IOException { PublicKey publicKey = getPublicKeyFromConfigFile(); String encodedMessage = Base64 .encodeBase64String(CipherUtils.encrypt(secureRequest.getBytes(), sessionKey)); String encodedKey = Base64.encodeBase64String(CipherUtils.encrypt(sessionKey.getEncoded(), publicKey)); String encryptedMessage = "" + "{" + " \"encryptedContent\":\"" + encodedMessage + "\"," + " \"encryptedKey\":\"" + encodedKey + "\"" + "}"; return encryptedMessage; }
From source file:org.apache.ws.security.message.token.KerberosTest.java
/** * Test using the KerberosSecurity class to retrieve a service ticket from a KDC, wrap it * in a BinarySecurityToken, and use the session key to sign the SOAP Body. */// ww w .j a v a2s . com @org.junit.Test @org.junit.Ignore public void testKerberosSignatureKI() throws Exception { Document doc = SOAPUtil.toSOAPPart(SOAPUtil.SAMPLE_SOAP_MSG); WSSecHeader secHeader = new WSSecHeader(); secHeader.insertSecurityHeader(doc); KerberosSecurity bst = new KerberosSecurity(doc); bst.retrieveServiceTicket("alice", null, "bob@service.ws.apache.org"); bst.setID("Id-" + bst.hashCode()); WSSecSignature sign = new WSSecSignature(); sign.setSignatureAlgorithm(SignatureMethod.HMAC_SHA1); sign.setKeyIdentifierType(WSConstants.CUSTOM_KEY_IDENTIFIER); sign.setCustomTokenValueType(WSConstants.WSS_KRB_KI_VALUE_TYPE); SecretKey secretKey = bst.getSecretKey(); byte[] keyData = secretKey.getEncoded(); sign.setSecretKey(keyData); byte[] digestBytes = WSSecurityUtil.generateDigest(bst.getToken()); sign.setCustomTokenId(Base64.encode(digestBytes)); Document signedDoc = sign.build(doc, null, secHeader); WSSecurityUtil.prependChildElement(secHeader.getSecurityHeader(), bst.getElement()); if (LOG.isDebugEnabled()) { String outputString = org.apache.ws.security.util.XMLUtils.PrettyDocumentToString(signedDoc); LOG.debug(outputString); } // Configure the Validator WSSConfig wssConfig = WSSConfig.getNewInstance(); KerberosTokenValidator validator = new KerberosTokenValidator(); validator.setContextName("bob"); validator.setServiceName("bob@service.ws.apache.org"); // validator.setKerberosTokenDecoder(new KerberosTokenDecoderImpl()); wssConfig.setValidator(WSSecurityEngine.BINARY_TOKEN, validator); WSSecurityEngine secEngine = new WSSecurityEngine(); secEngine.setWssConfig(wssConfig); List<WSSecurityEngineResult> results = secEngine.processSecurityHeader(doc, null, null, null); WSSecurityEngineResult actionResult = WSSecurityUtil.fetchActionResult(results, WSConstants.BST); BinarySecurity token = (BinarySecurity) actionResult.get(WSSecurityEngineResult.TAG_BINARY_SECURITY_TOKEN); assertTrue(token != null); Principal principal = (Principal) actionResult.get(WSSecurityEngineResult.TAG_PRINCIPAL); assertTrue(principal instanceof KerberosPrincipal); assertTrue(principal.getName().contains("alice")); }
From source file:com.diona.fileReader.CipherUtil.java
/** * Generates the secret key to be used for encryption. The secret key is retrieved from the shared preferences if * previously calculated.//from w w w . j av a 2 s.co m * * @return A new secret key if not previously calculated. * @throws NoSuchAlgorithmException * @throws InvalidKeySpecException * @throws UnsupportedEncodingException */ private SecretKeySpec getSecretKey(final Context context) throws NoSuchAlgorithmException, InvalidKeySpecException, UnsupportedEncodingException { // final SocialWorkerSharedPreferences sharedPreferences = SocialWorkerSharedPreferences.getInstance(); // if (sharedPreferences.getSecretKey() == null) { final byte[] salt = generateRandomKeyBytes(SALT_LENGTH); final SecretKeyFactory factory = SecretKeyFactory.getInstance(SECRET_KEY_ALGORITHM); final PBEKeySpec spec = new PBEKeySpec(SECRET_KEY_PASSPHRASE.toCharArray(), salt, KEY_ITERATIONS, KEY_SIZE); final SecretKey secretKey = factory.generateSecret(spec); final SecretKeySpec secretKeySpec = new SecretKeySpec(secretKey.getEncoded(), ENCRYPTION_ALGORITHM); // Set the value of the secret key in private shared preferences //sharedPreferences.setSecretKey(secretKeySpec); return secretKeySpec; /*} else { return sharedPreferences.getSecretKey(); }*/ }
From source file:edu.stanford.junction.extra.Encryption.java
@Override public boolean beforeActivityCreate() { try {//from ww w .jav a 2 s . c om KeyGenerator kgen = KeyGenerator.getInstance("AES"); kgen.init(128); SecretKey skey = kgen.generateKey(); mKey = skey.getEncoded(); init(); } catch (Exception e) { e.printStackTrace(); } return true; }
From source file:org.apache.pdfbox.pdmodel.encryption.PublicKeySecurityHandler.java
/** * Prepare the document for encryption./* w ww . j ava 2s . c om*/ * * @param doc The document that will be encrypted. * * @throws CryptographyException If there is an error while encrypting. */ public void prepareDocumentForEncryption(PDDocument doc) throws CryptographyException { try { Security.addProvider(new BouncyCastleProvider()); PDEncryptionDictionary dictionary = doc.getEncryptionDictionary(); if (dictionary == null) { dictionary = new PDEncryptionDictionary(); } dictionary.setFilter(FILTER); dictionary.setLength(this.keyLength); dictionary.setVersion(2); // remove CF, StmF, and StrF entries that may be left from a previous encryption dictionary.removeV45filters(); dictionary.setSubFilter(SUBFILTER); byte[][] recipientsField = new byte[policy.getRecipientsNumber()][]; // create the 20 bytes seed byte[] seed = new byte[20]; KeyGenerator key = KeyGenerator.getInstance("AES"); key.init(192, new SecureRandom()); SecretKey sk = key.generateKey(); System.arraycopy(sk.getEncoded(), 0, seed, 0, 20); // create the 20 bytes seed Iterator it = policy.getRecipientsIterator(); int i = 0; while (it.hasNext()) { PublicKeyRecipient recipient = (PublicKeyRecipient) it.next(); X509Certificate certificate = recipient.getX509(); int permission = recipient.getPermission().getPermissionBytesForPublicKey(); byte[] pkcs7input = new byte[24]; byte one = (byte) (permission); byte two = (byte) (permission >>> 8); byte three = (byte) (permission >>> 16); byte four = (byte) (permission >>> 24); System.arraycopy(seed, 0, pkcs7input, 0, 20); // put this seed in the pkcs7 input pkcs7input[20] = four; pkcs7input[21] = three; pkcs7input[22] = two; pkcs7input[23] = one; DERObject obj = createDERForRecipient(pkcs7input, certificate); ByteArrayOutputStream baos = new ByteArrayOutputStream(); DEROutputStream k = new DEROutputStream(baos); k.writeObject(obj); recipientsField[i] = baos.toByteArray(); i++; } dictionary.setRecipients(recipientsField); int sha1InputLength = seed.length; for (int j = 0; j < dictionary.getRecipientsLength(); j++) { COSString string = dictionary.getRecipientStringAt(j); sha1InputLength += string.getBytes().length; } byte[] sha1Input = new byte[sha1InputLength]; System.arraycopy(seed, 0, sha1Input, 0, 20); int sha1InputOffset = 20; for (int j = 0; j < dictionary.getRecipientsLength(); j++) { COSString string = dictionary.getRecipientStringAt(j); System.arraycopy(string.getBytes(), 0, sha1Input, sha1InputOffset, string.getBytes().length); sha1InputOffset += string.getBytes().length; } MessageDigest md = MessageDigest.getInstance("SHA-1"); byte[] mdResult = md.digest(sha1Input); this.encryptionKey = new byte[this.keyLength / 8]; System.arraycopy(mdResult, 0, this.encryptionKey, 0, this.keyLength / 8); doc.setEncryptionDictionary(dictionary); doc.getDocument().setEncryptionDictionary(dictionary.encryptionDictionary); } catch (NoSuchAlgorithmException ex) { throw new CryptographyException(ex); } catch (NoSuchProviderException ex) { throw new CryptographyException(ex); } catch (Exception e) { LOG.error(e, e); throw new CryptographyException(e); } }
From source file:io.kodokojo.config.module.SecurityModule.java
@Provides @Singleton// w ww . j a va2 s .c om @Named("securityKey") SecretKey provideSecretKey(SecurityConfig securityConfig) { if (securityConfig == null) { throw new IllegalArgumentException("securityConfig must be defined."); } File keyFile = createPrivateKeyFile(securityConfig); if (keyFile.exists() && keyFile.canRead()) { return provideAesKey(keyFile); } else { SecretKey res = generateAesKey(); try { keyFile.createNewFile(); } catch (IOException e) { throw new RuntimeException("Unable to create " + keyFile.getAbsolutePath() + " file.", e); } try (FileOutputStream out = new FileOutputStream(securityConfig.privateKeyPath())) { out.write(res.getEncoded()); out.flush(); return res; } catch (IOException e) { throw new RuntimeException( "unable to read and/or create key file at path " + keyFile.getAbsolutePath(), e); } } }
From source file:net.alegen.datpass.library.Generator.java
public String password(String input, int length) throws GeneratorException { if (this.currentProfile == null) { log.error("Cannot generate a password without having loaded a profile first."); throw new GeneratorException(); }//from w ww. j av a 2s .co m try { // calculate bit length int bitLength = (int) (length * 4.0 / 3 * 8); // take into account length for base64 encoding if (bitLength % 8 != 0) bitLength = (bitLength / 8) * 8; // ensure multiple of 8 // generate password SecretKey secretKey = CryptoManager.getInstance().derivateKey( KeyDerivationFunctions.fromString(this.currentProfile.getValue(FieldManager.FUNCTION_FIELD)), input, this.currentProfile.getValue(FieldManager.SALT_FIELD).getBytes("UTF-8"), bitLength, Integer.parseInt(this.currentProfile.getValue(FieldManager.ITER_FIELD))); byte[] encodedPassword = Base64.encodeBase64(secretKey.getEncoded()); String retval = new String(encodedPassword, "UTF-8"); // trim to desired length if (retval.length() != length) retval = retval.substring(0, length); // substitute characters to have just a-z, A-z, 0-9 retval = retval.replace('/', retval.charAt(retval.length() / 2)); retval = retval.replace('+', retval.charAt(retval.length() / 3)); retval = retval.replace('=', retval.charAt(retval.length() / 5)); return retval; } catch (UnsupportedEncodingException e) { log.error("UTF-8 encoding seems to not be supported?!"); e.printStackTrace(); throw new RuntimeException("An internall error occured and the operation failed."); } }