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

The following examples show how to use org.springframework.security.crypto.codec.Hex. These examples are extracted from open source projects. 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 Project: mPaaS   Source File: RsaEncryptProvider.java    License: 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 Project: mPass   Source File: RsaEncryptProvider.java    License: 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 Project: summerframework   Source File: StringEncryptorHolder.java    License: 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 4
Source Project: SMSC   Source File: EncrypterUtil.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 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;
}
 
Example 5
Source Project: DataHubSystem   Source File: User.java    License: 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 6
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 7
Source Project: alf.io   Source File: AdditionalService.java    License: 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 8
Source Project: mPaaS   Source File: RsaPublicKeyFilter.java    License: 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 9
Source Project: mPass   Source File: RsaPublicKeyFilter.java    License: 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 10
Source Project: mPass   Source File: RsaEncryptProvider.java    License: 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 11
Source Project: fast-family-master   Source File: PasswordUtils.java    License: 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 12
Source Project: fast-family-master   Source File: PasswordUtils.java    License: 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 13
Source Project: Spring   Source File: TokenUtils.java    License: 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 14
@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 15
Source Project: spring-backend-boilerplate   Source File: TOTPUtils.java    License: 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 16
Source Project: spring-backend-boilerplate   Source File: SecurityUtils.java    License: 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 17
Source Project: greenbeans   Source File: Encryptor.java    License: 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 18
Source Project: haven-platform   Source File: DockerServiceMock.java    License: 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 19
@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 20
/**
 * 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 21
/**
 * 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 22
Source Project: alf.io   Source File: NotificationManager.java    License: 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 23
Source Project: ZenQuery   Source File: StringUtil.java    License: 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 24
Source Project: studio   Source File: SessionTokenUtils.java    License: 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 25
Source Project: boot-examples   Source File: TokenUtils.java    License: 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 26
Source Project: flair-engine   Source File: AESGCMBytesEncryptor.java    License: Apache License 2.0 4 votes vote down vote up
public AESGCMBytesEncryptor(String passphrase, KeyDerivationFunction keyDerivationFunction, CharSequence salt, BytesKeyGenerator ivGenerator) {
    this.secretKey = new KeyParameter(keyDerivationFunction.derive(passphrase, Hex.decode(salt), 32));
    this.ivGenerator = ivGenerator;
}
 
Example 27
Source Project: summerframework   Source File: AbstractEncryptorHolder.java    License: Apache License 2.0 4 votes vote down vote up
public AbstractEncryptorHolder(String password, String salt) {
    this.password = password;
    this.salt = new String(Hex.encode(salt.getBytes(Charset.forName("utf-8"))));
}
 
Example 28
Source Project: blog   Source File: AesEncryptor.java    License: Apache License 2.0 4 votes vote down vote up
public String encrypt(String text) {
    return new String(Hex.encode(encryptor.encrypt(Utf8.encode(text))));
}
 
Example 29
Source Project: blog   Source File: AesEncryptor.java    License: Apache License 2.0 4 votes vote down vote up
public String decrypt(String encryptedText) {
    return Utf8.decode(encryptor.decrypt(Hex.decode(encryptedText)));
}
 
Example 30
Source Project: fast-family-master   Source File: CustomPasswordEnconder.java    License: Apache License 2.0 4 votes vote down vote up
@Override
public String encode(CharSequence charSequence) {
    return PasswordUtils.encryptPassword(Hex.decode(charSequence));
}