org.springframework.security.crypto.codec.Hex Java Examples

The following examples show how to use org.springframework.security.crypto.codec.Hex. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: RsaEncryptProvider.java    From mPaaS with Apache License 2.0 6 votes vote down vote up
/**
 * 随机生成密钥对
 * @throws NoSuchAlgorithmException
 */
public static void genKeyPair() throws NoSuchAlgorithmException {
    // KeyPairGenerator类用于生成公钥和私钥对,基于RSA算法生成对象
    KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("RSA");
    // 初始化密钥对生成器,密钥大小为96-1024位
    keyPairGen.initialize(1024,new SecureRandom());
    // 生成一个密钥对,保存在keyPair中
    KeyPair keyPair = keyPairGen.generateKeyPair();
    RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();   // 得到私钥
    RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();  // 得到公钥
    String publicKeyString = new String(Hex.encode(publicKey.getEncoded()));
    // 得到私钥字符串
    String privateKeyString = new String(Hex.encode((privateKey.getEncoded())));
    // 将公钥和私钥保存到Map
    //0表示公钥
    System.out.println("公钥 16进制:"+publicKeyString);
    //1表示私钥
    System.out.println("私钥 16进制:"+privateKeyString);
}
 
Example #2
Source File: RsaEncryptProvider.java    From mPass with Apache License 2.0 6 votes vote down vote up
/**
 * 随机生成密钥对
 * @throws NoSuchAlgorithmException
 */
public static void genKeyPair() throws NoSuchAlgorithmException {
    // KeyPairGenerator类用于生成公钥和私钥对,基于RSA算法生成对象
    KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("RSA");
    // 初始化密钥对生成器,密钥大小为96-1024位
    keyPairGen.initialize(1024,new SecureRandom());
    // 生成一个密钥对,保存在keyPair中
    KeyPair keyPair = keyPairGen.generateKeyPair();
    RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();   // 得到私钥
    RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();  // 得到公钥
    String publicKeyString = new String(Hex.encode(publicKey.getEncoded()));
    // 得到私钥字符串
    String privateKeyString = new String(Hex.encode((privateKey.getEncoded())));
    // 将公钥和私钥保存到Map
    //0表示公钥
    System.out.println("公钥 16进制:"+publicKeyString);
    //1表示私钥
    System.out.println("私钥 16进制:"+privateKeyString);
}
 
Example #3
Source File: User.java    From DataHubSystem with GNU Affero General Public License v3.0 6 votes vote down vote up
public void setPassword (String password)
{
   // Encrypt password with MessageDigest
   PasswordEncryption encryption = PasswordEncryption.MD5;
   setPasswordEncryption (encryption);
   if (encryption != PasswordEncryption.NONE) // when configurable
   {
      try
      {
         MessageDigest md =
            MessageDigest.getInstance (encryption.getAlgorithmKey ());
         password =
            new String (
                  Hex.encode (md.digest (password.getBytes ("UTF-8"))));
      }
      catch (Exception e)
      {
         throw new UserBadEncryptionException (
            "There was an error while encrypting password of user " +
               getUsername (), e);
      }
   }
   this.password = password;
}
 
Example #4
Source File: StringEncryptorHolder.java    From summerframework with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) {

        TextEncryptor encryptor =
            Encryptors.delux("pass", new String(Hex.encode("salt".getBytes(Charset.forName("utf-8")))));
        System.out.println(encryptor.encrypt("sadfsadfasfsadf"));
        System.out.println(encryptor.encrypt("sadfsadfasfsadf"));
        System.out.println(encryptor.decrypt(encryptor.encrypt("这是密码")));
    }
 
Example #5
Source File: EncryptPassword.java    From DataHubSystem with GNU Affero General Public License v3.0 6 votes vote down vote up
public static String encrypt (String password, PasswordEncryption encryption)
   throws EncryptPasswordException
{
   if (encryption != PasswordEncryption.NONE) // when configurable
   {
      try
      {
         MessageDigest md =
            MessageDigest.getInstance (encryption.getAlgorithmKey ());
         password =
            new String (
                  Hex.encode (md.digest (password.getBytes ("UTF-8"))));
      }
      catch (Exception e)
      {
         throw new EncryptPasswordException (
            "There was an error while encrypting password.", e);
      }
   }
   return password;
}
 
Example #6
Source File: AdditionalService.java    From alf.io with GNU General Public License v3.0 6 votes vote down vote up
public String getChecksum() {
    try {
        MessageDigest digest = MessageDigest.getInstance("SHA-256");
        digest.update(Boolean.toString(fixPrice).getBytes(StandardCharsets.UTF_8));
        digest.update(Integer.toString(ordinal).getBytes(StandardCharsets.UTF_8));
        digest.update(Integer.toString(availableQuantity).getBytes(StandardCharsets.UTF_8));
        digest.update(Integer.toString(maxQtyPerOrder).getBytes(StandardCharsets.UTF_8));
        digest.update(utcInception.toString().getBytes(StandardCharsets.UTF_8));
        digest.update(utcExpiration.toString().getBytes(StandardCharsets.UTF_8));
        digest.update(Optional.ofNullable(vat).map(BigDecimal::toString).orElse("").getBytes(StandardCharsets.UTF_8));
        digest.update(vatType.name().getBytes(StandardCharsets.UTF_8));
        digest.update(type.name().getBytes(StandardCharsets.UTF_8));
        if (supplementPolicy != null) {
            digest.update(supplementPolicy.name().getBytes(StandardCharsets.UTF_8));
        }
        return new String(Hex.encode(digest.digest()));
    } catch (NoSuchAlgorithmException e) {
        throw new IllegalStateException(e);
    }
}
 
Example #7
Source File: TokenUtils.java    From Spring with Apache License 2.0 5 votes vote down vote up
private static String computeSignature(UserDetails userDetails, long expires) {
	String signature = "";
	signature += (userDetails.getUsername()) + (":");
	signature += (expires) + (":");
	signature += (userDetails.getPassword()) + (":");
	signature += (TokenUtils.MAGIC_KEY);
	return new String(Hex.encode(MESSAGE_DIGEST.digest(signature.getBytes())));
}
 
Example #8
Source File: DockerServiceMock.java    From haven-platform with Apache License 2.0 5 votes vote down vote up
private String makeId() {
    synchronized (containers) {
        while(true) {
            byte[] arr = new byte[ID_LEN/2];
            ThreadLocalRandom.current().nextBytes(arr);
            char[] encode = Hex.encode(arr);
            String id = new String(encode);
            // this is unlikely, but if happened we got strange errors, because we check it
            if(!containers.containsKey(id)) {
                return id;
            }
        }
    }
}
 
Example #9
Source File: Encryptor.java    From greenbeans with Apache License 2.0 5 votes vote down vote up
public String decrypt(String data) {
	if (data == null) {
		return null;
	}
	byte[] decodedBytes = Hex.decode(data);
	byte[] decryptedBytes = encryptor.decrypt(decodedBytes);
	return new String(decryptedBytes, StandardCharsets.UTF_8);
}
 
Example #10
Source File: SystemService.java    From DataHubSystem with GNU Affero General Public License v3.0 5 votes vote down vote up
@PreAuthorize ("hasRole('ROLE_SYSTEM_MANAGER')")
@Transactional (readOnly=false, propagation=Propagation.REQUIRED)
@Caching (evict = {
   @CacheEvict (value = "user", allEntries = true),
   @CacheEvict (value = "userByName", allEntries = true)})
public void changeRootPassword (String new_pwd, String old_pwd)
{
   User root =
      userDao.getByName (
            cfgManager.getAdministratorConfiguration ().getName ());
   PasswordEncryption encryption = root.getPasswordEncryption ();
   if (encryption != PasswordEncryption.NONE) 
   {
      try
      {
         MessageDigest md = MessageDigest.getInstance(
               encryption.getAlgorithmKey());
         old_pwd = new String(
               Hex.encode(md.digest(old_pwd.getBytes("UTF-8"))));
      }
      catch (Exception e)
      {
         throw new UserBadEncryptionException (
               "There was an error while encrypting password of root user",
               e);
      }
   }
   if ( (old_pwd == null) || ("".equals (old_pwd)) ||
      ( !root.getPassword ().equals (old_pwd)))
      throw new SecurityException ("Wrong password.");

   if ( (new_pwd == null) || "".equals (new_pwd.trim ()))
      throw new SecurityException ("New password cannot be empty.");

   String password = new_pwd.trim ();
   root.setPassword (password);
   userDao.update (root);
}
 
Example #11
Source File: DefaultTextEncryptor.java    From entando-core with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Returns a Base64 string composed by the salt followed by the encrypted
 * data.
 */
@Override
public String encrypt(String plainText) {

    // default StringKeyGenerator returns a 8 bytes hex-encoded string
    String salt = KeyGenerators.string().generateKey();

    BytesEncryptor encryptor = Encryptors.standard(key, salt);
    byte[] encrypted = encryptor.encrypt(plainText.getBytes());

    byte[] saltAndSecret = ArrayUtils.addAll(Hex.decode(salt), encrypted);
    return Base64.getEncoder().encodeToString(saltAndSecret);
}
 
Example #12
Source File: DefaultTextEncryptor.java    From entando-core with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Returns decrypted text from a Base64 string composed by the salt followed
 * by the encrypted data.
 */
@Override
public String decrypt(String base64Data) {

    byte[] bytes = Base64.getDecoder().decode(base64Data);
    byte[] saltBytes = ArrayUtils.subarray(bytes, 0, 8);
    byte[] encryptedBytes = ArrayUtils.subarray(bytes, 8, bytes.length);

    String salt = new String(Hex.encode(saltBytes));
    BytesEncryptor encryptor = Encryptors.standard(key, salt);

    return new String(encryptor.decrypt(encryptedBytes));
}
 
Example #13
Source File: SecurityUtils.java    From spring-backend-boilerplate with Apache License 2.0 5 votes vote down vote up
public static String generateHexIdentity(String value) {
	try {
		if (md5MessageDigest != null) {
			return new String(Hex.encode(md5MessageDigest.digest(value.getBytes("utf-8"))));
		}
	} catch (UnsupportedEncodingException e) {
		e.printStackTrace();
	}
	return value;
}
 
Example #14
Source File: TOTPUtils.java    From spring-backend-boilerplate with Apache License 2.0 5 votes vote down vote up
/**
 * @param base32Key       base32 encoded key
 * @param timeStepInMills
 * @return
 */
public static String getGeneratedValue(String base32Key, long timeStepInMills) {
	// time step
	String hexKey = new String(Hex.encode(new Base32().decode(base32Key)));
	return TOTP.generateTOTP(hexKey,
							 Long.toHexString(System.currentTimeMillis() / timeStepInMills),
							 "6",
							 "HmacSHA1");
}
 
Example #15
Source File: NotificationManager.java    From alf.io with GNU General Public License v3.0 5 votes vote down vote up
private static String calculateChecksum(String recipient, String attachments, String subject, String text, String htmlRender)  {
    try {
        MessageDigest digest = MessageDigest.getInstance("SHA-256");
        digest.update(recipient.getBytes(StandardCharsets.UTF_8));
        digest.update(subject.getBytes(StandardCharsets.UTF_8));
        Optional.ofNullable(attachments).ifPresent(v -> digest.update(v.getBytes(StandardCharsets.UTF_8)));
        digest.update(text.getBytes(StandardCharsets.UTF_8));
        if(htmlRender != null) digest.update(htmlRender.getBytes(StandardCharsets.UTF_8));
        return new String(Hex.encode(digest.digest()));
    } catch (NoSuchAlgorithmException e) {
        throw new IllegalStateException(e);
    }
}
 
Example #16
Source File: InMemoryTokenStore.java    From spring-security-passwordless with Apache License 2.0 5 votes vote down vote up
@Override
public String create (String aUserId) {
  Assert.notNull(aUserId,"user id can't be null");
  byte bytes[] = new byte[TOKEN_BYTE_SIZE];
  random.nextBytes(bytes);
  String token = String.valueOf(Hex.encode(bytes));
  store.put(aUserId, token);
  return token;
}
 
Example #17
Source File: PasswordUtils.java    From fast-family-master with Apache License 2.0 5 votes vote down vote up
/**
 * 转md5 16进制数据
 *
 * @param data           元数据
 * @param salt           盐
 * @param hashIterations hash次数
 * @return
 */
public static String md5Hex(byte[] data, byte[] salt, int hashIterations) {
    MessageDigest digest = DigestUtils.getMd5Digest();
    if (salt != null) {
        digest.reset();
        digest.update(salt);
    }
    byte[] digestData = digest.digest(data);
    for (int i = 0; i < hashIterations; i++) {
        digest.reset();
        digestData = digest.digest(digestData);
    }
    return String.valueOf(Hex.encode(digestData));
}
 
Example #18
Source File: PasswordUtils.java    From fast-family-master with Apache License 2.0 5 votes vote down vote up
/**
 * 验证密码是否匹配
 *
 * @param originalPassword 原密码
 * @param encryptPassword  加密后密码
 * @param saltLength       盐长度
 * @return
 */
public static boolean matchPassword(String originalPassword, String encryptPassword,
                                    int saltLength, int hashIterations) {
    try {
        byte[] salt = Hex.decode(encryptPassword.substring(0, saltLength * 4));
        String md5HexStr = md5Hex(originalPassword.getBytes(), salt, hashIterations);
        return md5HexStr.equals(encryptPassword.substring(saltLength * 4));
    } catch (Exception e) {
        throw new NoAuthException("验证密码失败", e);
    }
}
 
Example #19
Source File: StringUtil.java    From ZenQuery with Apache License 2.0 5 votes vote down vote up
public static String hashWithSha256(String input) {
    String output = "";

    try {
        MessageDigest messageDigest = MessageDigest.getInstance("SHA-256");
        messageDigest.update(input.getBytes("UTF-8"));
        output = new String(Hex.encode(messageDigest.digest()));
    } catch (Exception e) {
        logger.debug(e);
    }

    return output;
}
 
Example #20
Source File: SessionTokenUtils.java    From studio with GNU General Public License v3.0 5 votes vote down vote up
public static String computeSignature(String username, long expires) {
    StringBuilder signatureBuilder = new StringBuilder();
    signatureBuilder.append(username);
    signatureBuilder.append(":");
    signatureBuilder.append(expires);

    MessageDigest digest;
    try {
        digest = MessageDigest.getInstance("MD5");
    } catch (NoSuchAlgorithmException e) {
        throw new IllegalStateException("No MD5 algorithm available!");
    }

    return new String(Hex.encode(digest.digest(signatureBuilder.toString().getBytes())));
}
 
Example #21
Source File: TokenUtils.java    From boot-examples with Apache License 2.0 5 votes vote down vote up
public String computeSignature(UserDetails userDetails, long expires) {
    StringBuilder signatureBuilder = new StringBuilder();
    signatureBuilder.append(userDetails.getUsername()).append(":");
    signatureBuilder.append(expires).append(":");
    signatureBuilder.append(userDetails.getPassword()).append(":");
    signatureBuilder.append(TokenUtils.MAGIC_KEY);

    MessageDigest digest;
    try {
        digest = MessageDigest.getInstance("MD5");
    } catch (NoSuchAlgorithmException e) {
        throw new IllegalStateException("No MD5 algorithm available!");
    }
    return new String(Hex.encode(digest.digest(signatureBuilder.toString().getBytes())));
}
 
Example #22
Source File: RsaPublicKeyFilter.java    From mPaaS with Apache License 2.0 5 votes vote down vote up
/**
 * RSA publickey相关操作
 *
 * @param request
 * @param response
 * @param pubKey
 */
private void handleTenant(HttpServletRequest request,
                          HttpServletResponse response,
                          String pubKey) {
    if (RSA_KEY.equals(pubKey)) {
        if(base64PublicKey==null) {
            //publicCode base64 编码
            //由于配置文件中的RSA 密钥是Hex 编码,需要转换
            if (StringUtils.isNotBlank(systemConfig.getPublicCode())) {
                base64PublicKey= Base64.getEncoder().encodeToString(Hex.decode(systemConfig.getPublicCode()));
            }
        }
        response.setHeader(HEADER_PUBKEY, base64PublicKey);
    }
}
 
Example #23
Source File: RsaEncryptProvider.java    From mPass with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    //生成公钥和私钥

    String p = "30819f300d06092a864886f70d010101050003818d00308189028181009b44b604191d16ca3d47f7cddb0220535242eb54bc3b5391707ca568ce76fc22f251ab36c32a531eeb9c1222fc3e7f4a2a53eed609958a164f28a63a6bd6958b3d25d574bea89cd3ac37d85ef8f2f15d8dfc7d1dc442f166022250f058c9ac63491b7d67b79f9414a445d742ea40f95868bbbbf2f5f4dc868603aa655840f6f30203010001";
    String pr = "30820274020100300d06092a864886f70d01010105000482025e3082025a020100028181009b44b604191d16ca3d47f7cddb0220535242eb54bc3b5391707ca568ce76fc22f251ab36c32a531eeb9c1222fc3e7f4a2a53eed609958a164f28a63a6bd6958b3d25d574bea89cd3ac37d85ef8f2f15d8dfc7d1dc442f166022250f058c9ac63491b7d67b79f9414a445d742ea40f95868bbbbf2f5f4dc868603aa655840f6f30203010001027f527c2e35ff2174f9fb9440111c4804e43ecf4e35b5c9ce9b7526c2b8eaf64afc45bf1d35fa7881afeb7afe2797d99bc5cab6cc2ae8ec886f519e46b0c2993cd7e7c465b3b25741bd394442b29b0ef45c18430fb6363343f343f8fe2623b14857ac562c0dd2097b314ad22caff8e974473e8aab74280cc9d4e61f1515b75f41024100cb6a95ae12f3583a2e514bb75cb4ac1d3230fc094ef86a6ab3a0c4e9bed1058fd9159fc5897ee99509d73b835921294abac8738b28c2657fbc09f4b13c9479bf024100c367db20d8cdd381ffc5a34f643b5567cb90db7b7938b01c308897174b35f9956737192231b89198800dbaca95a4a82a7b7735973003828b246aafab1348c7cd02407eb2e0901015a9fa732707b629f40ed010971a24e21f30894d60f1c575a8d3820980c2875360cd349b70880d03d2f7d92805fa91cecd6652ed5876247ecb2c1902402b999dc43b7bd988b52845232ecb2a68497c9dec7404d90ec1298904f28c2d8f4f8374c13374ea4fabaae495d543f31ddf849ed988261057b99d706aec979db5024100b046eb05db41b88649c0995c0201191276c9495e293634f9ccc8f4e5e98969c4e79afb8b018afad1742fa2688da2ec1f0ef8578cdc7552d86eb8e443fbae9c76";
    RsaEncryptProvider rsaEncryptProvider = new RsaEncryptProvider(Hex.decode(pr), Hex.decode(p));
    //加密字符串
    String message = "1";
    String messageEn = rsaEncryptProvider.encrypt(message);
    System.out.println(message + "\t加密后的字符串为:" + messageEn);
    String messageDe = rsaEncryptProvider.decrypt(messageEn);
    System.out.println("还原后的字符串为:" + messageDe);
}
 
Example #24
Source File: RsaPublicKeyFilter.java    From mPass with Apache License 2.0 5 votes vote down vote up
/**
 * RSA publickey相关操作
 *
 * @param request
 * @param response
 * @param pubKey
 */
private void handleTenant(HttpServletRequest request,
                          HttpServletResponse response,
                          String pubKey) {
    if (RSA_KEY.equals(pubKey)) {
        if(base64PublicKey==null) {
            //publicCode base64 编码
            //由于配置文件中的RSA 密钥是Hex 编码,需要转换
            if (StringUtils.isNotBlank(systemConfig.getPublicCode())) {
                base64PublicKey= Base64.getEncoder().encodeToString(Hex.decode(systemConfig.getPublicCode()));
            }
        }
        response.setHeader(HEADER_PUBKEY, base64PublicKey);
    }
}
 
Example #25
Source File: MessageDigestPasswordEncoder.java    From lemon with Apache License 2.0 4 votes vote down vote up
private byte[] decode(CharSequence encodedPassword) {
    return Hex.decode(encodedPassword);
}
 
Example #26
Source File: MessageDigestPasswordEncoder.java    From lemon with Apache License 2.0 4 votes vote down vote up
private String encode(CharSequence rawPassword, byte[] salt) {
    byte[] digest = digest(rawPassword, salt);

    return new String(Hex.encode(digest));
}
 
Example #27
Source File: UserService.java    From DataHubSystem with GNU Affero General Public License v3.0 4 votes vote down vote up
@PreAuthorize ("isAuthenticated ()")
@Transactional (readOnly=false, propagation=Propagation.REQUIRED)
@Caching (evict = {
   @CacheEvict(value = "user", allEntries = true),
   @CacheEvict(value = "userByName", allEntries = true),
   @CacheEvict(value = "json_user", allEntries = true)})
public void selfChangePassword (String uuid, String old_password,
      String new_password) throws RootNotModifiableException,
      RequiredFieldMissingException, EmailNotSentException,
      UserBadOldPasswordException
{
   User u = userDao.read (uuid);
   checkRoot (u);

   //encrypt old password to compare
   PasswordEncryption encryption = u.getPasswordEncryption ();
   if (encryption != PasswordEncryption.NONE) // when configurable
   {
      try
      {
         MessageDigest md =
               MessageDigest.getInstance(encryption.getAlgorithmKey());
         old_password = new String(
               Hex.encode(md.digest(old_password.getBytes("UTF-8"))));
      }
      catch (Exception e)
      {
         throw new UserBadEncryptionException (
               "There was an error while encrypting password of user " +
                     u.getUsername (), e);
      }
   }

   if (! u.getPassword ().equals(old_password))
   {
      throw new UserBadOldPasswordException("Old password is not correct.");
   }

   u.setPassword (new_password);

   checkRequiredFields (u);
   userDao.update (u);
}
 
Example #28
Source File: ForceEncryptPassword.java    From DataHubSystem with GNU Affero General Public License v3.0 4 votes vote down vote up
@Override
public void execute (Database database) throws CustomChangeException
{
   try
   {
      JdbcConnection jdbc = (JdbcConnection) database.getConnection ();
      String sql;
      Statement statement;
      ResultSet resultSet;

      // Retrieve unencrypted user password
      sql = "SELECT LOGIN, PASSWORD FROM USERS " +
            "WHERE PASSWORD_ENCRYPTION = 'NONE'";
      statement = jdbc.createStatement ();
      HashMap<String, String> unencrypted_user = new HashMap<> ();
      resultSet = statement.executeQuery (sql);
      while (resultSet.next ())
      {
         unencrypted_user.put (resultSet.getString ("LOGIN"),
               resultSet.getString ("PASSWORD"));
      }
      resultSet.close ();
      statement.close ();

      // Encrypt user password and update user
      MessageDigest md = MessageDigest.getInstance ("MD5");
      sql = "UPDATE USERS SET PASSWORD_ENCRYPTION = 'MD5', PASSWORD = '%s'" +
            " WHERE LOGIN = '%s'";
      String query;
      String password;
      for (String login : unencrypted_user.keySet ())
      {
         password = unencrypted_user.get (login);
         password = new String (
               Hex.encode (md.digest (password.getBytes ("UTF-8"))));
         query = String.format (sql, password, login);
         statement = jdbc.createStatement ();
         int updated =  statement.executeUpdate (query);
         if (updated != 1)
         {
            LOGGER.warn(updated + " encryption update perform on user : " + login);
         }
         statement.close ();
      }
      unencrypted_user.clear ();
   }
   catch (Exception e)
   {
      throw new CustomChangeException (
            "An error occurred during forceEncryptPassword changelog", e);
   }
}
 
Example #29
Source File: DefaultAuthenticationProvider.java    From DataHubSystem with GNU Affero General Public License v3.0 4 votes vote down vote up
@Override
@Transactional (propagation=Propagation.REQUIRED)
public Authentication authenticate (Authentication authentication)
   throws AuthenticationException
{
   String username = (String) authentication.getPrincipal ();
   String password = (String) authentication.getCredentials ();
   String ip = "unknown";
   if (authentication.getDetails () instanceof WebAuthenticationDetails)
   {
      ip = ((WebAuthenticationDetails)authentication.getDetails ())
            .getRemoteAddress ();
   }
   LOGGER.info ("Connection attempted by '" + authentication.getName () +
         "' from " + ip);

   User user = userService.getUserNoCheck (username);
   if (user == null || user.isDeleted ())
   {
      throw new BadCredentialsException (errorMessage);
   }

   PasswordEncryption encryption = user.getPasswordEncryption ();
   if ( !encryption.equals (PasswordEncryption.NONE))
   {
      MessageDigest md;
      try
      {
         md = MessageDigest.getInstance (encryption.getAlgorithmKey ());
         password =
            new String (
                  Hex.encode (md.digest (password.getBytes ("UTF-8"))));
      }
      catch (NoSuchAlgorithmException | UnsupportedEncodingException e)
      {
         throw new BadCredentialsException ("Authentication process failed",
               e);
      }
   }

   if ( !user.getPassword ().equals (password))
   {
      LOGGER.warn (
            new Message (MessageType.USER, "Connection refused for '" +
                  username
                  + "' from " + ip +
                  " : error in login/password combination"));
      throw new BadCredentialsException (errorMessage);
   }
   
   for (AccessRestriction restriction : user.getRestrictions ())
   {
      LOGGER.warn ("Connection refused for '" + username +
            "' from " + ip + " : account is locked (" +
            restriction.getBlockingReason () + ")");
      throw new LockedException (restriction.getBlockingReason ());
   }
   
   LOGGER.info ("Connection success for '" + username + "' from " + ip);
   return new ValidityAuthentication (user, user.getAuthorities ());
}
 
Example #30
Source File: StubUserController.java    From DataHubSystem with GNU Affero General Public License v3.0 4 votes vote down vote up
@PreAuthorize("isAuthenticated ()")
@RequestMapping(value = "/users/{userid}", method = RequestMethod.PUT)
public int updateUserProfile(Principal principal,
		@RequestBody UserRequestBody body,
		@PathVariable(value = "userid") String userid) throws RequiredFieldMissingException, RootNotModifiableException {
	logger.info("******** updateUserProfile()");
	int responseCode = 0;
	User user = body.getUser();
	logger.info("******** called body.getUser");
	PasswordModel passwordModel = body.getPasswordModel();
	User u = getUserFromPrincipal(principal);

	// check user fields. set only not empty fields
	if (user.getEmail() != null && !user.getEmail().isEmpty())
		u.setEmail(user.getEmail());
	if (user.getFirstname() != null && !user.getFirstname().isEmpty())
		u.setFirstname(user.getFirstname());
	if (user.getLastname() != null && !user.getLastname().isEmpty())
		u.setLastname(user.getLastname());
	if (user.getAddress() != null)
		u.setAddress(user.getAddress());
	if (user.getPhone() != null)
		u.setPhone(user.getPhone());
	if (user.getCountry() != null && !user.getCountry().isEmpty()
			&& !user.getCountry().equals("unknown"))
		u.setCountry(user.getCountry());
	if (user.getUsage() != null && !user.getUsage().isEmpty()
			&& !user.getUsage().equals("unknown"))
		u.setUsage(user.getUsage());
	if (user.getSubUsage() != null && !user.getSubUsage().isEmpty()
			&& !user.getSubUsage().equals("unknown"))
		u.setSubUsage(user.getSubUsage());
	if (user.getDomain() != null && !user.getDomain().isEmpty()
			&& !user.getDomain().equals("unknown"))
		u.setDomain(user.getDomain());
	if (user.getSubDomain() != null && !user.getSubDomain().isEmpty()
			&& !user.getSubDomain().equals("unknown"))
		u.setSubDomain(user.getSubDomain());

	if (user.getPassword() != null && passwordModel != null) {
		logger.info("******** update user password");
		// encrypt old password to compare
		PasswordEncryption encryption = u.getPasswordEncryption();
		String oldpwd = passwordModel.getOldPassword();
		if (encryption != PasswordEncryption.NONE) // when configurable
		{
			try {
				MessageDigest md = MessageDigest.getInstance(encryption
						.getAlgorithmKey());
				oldpwd = new String(Hex.encode(md.digest(passwordModel
						.getOldPassword().getBytes("UTF-8"))));
			} catch (Exception e) {
				responseCode = 1002;
				throw new UserBadEncryptionException(
						"There was an error while encrypting password of user "
								+ u.getUsername(), e);
			}
		}

		if (!u.getPassword().equals(oldpwd)) {
			responseCode = 1003;
			throw new UserBadOldPasswordException(
					"Old password is not correct.");
		}

		if (!user.getPassword().equals(passwordModel.getConfirmPassword())) {
			responseCode = 1004;
			throw new UserPasswordConfirmationException(
					"Confirmation password value doesn't match.");
		}
		userService.selfChangePassword(u.getUUID(),passwordModel.getOldPassword(),passwordModel.getConfirmPassword());
	}
	logger.info("******** update user");

	userService.selfUpdateUser(u);
	return responseCode;
}