List of usage examples for javax.crypto SecretKey getEncoded
public byte[] getEncoded();
From source file:org.apache.ws.security.processor.EncryptedDataProcessor.java
public List<WSSecurityEngineResult> handleToken(Element elem, RequestData request, WSDocInfo wsDocInfo) throws WSSecurityException { if (log.isDebugEnabled()) { log.debug("Found EncryptedData element"); }//from w w w . j av a 2 s . c o m Element kiElem = WSSecurityUtil.getDirectChildElement(elem, "KeyInfo", WSConstants.SIG_NS); // KeyInfo cannot be null if (kiElem == null) { throw new WSSecurityException(WSSecurityException.UNSUPPORTED_ALGORITHM, "noKeyinfo"); } String symEncAlgo = X509Util.getEncAlgo(elem); // Check BSP compliance if (request.getWssConfig().isWsiBSPCompliant()) { checkBSPCompliance(symEncAlgo); } // Get the Key either via a SecurityTokenReference or an EncryptedKey Element secRefToken = WSSecurityUtil.getDirectChildElement(kiElem, "SecurityTokenReference", WSConstants.WSSE_NS); Element encryptedKeyElement = WSSecurityUtil.getDirectChildElement(kiElem, WSConstants.ENC_KEY_LN, WSConstants.ENC_NS); if (elem != null && request.isRequireSignedEncryptedDataElements()) { WSSecurityUtil.verifySignedElement(elem, elem.getOwnerDocument(), wsDocInfo.getSecurityHeader()); } SecretKey key = null; List<WSSecurityEngineResult> encrKeyResults = null; Principal principal = null; if (secRefToken != null) { STRParser strParser = new SecurityTokenRefSTRParser(); Map<String, Object> parameters = new HashMap<String, Object>(); parameters.put(SecurityTokenRefSTRParser.SIGNATURE_METHOD, symEncAlgo); strParser.parseSecurityTokenReference(secRefToken, request, wsDocInfo, parameters); byte[] secretKey = strParser.getSecretKey(); principal = strParser.getPrincipal(); key = WSSecurityUtil.prepareSecretKey(symEncAlgo, secretKey); } else if (encryptedKeyElement != null) { EncryptedKeyProcessor encrKeyProc = new EncryptedKeyProcessor(); encrKeyResults = encrKeyProc.handleToken(encryptedKeyElement, request, wsDocInfo); byte[] symmKey = (byte[]) encrKeyResults.get(0).get(WSSecurityEngineResult.TAG_SECRET); key = WSSecurityUtil.prepareSecretKey(symEncAlgo, symmKey); } else { throw new WSSecurityException(WSSecurityException.UNSUPPORTED_ALGORITHM, "noEncKey"); } // Check for compliance against the defined AlgorithmSuite AlgorithmSuite algorithmSuite = request.getAlgorithmSuite(); if (algorithmSuite != null) { AlgorithmSuiteValidator algorithmSuiteValidator = new AlgorithmSuiteValidator(algorithmSuite); if (principal instanceof WSDerivedKeyTokenPrincipal) { algorithmSuiteValidator .checkDerivedKeyAlgorithm(((WSDerivedKeyTokenPrincipal) principal).getAlgorithm()); algorithmSuiteValidator .checkEncryptionDerivedKeyLength(((WSDerivedKeyTokenPrincipal) principal).getLength()); } algorithmSuiteValidator.checkSymmetricKeyLength(key.getEncoded().length); algorithmSuiteValidator.checkSymmetricEncryptionAlgorithm(symEncAlgo); } // initialize Cipher .... XMLCipher xmlCipher = null; try { xmlCipher = XMLCipher.getInstance(symEncAlgo); xmlCipher.setSecureValidation(true); xmlCipher.init(XMLCipher.DECRYPT_MODE, key); } catch (XMLEncryptionException ex) { throw new WSSecurityException(WSSecurityException.UNSUPPORTED_ALGORITHM, null, null, ex); } Node previousSibling = elem.getPreviousSibling(); Node parent = elem.getParentNode(); try { xmlCipher.doFinal(elem.getOwnerDocument(), elem, false); } catch (Exception e) { throw new WSSecurityException(WSSecurityException.FAILED_CHECK, null, null, e); } WSDataRef dataRef = new WSDataRef(); dataRef.setWsuId(elem.getAttributeNS(null, "Id")); dataRef.setAlgorithm(symEncAlgo); dataRef.setContent(false); Node decryptedNode; if (previousSibling == null) { decryptedNode = parent.getFirstChild(); } else { decryptedNode = previousSibling.getNextSibling(); } if (decryptedNode != null && Node.ELEMENT_NODE == decryptedNode.getNodeType()) { dataRef.setProtectedElement((Element) decryptedNode); } dataRef.setXpath(ReferenceListProcessor.getXPath(decryptedNode)); WSSecurityEngineResult result = new WSSecurityEngineResult(WSConstants.ENCR, Collections.singletonList(dataRef)); result.put(WSSecurityEngineResult.TAG_ID, elem.getAttributeNS(null, "Id")); wsDocInfo.addResult(result); wsDocInfo.addTokenElement(elem); WSSConfig wssConfig = request.getWssConfig(); if (wssConfig != null) { // Get hold of the plain text element Element decryptedElem; if (previousSibling == null) { decryptedElem = (Element) parent.getFirstChild(); } else { decryptedElem = (Element) previousSibling.getNextSibling(); } QName el = new QName(decryptedElem.getNamespaceURI(), decryptedElem.getLocalName()); Processor proc = request.getWssConfig().getProcessor(el); if (proc != null) { if (log.isDebugEnabled()) { log.debug("Processing decrypted element with: " + proc.getClass().getName()); } List<WSSecurityEngineResult> results = proc.handleToken(decryptedElem, request, wsDocInfo); List<WSSecurityEngineResult> completeResults = new ArrayList<WSSecurityEngineResult>(); if (encrKeyResults != null) { completeResults.addAll(encrKeyResults); } completeResults.add(result); completeResults.addAll(0, results); return completeResults; } } encrKeyResults.add(result); return encrKeyResults; }
From source file:edu.hku.sdb.rewrite.SdbSchemeRewriter.java
private Expr rewriteLikePredicate(LikePredicate likePred) { if (!likePred.involveEncrytedCol()) return likePred; SdbLikeExpr expr = new SdbLikeExpr(); assert (likePred.getColumn() instanceof FieldLiteral); assert (likePred.getPattern() instanceof StringLiteral); FieldLiteral column = (FieldLiteral) likePred.getColumn(); StringLiteral keyword = (StringLiteral) likePred.getPattern(); expr.addChild(column);/* w w w.j a va2s.c om*/ expr.addChild(keyword); SecretKey pubKey = column.getSearchColKey().getPubKey(); StringLiteral pubKeyEncoded = new StringLiteral(Base64.encodeBase64String(pubKey.getEncoded())); expr.addChild(pubKeyEncoded); return expr; }
From source file:com.filelocker.encryption.AES_Encryption.java
/** * If a file is being decrypted, we need to know the pasword, the salt and the initialization vector (iv). * We have the password from initializing the class. pass the iv and salt here which is * obtained when encrypting the file initially. * * @param inFile - The Encrypted File containing encrypted data , salt and InitVec * @throws NoSuchAlgorithmException//from w ww . j a v a 2 s . c o m * @throws InvalidKeySpecException * @throws NoSuchPaddingException * @throws InvalidKeyException * @throws InvalidAlgorithmParameterException * @throws DecoderException * @throws IOException */ public void setupDecrypt(File inFile) throws NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException, DecoderException, IOException { SecretKeyFactory factory = null; SecretKey tmp = null; SecretKey secret = null; byte[] vSalt = new byte[8]; byte[] vInitVec = new byte[16]; RandomAccessFile vFile = new RandomAccessFile(inFile, "rw"); //The last 8 bits are salt so seek to length of file minus 9 bits vFile.seek(vFile.length() - 8); vFile.readFully(vSalt); //The last 8 bits are salt and 16 bits before last 8 are Initialization Vectory so 8+16=24 //Thus to seek to length of file minus 24 bits vFile.seek(vFile.length() - 24); vFile.readFully(vInitVec); vFile.seek(0); File tmpFile = new File(inFile.getAbsolutePath() + ".tmpEncryption.file"); RandomAccessFile vTmpFile = new RandomAccessFile(tmpFile, "rw"); for (int i = 0; i < (vFile.length() - 24); ++i) { vTmpFile.write(vFile.readByte()); } vFile.close(); vTmpFile.close(); inFile.delete(); tmpFile.renameTo(inFile); Db("got salt " + Hex.encodeHexString(vSalt)); Db("got initvector :" + Hex.encodeHexString(vInitVec)); /* Derive the key, given password and salt. */ // in order to do 256 bit crypto, you have to muck with the files for Java's "unlimted security" // The end user must also install them (not compiled in) so beware. // see here: // http://www.javamex.com/tutorials/cryptography/unrestricted_policy_files.shtml // PBKDF2WithHmacSHA1,Constructs secret keys using the Password-Based Key Derivation Function function //found in PKCS #5 v2.0. (PKCS #5: Password-Based Cryptography Standard) factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1"); KeySpec spec = new PBEKeySpec(vPassword.toCharArray(), vSalt, ITERATIONS, KEYLEN_BITS); tmp = factory.generateSecret(spec); secret = new SecretKeySpec(tmp.getEncoded(), "AES"); // Decrypt the message, given derived key and initialization vector. vDecipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); vDecipher.init(Cipher.DECRYPT_MODE, secret, new IvParameterSpec(vInitVec)); }
From source file:com.mirth.connect.server.controllers.DefaultConfigurationController.java
/** * Instantiates the encryptor and digester using the configuration properties. If the properties * are not found, reasonable defaults are used. * //from w w w . j a v a2 s .c om * @param provider * The provider to use (ex. BC) * @param keyStore * The keystore from which to load the secret encryption key * @param keyPassword * The secret key password * @throws Exception */ private void configureEncryption(Provider provider, KeyStore keyStore, char[] keyPassword) throws Exception { SecretKey secretKey = null; if (!keyStore.containsAlias(SECRET_KEY_ALIAS)) { logger.debug("encryption key not found, generating new one"); KeyGenerator keyGenerator = KeyGenerator.getInstance(encryptionConfig.getEncryptionAlgorithm(), provider); keyGenerator.init(encryptionConfig.getEncryptionKeyLength()); secretKey = keyGenerator.generateKey(); KeyStore.SecretKeyEntry entry = new KeyStore.SecretKeyEntry(secretKey); keyStore.setEntry(SECRET_KEY_ALIAS, entry, new KeyStore.PasswordProtection(keyPassword)); } else { logger.debug("found encryption key in keystore"); secretKey = (SecretKey) keyStore.getKey(SECRET_KEY_ALIAS, keyPassword); } /* * Now that we have a secret key, store it in the encryption settings so that we can use it * to encryption things client side. */ encryptionConfig.setSecretKey(secretKey.getEncoded()); encryptor = new KeyEncryptor(); encryptor.setProvider(provider); encryptor.setKey(secretKey); encryptor.setFormat(Output.BASE64); digester = new Digester(); digester.setProvider(provider); digester.setAlgorithm(encryptionConfig.getDigestAlgorithm()); digester.setFormat(Output.BASE64); }
From source file:com.emc.storageos.api.service.impl.resource.DisasterRecoveryService.java
/** * Get standby site configuration/* w ww . ja va 2 s . c om*/ * * @return SiteConfigRestRep standby site configuration. */ @GET @Consumes({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON }) @CheckPermission(roles = { Role.SECURITY_ADMIN, Role.RESTRICTED_SECURITY_ADMIN, Role.SYSTEM_ADMIN, Role.RESTRICTED_SYSTEM_ADMIN, Role.SYSTEM_MONITOR }) @Path("/localconfig") public SiteConfigRestRep getStandbyConfig() { log.info("Begin to get standby config"); String siteId = coordinator.getSiteId(); SecretKey key = apiSignatureGenerator.getSignatureKey(SignatureKeyType.INTERVDC_API); Site site = drUtil.getSiteFromLocalVdc(siteId); SiteConfigRestRep siteConfigRestRep = new SiteConfigRestRep(); siteConfigRestRep.setUuid(siteId); siteConfigRestRep.setVip(site.getVip()); siteConfigRestRep.setVip6(site.getVip6()); siteConfigRestRep.setSecretKey(new String(Base64.encodeBase64(key.getEncoded()), Charset.forName("UTF-8"))); siteConfigRestRep.setHostIPv4AddressMap(site.getHostIPv4AddressMap()); siteConfigRestRep.setHostIPv6AddressMap(site.getHostIPv6AddressMap()); siteConfigRestRep.setDbSchemaVersion(coordinator.getCurrentDbSchemaVersion()); siteConfigRestRep.setFreshInstallation(isFreshInstallation()); siteConfigRestRep.setClusterStable(isClusterStable()); siteConfigRestRep.setNodeCount(site.getNodeCount()); siteConfigRestRep.setState(site.getState().toString()); try { siteConfigRestRep.setSoftwareVersion( coordinator.getTargetInfo(RepositoryInfo.class).getCurrentVersion().toString()); } catch (Exception e) { log.error("Fail to get software version {}", e); } log.info("Return result: {}", siteConfigRestRep); return siteConfigRestRep; }
From source file:com.cloud.user.AccountManagerImpl.java
private String createUserSecretKey(long userId) { try {//w ww. j a v a2 s. c o m UserVO updatedUser = _userDao.createForUpdate(); String encodedKey = null; int retryLimit = 10; UserVO userBySecretKey = null; do { KeyGenerator generator = KeyGenerator.getInstance("HmacSHA1"); SecretKey key = generator.generateKey(); encodedKey = Base64.encodeBase64URLSafeString(key.getEncoded()); userBySecretKey = _userDao.findUserBySecretKey(encodedKey); retryLimit--; } while ((userBySecretKey != null) && (retryLimit >= 0)); if (userBySecretKey != null) { return null; } updatedUser.setSecretKey(encodedKey); _userDao.update(userId, updatedUser); return encodedKey; } catch (NoSuchAlgorithmException ex) { s_logger.error("error generating secret key for user id=" + userId, ex); } return null; }
From source file:com.cloud.user.AccountManagerImpl.java
private String createUserApiKey(long userId) { try {//from w w w.jav a 2 s . co m UserVO updatedUser = _userDao.createForUpdate(); String encodedKey = null; Pair<User, Account> userAcct = null; int retryLimit = 10; do { // FIXME: what algorithm should we use for API keys? KeyGenerator generator = KeyGenerator.getInstance("HmacSHA1"); SecretKey key = generator.generateKey(); encodedKey = Base64.encodeBase64URLSafeString(key.getEncoded()); userAcct = _accountDao.findUserAccountByApiKey(encodedKey); retryLimit--; } while ((userAcct != null) && (retryLimit >= 0)); if (userAcct != null) { return null; } updatedUser.setApiKey(encodedKey); _userDao.update(userId, updatedUser); return encodedKey; } catch (NoSuchAlgorithmException ex) { s_logger.error("error generating secret key for user id=" + userId, ex); } return null; }
From source file:com.emc.storageos.api.service.impl.resource.DisasterRecoveryService.java
/** * Prepare all sites related info for synchronizing them from master to be added or resumed standby site * * @param standbySites All standby sites * @param ipsecKey The cluster ipsec key * @param targetStandbyUUID The uuid of the target standby * @param targetStandbyDataRevision The data revision of the target standby * @return SiteConfigParam all the sites configuration *//*from ww w .j a v a 2 s .com*/ private SiteConfigParam prepareSiteConfigParam(List<Site> standbySites, String ipsecKey, String targetStandbyUUID, long targetStandbyDataRevision, long vdcConfigVersion, SecretKey secretKey) { log.info("Preparing to sync sites info among to be added/resumed standby site..."); Site active = drUtil.getActiveSite(); SiteConfigParam configParam = new SiteConfigParam(); SiteParam activeSite = new SiteParam(); siteMapper.map(active, activeSite); activeSite.setIpsecKey(ipsecKey); log.info(" active site info:{}", activeSite.toString()); configParam.setActiveSite(activeSite); List<SiteParam> standbySitesParam = new ArrayList<>(); for (Site standby : standbySites) { SiteParam standbyParam = new SiteParam(); siteMapper.map(standby, standbyParam); standbyParam.setSecretKey( new String(Base64.encodeBase64(secretKey.getEncoded()), Charset.forName("UTF-8"))); if (standby.getUuid().equals(targetStandbyUUID)) { log.info("Set data revision for site {} to {}", standby.getUuid(), targetStandbyDataRevision); standbyParam.setDataRevision(targetStandbyDataRevision); } standbySitesParam.add(standbyParam); log.info(" standby site info:{}", standbyParam.toString()); } configParam.setStandbySites(standbySitesParam); configParam.setVdcConfigVersion(vdcConfigVersion); // Need set stanby's NTP same as primary, so standby time is consistent with primary after reboot // It's because time inconsistency between primary and standby will cause db rebuild issue: COP-17965 PropertyInfoExt targetPropInfo = coordinator.getTargetInfo(PropertyInfoExt.class); String ntpServers = targetPropInfo.getProperty(NTPSERVERS); log.info(" active site ntp servers: {}", ntpServers); configParam.setNtpServers(ntpServers); return configParam; }
From source file:org.geoserver.security.GeoServerSecurityManager.java
/** * Determines if strong encryption is available. * <p>// w ww . jav a2s . co m * This method does the determination by trying to encrypt a value with AES 256 Bit encryption. * </p> * * @return True if strong encryption avaialble, otherwise false. */ public boolean isStrongEncryptionAvailable() { if (strongEncryptionAvaialble != null) return strongEncryptionAvaialble; KeyGenerator kgen; try { kgen = KeyGenerator.getInstance("AES"); kgen.init(256); SecretKey skey = kgen.generateKey(); byte[] raw = skey.getEncoded(); SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES"); Cipher cipher = Cipher.getInstance("AES"); cipher.init(Cipher.ENCRYPT_MODE, skeySpec); cipher.doFinal("This is just an example".getBytes()); strongEncryptionAvaialble = true; LOGGER.info("Strong cryptograhpy is available"); } catch (InvalidKeyException e) { strongEncryptionAvaialble = false; LOGGER.warning("Strong cryptograhpy is NOT available" + "\nDownload and install of policy files recommended" + "\nfrom http://www.oracle.com/technetwork/java/javase/downloads/jce-6-download-429243.html"); } catch (Exception ex) { LOGGER.log(Level.WARNING, "Strong cryptograhpy is NOT available, unexpected error", ex); strongEncryptionAvaialble = false; //should not happen } return strongEncryptionAvaialble; }
From source file:org.apache.hadoop.yarn.server.resourcemanager.recovery.TestRMStateStore.java
void testRMAppStateStore(RMStateStoreHelper stateStoreHelper) throws Exception { long submitTime = System.currentTimeMillis(); Configuration conf = new YarnConfiguration(); RMStateStore store = stateStoreHelper.getRMStateStore(); TestDispatcher dispatcher = new TestDispatcher(); store.setRMDispatcher(dispatcher);/*from ww w . jav a 2 s .com*/ AMRMTokenSecretManager appTokenMgr = new AMRMTokenSecretManager(conf); ClientToAMTokenSecretManagerInRM clientToAMTokenMgr = new ClientToAMTokenSecretManagerInRM(); ApplicationAttemptId attemptId1 = ConverterUtils .toApplicationAttemptId("appattempt_1352994193343_0001_000001"); ApplicationId appId1 = attemptId1.getApplicationId(); storeApp(store, appId1, submitTime); // create application token and client token key for attempt1 Token<AMRMTokenIdentifier> appAttemptToken1 = generateAMRMToken(attemptId1, appTokenMgr); HashSet<Token<?>> attemptTokenSet1 = new HashSet<Token<?>>(); attemptTokenSet1.add(appAttemptToken1); SecretKey clientTokenKey1 = clientToAMTokenMgr.createMasterKey(attemptId1); ContainerId containerId1 = storeAttempt(store, attemptId1, "container_1352994193343_0001_01_000001", appAttemptToken1, clientTokenKey1, dispatcher); String appAttemptIdStr2 = "appattempt_1352994193343_0001_000002"; ApplicationAttemptId attemptId2 = ConverterUtils.toApplicationAttemptId(appAttemptIdStr2); // create application token and client token key for attempt2 Token<AMRMTokenIdentifier> appAttemptToken2 = generateAMRMToken(attemptId2, appTokenMgr); HashSet<Token<?>> attemptTokenSet2 = new HashSet<Token<?>>(); attemptTokenSet2.add(appAttemptToken2); SecretKey clientTokenKey2 = clientToAMTokenMgr.createMasterKey(attemptId2); ContainerId containerId2 = storeAttempt(store, attemptId2, "container_1352994193343_0001_02_000001", appAttemptToken2, clientTokenKey2, dispatcher); ApplicationAttemptId attemptIdRemoved = ConverterUtils .toApplicationAttemptId("appattempt_1352994193343_0002_000001"); ApplicationId appIdRemoved = attemptIdRemoved.getApplicationId(); storeApp(store, appIdRemoved, submitTime); storeAttempt(store, attemptIdRemoved, "container_1352994193343_0002_01_000001", null, null, dispatcher); RMApp mockRemovedApp = mock(RMApp.class); HashMap<ApplicationAttemptId, RMAppAttempt> attempts = new HashMap<ApplicationAttemptId, RMAppAttempt>(); ApplicationSubmissionContext context = new ApplicationSubmissionContextPBImpl(); context.setApplicationId(appIdRemoved); when(mockRemovedApp.getSubmitTime()).thenReturn(submitTime); when(mockRemovedApp.getApplicationSubmissionContext()).thenReturn(context); when(mockRemovedApp.getAppAttempts()).thenReturn(attempts); RMAppAttempt mockRemovedAttempt = mock(RMAppAttempt.class); when(mockRemovedAttempt.getAppAttemptId()).thenReturn(attemptIdRemoved); attempts.put(attemptIdRemoved, mockRemovedAttempt); store.removeApplication(mockRemovedApp); // let things settle down Thread.sleep(1000); store.close(); // load state store = stateStoreHelper.getRMStateStore(); RMState state = store.loadState(); Map<ApplicationId, ApplicationState> rmAppState = state.getApplicationState(); ApplicationState appState = rmAppState.get(appId1); // app is loaded assertNotNull(appState); // app is loaded correctly assertEquals(submitTime, appState.getSubmitTime()); // submission context is loaded correctly assertEquals(appId1, appState.getApplicationSubmissionContext().getApplicationId()); ApplicationAttemptState attemptState = appState.getAttempt(attemptId1); // attempt1 is loaded correctly assertNotNull(attemptState); assertEquals(attemptId1, attemptState.getAttemptId()); // attempt1 container is loaded correctly assertEquals(containerId1, attemptState.getMasterContainer().getId()); // attempt1 applicationToken is loaded correctly HashSet<Token<?>> savedTokens = new HashSet<Token<?>>(); savedTokens.addAll(attemptState.getAppAttemptCredentials().getAllTokens()); assertEquals(attemptTokenSet1, savedTokens); // attempt1 client token master key is loaded correctly assertArrayEquals(clientTokenKey1.getEncoded(), attemptState.getAppAttemptCredentials().getSecretKey(RMStateStore.AM_CLIENT_TOKEN_MASTER_KEY_NAME)); attemptState = appState.getAttempt(attemptId2); // attempt2 is loaded correctly assertNotNull(attemptState); assertEquals(attemptId2, attemptState.getAttemptId()); // attempt2 container is loaded correctly assertEquals(containerId2, attemptState.getMasterContainer().getId()); // attempt2 applicationToken is loaded correctly savedTokens.clear(); savedTokens.addAll(attemptState.getAppAttemptCredentials().getAllTokens()); assertEquals(attemptTokenSet2, savedTokens); // attempt2 client token master key is loaded correctly assertArrayEquals(clientTokenKey2.getEncoded(), attemptState.getAppAttemptCredentials().getSecretKey(RMStateStore.AM_CLIENT_TOKEN_MASTER_KEY_NAME)); // assert store is in expected state after everything is cleaned assertTrue(stateStoreHelper.isFinalStateValid()); store.close(); }