Example usage for org.apache.shiro.util ByteSource toBase64

List of usage examples for org.apache.shiro.util ByteSource toBase64

Introduction

In this page you can find the example usage for org.apache.shiro.util ByteSource toBase64.

Prototype

String toBase64();

Source Link

Document

Returns the <a href="http://en.wikipedia.org/wiki/Base64">Base 64</a>-formatted String representation of the underlying wrapped byte array.

Usage

From source file:br.com.criativasoft.opendevice.restapi.auth.AesRuntimeCipher.java

License:Open Source License

/**
 * Encript text// ww  w. ja  v a 2 s.  co  m
 * If you encrypt the same text with the same key twice, you will get two different encrypted texts.
 * @param text
 * @return encrypted text in base64 format
 */
public String encript(String text) {
    ByteSource encrypt = cipher.encrypt(text.getBytes(), key);
    return encrypt.toBase64();
}

From source file:com.ning.billing.tenant.dao.DefaultTenantDao.java

License:Apache License

@Override
public void create(final TenantModelDao entity, final InternalCallContext context) throws TenantApiException {
    // Create the salt and password
    final ByteSource salt = rng.nextBytes();
    // Hash the plain-text password with the random salt and multiple iterations and then Base64-encode the value (requires less space than Hex)
    final String hashedPasswordBase64 = new SimpleHash(KillbillCredentialsMatcher.HASH_ALGORITHM_NAME,
            entity.getApiSecret(), salt, KillbillCredentialsMatcher.HASH_ITERATIONS).toBase64();

    transactionalSqlDao.execute(new EntitySqlDaoTransactionWrapper<Void>() {
        @Override/*from  w ww.ja  v  a 2 s.c o m*/
        public Void inTransaction(final EntitySqlDaoWrapperFactory<EntitySqlDao> entitySqlDaoWrapperFactory)
                throws Exception {
            final TenantModelDao tenantModelDaoWithSecret = new TenantModelDao(entity.getId(),
                    context.getCreatedDate(), context.getUpdatedDate(), entity.getExternalKey(),
                    entity.getApiKey(), hashedPasswordBase64, salt.toBase64());
            entitySqlDaoWrapperFactory.become(TenantSqlDao.class).create(tenantModelDaoWithSecret, context);
            return null;
        }
    });
}

From source file:com.streamreduce.util.SecurityUtil.java

License:Apache License

/**
 * Returns encrypted password using given key
 *
 * @param password password to encrypt in plain text
 * @param key      the encryption key//from w  w  w . j a  v  a  2 s.  co  m
 * @return encrypted password in base64 encoding
 */
public static String encryptPassword(String password, byte[] key) {
    AesCipherService cipherService = new AesCipherService();
    ByteSource encrypted = cipherService.encrypt(password.getBytes(), key);
    return encrypted.toBase64();
}

From source file:com.tensorwrench.shiro.realm.MongoUserPasswordRealm.java

License:Apache License

/**
 * Creates a user credential suitable for use with this realm.  Intended for
 * creating the credentials to be inserted into the collection for later use.
 * // ww  w.  j  a v  a2  s  . c  o  m
 */
public DBObject createUserCredentials(String username, String plainTextPassword) {
    ByteSource salt = rng.nextBytes();

    BasicDBObject obj = new BasicDBObject();
    obj.put("name", username);
    obj.put("password", new Sha256Hash(plainTextPassword, salt, hashIterations).toBase64());
    obj.put("salt", salt.toBase64());
    obj.put("algorithm", Sha256Hash.ALGORITHM_NAME);
    obj.put("hashIterations", hashIterations);
    return obj;
}

From source file:de.elomagic.mag.utils.SimpleCrypt.java

License:Apache License

public static String encrypt(String decrypted) throws IOException {
    try {/*  ww w  .j a  v  a 2  s .c  om*/
        byte[] secretBytes = CodecSupport.toBytes(decrypted, "utf-8");

        ByteSource encrypted = CIPHER.encrypt(secretBytes, getMasterKey());

        return "{" + encrypted.toBase64() + "}";
    } catch (Exception ex) {
        LOGGER.error(ex.getMessage(), ex);
        throw (ex);
    }
}

From source file:net.noday.cat.service.impl.UserServiceImpl.java

License:Apache License

/**
 * ???salt?1024 sha-1 hash//from  w w w . ja v a2s . c om
 */
private void entryptPassword(User user) {
    ByteSource salt = Digests.generateSalt(Digests.SALT_SIZE);
    user.setSalt(salt.toBase64());

    String hashPassword = Digests.sha256Hash(user.getPlainPassword(), salt, 1024);
    user.setPassword(hashPassword);
}

From source file:net.noday.core.utils.PasswordUtil.java

License:Apache License

public static void main(String[] args) {
    ByteSource salt = Digests.generateSalt(Digests.SALT_SIZE);
    String hashPassword = Digests.sha256Hash("yourPassword", salt, 1024);
    System.out.println("salt:" + salt.toBase64());
    System.out.println("password:" + hashPassword);
}

From source file:net.scran24.frontpage.server.services.GenUserServiceImpl.java

License:Apache License

@Override
public UserRecord autoCreateUser(final String survey_name) {
    if (survey_name.isEmpty())
        throw new RuntimeException("This feature is not applicable to system-wide users");

    try {/*from   w w w. j  av  a 2 s  . c o  m*/
        SurveyParameters parameters = dataStore.getSurveyParameters(survey_name);

        if (!parameters.allowGenUsers)
            throw new RuntimeException("Automatically generated user records are not allowed for this survey");

        final String counterName = survey_name + "_gen_user_counter";

        int counter = Integer.parseInt(dataStore.getGlobalValue(counterName).getOrElse("0"));

        StringBuilder psb = new StringBuilder();

        ByteSource bytes = rng.nextBytes(passwordLength);

        for (int i = 0; i < passwordLength; i++) {
            int index = ((int) (bytes.getBytes()[i]) + 128) % passwordChars.length();
            psb.append(passwordChars.charAt(index));
        }

        ByteSource salt = rng.nextBytes();

        String password = psb.toString();

        String passwordHashBase64 = new Sha256Hash(password, salt, 1024).toBase64();
        String passwordSaltBase64 = salt.toBase64();

        Set<String> roles = new HashSet<String>();
        roles.add("respondent");

        Set<String> permissions = new HashSet<String>();
        permissions.add("processSurvey:" + survey_name);

        int retries = 20;
        boolean addUserOk = false;
        String username = "";

        while (retries > 0) {
            counter++;
            username = survey_name + counter;

            try {
                dataStore.addUser(survey_name,
                        new SecureUserRecord(username, passwordHashBase64, passwordSaltBase64,
                                Option.<String>none(), Option.<String>none(), Option.<String>none(), roles,
                                permissions, new HashMap<String, String>()));
                addUserOk = true;
                break;
            } catch (DataStoreException | DuplicateKeyException e) {
                continue;
            }
        }

        if (!addUserOk)
            throw new RuntimeException("Could not find a unique user name in 20 attempts");

        dataStore.setGlobalValue(counterName, Integer.toString(counter));

        return new UserRecord(username, password, Option.<String>none(), Option.<String>none(),
                Option.<String>none(), new HashMap<String, String>());

    } catch (NumberFormatException e) {
        throw new RuntimeException(e);
    } catch (DataStoreException e) {
        throw new RuntimeException(e);
    }
}

From source file:net.scran24.staff.server.services.UploadUserInfoService.java

License:Apache License

private List<SecureUserRecord> mapToSecureUserRecords(List<UserRecord> userRecords, Set<String> roles,
        Set<String> permissions) {
    List<SecureUserRecord> result = new ArrayList<SecureUserRecord>();

    RandomNumberGenerator rng = new SecureRandomNumberGenerator();

    for (UserRecord r : userRecords) {
        ByteSource salt = rng.nextBytes();

        String passwordHashBase64 = new Sha256Hash(r.password, salt, 1024).toBase64();
        String passwordSaltBase64 = salt.toBase64();

        result.add(new SecureUserRecord(r.username, passwordHashBase64, passwordSaltBase64, r.name, r.email,
                r.phone, roles, permissions, r.customFields));
    }/*w w w.j a  v a  2  s . c o  m*/

    return result;
}

From source file:org.apache.camel.component.shiro.security.ShiroSecurityProcessor.java

License:Apache License

private void applySecurityPolicy(Exchange exchange) throws Exception {
    ByteSource encryptedToken;//ww w  . j  av  a2 s .  c o m

    // if we have username and password as headers then use them to create a token
    String username = exchange.getIn().getHeader(ShiroSecurityConstants.SHIRO_SECURITY_USERNAME, String.class);
    String password = exchange.getIn().getHeader(ShiroSecurityConstants.SHIRO_SECURITY_PASSWORD, String.class);
    if (username != null && password != null) {
        ShiroSecurityToken token = new ShiroSecurityToken(username, password);

        // store the token as header, either as base64 or as the object as-is
        if (policy.isBase64()) {
            ByteSource bytes = ShiroSecurityHelper.encrypt(token, policy.getPassPhrase(),
                    policy.getCipherService());
            String base64 = bytes.toBase64();
            exchange.getIn().setHeader(ShiroSecurityConstants.SHIRO_SECURITY_TOKEN, base64);
        } else {
            exchange.getIn().setHeader(ShiroSecurityConstants.SHIRO_SECURITY_TOKEN, token);
        }
        // and now remove the headers as we turned those into the token instead
        exchange.getIn().removeHeader(ShiroSecurityConstants.SHIRO_SECURITY_USERNAME);
        exchange.getIn().removeHeader(ShiroSecurityConstants.SHIRO_SECURITY_PASSWORD);
    }

    Object token = ExchangeHelper.getMandatoryHeader(exchange, ShiroSecurityConstants.SHIRO_SECURITY_TOKEN,
            Object.class);

    // we support the token in a number of ways
    if (token instanceof ShiroSecurityToken) {
        ShiroSecurityToken sst = (ShiroSecurityToken) token;
        encryptedToken = ShiroSecurityHelper.encrypt(sst, policy.getPassPhrase(), policy.getCipherService());
        // Remove unencrypted token + replace with an encrypted token
        exchange.getIn().removeHeader(ShiroSecurityConstants.SHIRO_SECURITY_TOKEN);
        exchange.getIn().setHeader(ShiroSecurityConstants.SHIRO_SECURITY_TOKEN, encryptedToken);
    } else if (token instanceof String) {
        String data = (String) token;
        if (policy.isBase64()) {
            byte[] bytes = Base64.decode(data);
            encryptedToken = ByteSource.Util.bytes(bytes);
        } else {
            encryptedToken = ByteSource.Util.bytes(data);
        }
    } else if (token instanceof ByteSource) {
        encryptedToken = (ByteSource) token;
    } else {
        throw new CamelExchangeException("Shiro security header " + ShiroSecurityConstants.SHIRO_SECURITY_TOKEN
                + " is unsupported type: " + ObjectHelper.classCanonicalName(token), exchange);
    }

    ByteSource decryptedToken = policy.getCipherService().decrypt(encryptedToken.getBytes(),
            policy.getPassPhrase());

    ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(decryptedToken.getBytes());
    ObjectInputStream objectInputStream = new ObjectInputStream(byteArrayInputStream);
    ShiroSecurityToken securityToken;
    try {
        securityToken = (ShiroSecurityToken) objectInputStream.readObject();
    } finally {
        IOHelper.close(objectInputStream, byteArrayInputStream);
    }

    Subject currentUser = SecurityUtils.getSubject();

    // Authenticate user if not authenticated
    try {
        authenticateUser(currentUser, securityToken);

        // Test whether user's role is authorized to perform functions in the permissions list
        authorizeUser(currentUser, exchange);
    } finally {
        if (policy.isAlwaysReauthenticate()) {
            currentUser.logout();
        }
    }
}