List of usage examples for org.apache.shiro.authc.credential DefaultPasswordService encryptPassword
public String encryptPassword(Object plaintext)
From source file:br.com.criativasoft.opendevice.middleware.persistence.dao.jpa.UserJPA.java
License:Open Source License
@Override public User createUser(Account account, String username, String password) { User user = new User(); user.setUsername(username);/* ww w. ja v a2 s . c o m*/ user.setPassword(password); //Encrypt DefaultPasswordService service = new DefaultPasswordService(); DefaultHashService hashService = (DefaultHashService) service.getHashService(); hashService.setHashIterations(1); user.setPassword(service.encryptPassword(user.getPassword())); UserAccount userAccount = new UserAccount(); userAccount.setOwner(account); account.getUserAccounts().add(userAccount); if (account.getId() <= 0) userAccount.setType(AccountType.ACCOUNT_MANAGER); else userAccount.setType(AccountType.USER); userAccount.setUser(user); ApiKey key = new ApiKey(); key.setKey(account.getUuid()); key.setAppName("ApplicationID"); key.setAccount(userAccount); userAccount.getKeys().add(key); user.getAccounts().add(userAccount); persist(user); return user; }
From source file:com.mycompany.shirofaces.SHA256.java
public static void main(String args[]) { RandomNumberGenerator rng = new SecureRandomNumberGenerator(); Object salt = rng.nextBytes(); String hashedPasswordBase64 = new Sha256Hash("juancho18", salt, 1024).toBase64(); Sha256Hash sha256Hash = new Sha256Hash("juancho18"); System.out.println("Clave sin salt: " + sha256Hash.toHex()); System.out.println("Clave con salt : " + hashedPasswordBase64); DefaultHashService hashService = new DefaultHashService(); hashService.setHashIterations(50000); // 500000 hashService.setHashAlgorithmName(Sha256Hash.ALGORITHM_NAME); hashService.setPrivateSalt(new SimpleByteSource("jumarome")); hashService.setGeneratePublicSalt(true); DefaultPasswordService passwordService = new DefaultPasswordService(); passwordService.setHashService(hashService); String salte = hashService.getPrivateSalt().toBase64(); String claveMaldita = passwordService.encryptPassword("unaep"); System.out.println("Miraaa: " + claveMaldita); System.out.println("private salt= " + salte); }
From source file:edu.eci.pdsw.aeci.seguridad.ShiroLoginBean.java
/** * //from w w w .j a v a2 s. com * @param password The password to encrypt * @return the password encrypted */ public static String generateHash(String password) { DefaultHashService hashService = new DefaultHashService(); hashService.setHashIterations(500000); hashService.setHashAlgorithmName(Sha256Hash.ALGORITHM_NAME); hashService.setPrivateSalt(new SimpleByteSource("myprivatesalt")); hashService.setGeneratePublicSalt(true); DefaultPasswordService passwordService = new DefaultPasswordService(); passwordService.setHashService(hashService); String encryptedPassword = passwordService.encryptPassword(password); return encryptedPassword; }
From source file:edu.eci.pdsw.samples.managedbeans.LogginBean.java
public static String generateHash(String password) { DefaultHashService hashService = new DefaultHashService(); hashService.setHashIterations(500000); // 500000 hashService.setHashAlgorithmName(Sha256Hash.ALGORITHM_NAME); // Same salt as in shiro.ini, but NOT base64-encoded!! hashService.setPrivateSalt(new SimpleByteSource("myprivatesalt")); hashService.setGeneratePublicSalt(true); DefaultPasswordService passwordService = new DefaultPasswordService(); passwordService.setHashService(hashService); String encryptedPassword = passwordService.encryptPassword(password); return encryptedPassword; }
From source file:edu.eci.pdsw.samples.persistence.mybatisimpl.MyBatisDAOSolicitud.java
License:Open Source License
public static String generateHash(String password) { DefaultHashService hashService = new DefaultHashService(); hashService.setHashIterations(500000); // 500000 hashService.setHashAlgorithmName(Sha256Hash.ALGORITHM_NAME); // Same salt as in shiro.ini, but NOT base64-encoded!! hashService.setPrivateSalt(new SimpleByteSource("myprivatesalt")); hashService.setGeneratePublicSalt(true); DefaultPasswordService passwordService = new DefaultPasswordService(); passwordService.setHashService(hashService); String encryptedPassword = passwordService.encryptPassword(password); return encryptedPassword; }
From source file:io.opendevice.sonoff.SonOffRest.java
License:Open Source License
private void createDeviceAccount(String odevKey, String deviceID, String deviceApiKey) { Injector injector = GuiceInjectProvider.getInjector(); AccountDao accountDao = injector.getProvider(AccountDao.class).get(); UserDao userDao = injector.getProvider(UserDao.class).get(); Account account = accountDao.getAccountByApiKey(odevKey); if (account == null) { throw new NotFoundException("Account not found !"); }/*from www.j a v a 2s . c o m*/ ApiKey key = accountDao.findKey("SonOff", deviceApiKey); if (key == null) { BaseDeviceManager.getInstance().transactionBegin(); log.info("Creating new User/Key for Sonoff : " + deviceID); //Encrypt DefaultPasswordService service = new DefaultPasswordService(); DefaultHashService hashService = (DefaultHashService) service.getHashService(); hashService.setHashIterations(1); key = new ApiKey("SonOff", deviceApiKey); User user = new User("SonOff-" + deviceID, deviceApiKey); user.setPassword(service.encryptPassword(user.getPassword())); UserAccount userAccount = new UserAccount(); userAccount.setType(AccountType.DEVICE); userAccount.setOwner(account); userAccount.setUser(user); userAccount.getKeys().add(key); user.getAccounts().add(userAccount); key.setAccount(userAccount); userDao.persist(user); BaseDeviceManager.getInstance().transactionEnd(); } }
From source file:net.maritimecloud.portal.infrastructure.security.shiro.MaritimeCloudIdentityRealmTest.java
License:Apache License
@Test public void testSomeMethod() { // ApplicationServiceRegistry.identityApplicationService(); String submittedPlaintextPassword = "secret"; DefaultPasswordService passwordService = new DefaultPasswordService(); ((DefaultHashService) passwordService.getHashService()).setHashAlgorithmName("SHA-512"); String encryptedValue = passwordService.encryptPassword(submittedPlaintextPassword); System.out.println("" + encryptedValue); }
From source file:uk.ac.ox.it.ords.api.user.resources.UserResource.java
License:Apache License
@ApiOperation(value = "Updates a user", notes = "") @ApiResponses(value = { @ApiResponse(code = 200, message = "User successfully updated."), @ApiResponse(code = 400, message = "Invalid User supplied."), @ApiResponse(code = 403, message = "Not authorized to update this user."), @ApiResponse(code = 404, message = "User not found.") }) // //ww w . j a v a 2 s . c om // These are used by upstream gateways; including them here makes it easier to use an API portal // @ApiImplicitParams({ @ApiImplicitParam(name = "Version", value = "API version number", required = false, dataType = "string", paramType = "header"), @ApiImplicitParam(name = "Authorization", value = "API key", required = false, dataType = "string", paramType = "header"), }) @Path("/{id}") @PUT public Response updateUser(@PathParam("id") final int id, User user) throws Exception { // // Check auth // // No user if (SecurityUtils.getSubject().getPrincipal() == null) { return Response.status(403).build(); } // Modify-self if (SecurityUtils.getSubject().getPrincipal().equals(user.getPrincipalName())) { if (!SecurityUtils.getSubject().isPermitted(UserPermissions.USER_MODIFY_SELF)) { return Response.status(403).build(); } } else { // Modify-other if (!SecurityUtils.getSubject().isPermitted(UserPermissions.USER_MODIFY_ALL)) { return Response.status(403).build(); } } // // Does the original User object exist? // User originalUser = UserService.Factory.getInstance().getUser(id); if (originalUser == null) { return Response.status(404).build(); } // // Check for side-attack // if (user.getUserId() != id) { return Response.status(400).build(); } // // Validate // if (!UserService.Factory.getInstance().validate(user)) { return Response.status(400).build(); } // // Re-fill values that cannot be updated via User API // user.setStatus(originalUser.getStatus()); user.setToken(originalUser.getToken()); user.setVerificationUuid(originalUser.getVerificationUuid()); // // If the passwordRequest field is filled in, generate a new // token // if (user.getPasswordRequest() != null && !user.getPasswordRequest().isEmpty()) { DefaultPasswordService passwordService = new DefaultPasswordService(); user.setToken(passwordService.encryptPassword(user.getPasswordRequest())); UserAuditService.Factory.getInstance().createPasswordChangeRecord(user); } // // Update the User // UserService.Factory.getInstance().updateUser(user); return Response.ok().build(); }
From source file:uk.ac.ox.it.ords.api.user.resources.UserResource.java
License:Apache License
@ApiOperation(value = "Creates a user") @ApiResponses(value = {//from w w w. j a v a2 s. c om @ApiResponse(code = 201, message = "User successfully created.", responseHeaders = @ResponseHeader(name = "Location", description = "The URI of the user", response = URI.class)), @ApiResponse(code = 400, message = "Invalid user details."), @ApiResponse(code = 403, message = "Not authorized to create a user.") }) // // These are used by upstream gateways; including them here makes it easier to use an API portal // @ApiImplicitParams({ @ApiImplicitParam(name = "Version", value = "API version number", required = false, dataType = "string", paramType = "header"), @ApiImplicitParam(name = "Authorization", value = "API key", required = false, dataType = "string", paramType = "header"), }) @Path("/") @POST @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) public Response createUser(User user, @Context UriInfo uriInfo, @ApiParam(value = "Invitation code to verify, if user is being created in response to an invitation from an existing user", required = false) @QueryParam("i") final String invitationCode) throws Exception { // // We must have a logged-in user unless we allow sign ups // if (!MetaConfiguration.getConfiguration().getBoolean("ords.allow.signups")) { if (!SecurityUtils.getSubject().isAuthenticated()) { return Response.status(401).build(); } } // // The special anonymous user provides public permissions; // if this is the principal, we treat them as unauthenticated // if (SecurityUtils.getSubject().getPrincipal() != null) { if (SecurityUtils.getSubject().getPrincipal().equals("anonymous")) { UserAuditService.Factory.getInstance().createNotAuthRecord("User:query", "anonymous"); return Response.status(401).build(); } } // // If the principal is null, set it to the current subject // if (SecurityUtils.getSubject().getPrincipal() != null) { if (user.getPrincipalName() == null || user.getPrincipalName() == "") { user.setPrincipalName(SecurityUtils.getSubject().getPrincipal().toString()); } } // // If we don't have an email address given, or a principal name, // check if there is an invitation code that matches // // If there is, then lets look up the email address and add it to the user object // // This scenario takes place where we support invites and self-signup without // SSO; in this case we only get the invite code with no user principal available // if (user.getPrincipalName() == null || user.getPrincipalName() == "") { if (user.getEmail() == null || user.getEmail().isEmpty()) { if (invitationCode != null) { if (MetaConfiguration.getConfiguration().getBoolean("ords.allow.signups")) { String email = InvitationCodeService.Factory.getInstance() .getUserByInvitationCode(invitationCode); user.setEmail(email); } } } } // // If the principal is null and the subject are null, set the principal to be the email address // if (user.getPrincipalName() == null || user.getPrincipalName() == "") { user.setPrincipalName(user.getEmail()); } // // Check the principal name and the user match if we're not supporting self-sign-up // if (!MetaConfiguration.getConfiguration().getBoolean("ords.allow.signups")) { if (!user.getPrincipalName().equals(SecurityUtils.getSubject().getPrincipal())) { return Response.status(400).build(); } } // // Check there isn't another user with this email address. // if (UserService.Factory.getInstance().getUserByEmailAddress(user.getEmail()) != null) { return Response.status(409).build(); } // // Override with new user defaults // user.setStatus(User.AccountStatus.PENDING_EMAIL_VERIFICATION.name()); user.setPrincipalType(""); // Generate the OdbcUser name from the principal String odbcUser = user.getPrincipalName().replace("@", "").replace(".", ""); user.setOdbcUser(odbcUser); // // Generate a password hash, if a password was requested // if (user.getPasswordRequest() != null && !user.getPasswordRequest().isEmpty()) { DefaultPasswordService passwordService = new DefaultPasswordService(); user.setToken(passwordService.encryptPassword(user.getPasswordRequest())); } // // If we have an invitation code, look it up // if (invitationCode != null) { // // Get the code // String principalName = InvitationCodeService.Factory.getInstance() .getUserByInvitationCode(invitationCode); // // No match // if (principalName == null) { return Response.status(400).build(); } // // Does the principal name matching the code also match the principal name of the user we're creating? // if (!principalName.equals(user.getPrincipalName())) { return Response.status(400).build(); } // // Create the user, and verify their role at the same time // user.setStatus(User.AccountStatus.VERIFIED.name()); UserService.Factory.getInstance().createUser(user); UserRoleService.Factory.getInstance().verifyUser(user); } else { // // Validate the request // if (!UserService.Factory.getInstance().validate(user)) { return Response.status(400).build(); } // // Create the user // UserService.Factory.getInstance().createUser(user); // // Send verification email // VerificationEmailService.Factory.getInstance().sendVerificationMessage(user); } // // Return 201 with location of User object // UserAuditService.Factory.getInstance().createSignupRecord(user); UriBuilder builder = uriInfo.getAbsolutePathBuilder(); builder.path(Integer.toString(user.getUserId())); return Response.created(builder.build()).build(); }