You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
74 lines
2.2 KiB
Java
74 lines
2.2 KiB
Java
package cokr.xit.foundation.util;
|
|
|
|
import java.security.MessageDigest;
|
|
|
|
import org.apache.commons.codec.binary.Base64;
|
|
|
|
import cokr.xit.foundation.AbstractComponent;
|
|
|
|
/**문자열 인코더.
|
|
* @author mjkhan
|
|
*/
|
|
public class CharsEncoder extends AbstractComponent {
|
|
private String algorithm;
|
|
private boolean plainText;
|
|
|
|
/**문자열 인크립션에 사용할 알고리즘을 반환한다. 디폴트는 SHA-256.
|
|
* @return 문자열 인크립션에 사용할 알고리즘
|
|
*/
|
|
public String getAlgorithm() {
|
|
return ifEmpty(algorithm, "SHA-256");
|
|
}
|
|
|
|
/**문자열 인크립션에 사용할 알고리즘을 설정한다. 디폴트는 SHA-256.
|
|
* @param algorithm 문자열 인크립션에 사용할 알고리즘
|
|
*/
|
|
public void setAlgorithm(String algorithm) {
|
|
this.algorithm = algorithm;
|
|
}
|
|
|
|
/**인코딩 여부를 설정한다.
|
|
* @param plainText 인코딩 여부
|
|
* <ul><li>문자열을 인코딩하지 않으려면 true</li>
|
|
* <li>문자열을 인코딩하려면 false(디폴트)</li>
|
|
* </ul>
|
|
*/
|
|
public void setPlainText(boolean plainText) {
|
|
this.plainText = plainText;
|
|
}
|
|
|
|
/**문자열을 설정된 알고리즘으로 인크립션 후 BASE64로 인코딩하여 반환한다.
|
|
* @param rawChars 문자열
|
|
* @return 인코딩한 문자열
|
|
*/
|
|
public String encode(CharSequence rawChars) {
|
|
if (isEmpty(rawChars)) return "";
|
|
|
|
String str = rawChars.toString();
|
|
if (plainText) return str;
|
|
|
|
try {
|
|
MessageDigest md = MessageDigest.getInstance(getAlgorithm());
|
|
md.reset();
|
|
md.update(str.getBytes());
|
|
|
|
byte[] hashValue = md.digest(str.getBytes());
|
|
return new String(Base64.encodeBase64(hashValue));
|
|
} catch (Exception e) {
|
|
throw applicationException(e);
|
|
}
|
|
}
|
|
|
|
/**주어진 문자열을 인코딩한 결과가 인코딩한 문자열과 일치하는지 반환한다.
|
|
* @param rawChars 인코딩하지 않은 일반 문자열
|
|
* @param encodedChars 인코딩한 문자열
|
|
* @return
|
|
* <ul><li>두 문자열의 인코딩 결과가 같으면 true</li>
|
|
* <li>그렇지 않으면 false</li>
|
|
* </ul>
|
|
*/
|
|
public boolean matches(CharSequence rawChars, String encodedChars) {
|
|
String encoded = encode(rawChars);
|
|
return encoded.equals(encodedChars);
|
|
}
|
|
} |