All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.seepine.tool.secure.symmetric.SSE Maven / Gradle / Ivy

The newest version!
package com.seepine.tool.secure.symmetric;

import com.seepine.tool.exception.CryptoException;
import com.seepine.tool.util.Strings;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;

/**
 * 对称可搜索加密
 *
 * @author seepine
 * @since 0.3.14
 */
public class SSE {
  private final String key;
  private final String separate;

  /**
   * 构造
   *
   * @param key aes密钥
   */
  public SSE(@Nonnull String key) {
    this(key, Strings.POUND);
  }

  /**
   * 构造
   *
   * @param key aes密钥
   * @param separate 分隔符,默认#
   */
  public SSE(@Nonnull String key, @Nonnull String separate) {
    this.key = key;
    this.separate = separate;
  }

  /**
   * 快速构建
   *
   * @param key aes密钥
   * @return 实例
   */
  public static SSE create(@Nonnull String key) {
    return new SSE(key);
  }

  /**
   * 加密
   *
   * @param src 明文
   * @return 密文
   */
  @Nullable
  public String encode(@Nullable String src) {
    if (src == null) {
      return null;
    }
    StringBuilder cipher = new StringBuilder();
    AES aes = new AES(key);
    int index = 0;
    int length = src.length();
    while (index < length) {
      int byteCount = Character.charCount(src.codePointAt(index));
      cipher.append(aes.encrypt(src.substring(index, index + byteCount))).append(separate);
      index += byteCount;
    }
    return cipher.toString();
  }

  /**
   * 解密
   *
   * @param cipher 密文
   * @return 明文
   */
  @Nullable
  public String decode(@Nullable String cipher) {
    if (cipher == null) {
      return null;
    }
    ByteArrayOutputStream bs = new ByteArrayOutputStream();
    AES aes = new AES(key);
    try {
      for (String s : cipher.split(separate)) {
        bs.write(aes.decryptByte(Base64.decodeByte(s)));
      }
      return bs.toString(Strings.UTF_8);
    } catch (IOException e) {
      throw new CryptoException(e);
    }
  }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy