Java Code Examples for org.springframework.security.crypto.codec.Hex#encode()
The following examples show how to use
org.springframework.security.crypto.codec.Hex#encode() .
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: EncryptPassword.java From DataHubSystem with GNU Affero General Public License v3.0 | 6 votes |
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 2
Source File: User.java From DataHubSystem with GNU Affero General Public License v3.0 | 6 votes |
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 3
Source File: RsaEncryptProvider.java From mPaaS with Apache License 2.0 | 6 votes |
/** * 随机生成密钥对 * @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 4
Source File: DockerServiceMock.java From haven-platform with Apache License 2.0 | 5 votes |
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 5
Source File: DefaultTextEncryptor.java From entando-core with GNU Lesser General Public License v3.0 | 5 votes |
/** * 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 6
Source File: SessionTokenUtils.java From studio with GNU General Public License v3.0 | 5 votes |
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 7
Source File: NotificationManager.java From alf.io with GNU General Public License v3.0 | 5 votes |
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 8
Source File: SecurityUtils.java From spring-backend-boilerplate with Apache License 2.0 | 5 votes |
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 9
Source File: TOTPUtils.java From spring-backend-boilerplate with Apache License 2.0 | 5 votes |
/** * @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 10
Source File: StringUtil.java From ZenQuery with Apache License 2.0 | 5 votes |
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 11
Source File: TokenUtils.java From Spring with Apache License 2.0 | 5 votes |
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 12
Source File: TokenUtils.java From boot-examples with Apache License 2.0 | 5 votes |
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 13
Source File: Encryptor.java From greenbeans with Apache License 2.0 | 4 votes |
public String encrypt(String data) { if (data == null) { return null; } return new String(Hex.encode(encryptor.encrypt(data.getBytes(StandardCharsets.UTF_8)))); }
Example 14
Source File: MessageDigestPasswordEncoder.java From lemon with Apache License 2.0 | 4 votes |
private String encode(CharSequence rawPassword, byte[] salt) { byte[] digest = digest(rawPassword, salt); return new String(Hex.encode(digest)); }
Example 15
Source File: StubUserController.java From DataHubSystem with GNU Affero General Public License v3.0 | 4 votes |
@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; }
Example 16
Source File: DefaultAuthenticationProvider.java From DataHubSystem with GNU Affero General Public License v3.0 | 4 votes |
@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 17
Source File: UserService.java From DataHubSystem with GNU Affero General Public License v3.0 | 4 votes |
@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 18
Source File: AesEncryptor.java From blog with Apache License 2.0 | 4 votes |
public String encrypt(String text) { return new String(Hex.encode(encryptor.encrypt(Utf8.encode(text)))); }
Example 19
Source File: AbstractEncryptorHolder.java From summerframework with Apache License 2.0 | 4 votes |
public AbstractEncryptorHolder(String password, String salt) { this.password = password; this.salt = new String(Hex.encode(salt.getBytes(Charset.forName("utf-8")))); }
Example 20
Source File: EncrypterUtil.java From SMSC with Apache License 2.0 | -32 votes |
/** * Additional method to get salt from object. * * @param obj entity object * @return string with salt */ private static CharSequence getSalt(Object obj) throws IllegalAccessException { CharSequence salt; try { Field saltField = obj.getClass().getDeclaredField("salt"); saltField.setAccessible(true); salt = (CharSequence) saltField.get(obj); if (salt == null || salt.toString().isEmpty()) { salt = KeyGenerators.string().generateKey(); saltField.set(obj, salt); } saltField.setAccessible(false); } catch (NoSuchFieldException e) { LOGGER.info("Decrypt exception: salt field not found."); // Use encoded class name as salt, if salt field not available. salt = new String(Hex.encode(obj.getClass().getName().getBytes())); } return salt; }