co.privacyone.sdk.keychain.client.KeychainTokenizer Maven / Gradle / Ivy
The newest version!
/*************************************************************************
*
* Privacy1 AB CONFIDENTIAL
* ________________________
*
* [2017] - [2022] Privacy1 AB
* All Rights Reserved.
*
* NOTICE: All information contained herein is, and remains the property
* of Privacy1 AB. The intellectual and technical concepts contained herein
* are proprietary to Privacy1 AB and may be covered by European, U.S. and Foreign
* Patents, patents in process, and are protected by trade secret or copyright law.
*
* Dissemination of this information or reproduction of this material
* is strictly forbidden.
*/
package co.privacyone.sdk.keychain.client;
import co.privacyone.security.crypto.FF3Cipher;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.crypto.BadPaddingException;
import javax.crypto.IllegalBlockSizeException;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;
public class KeychainTokenizer {
public enum TokenizerType {
DIGITS(10),
DIGITS_CHARACTER_LOWERCASE(36),
DIGITS_CHARACTER_ALL(62);
private final int value;
TokenizerType(int value) {
this.value = value;
}
public int toValue() {return this.value;}
}
private static final Logger LOG = LoggerFactory.getLogger(KeychainTokenizer.class);
private FF3Cipher ff3Cipher;
/**
* Initialize a tokenizer.
* @param key key length must be 16, 24, 32 bytes.
* @param tweak 16 bytes String
* @param type tokenizer for digits(0123456789) and digits with uppercase
* letters(0123456789 + ABCEDEFGHIJKLMNOPQRSTUVWXYZ). etc.
*/
public KeychainTokenizer(
final String key,
final String tweak,
final TokenizerType type) {
this.ff3Cipher = new FF3Cipher(key, tweak, type.toValue());
}
public String encrypt(final String plainText)
throws BadPaddingException, IllegalBlockSizeException {
Map format = getStringFormat(plainText);
String stringNormal = plainText.replaceAll("[- ]", "");
String cipherTextNormal = this.ff3Cipher.encrypt(stringNormal);
String cipherText = formatString(cipherTextNormal, format);
return cipherText;
}
public String decrypt(final String cipherText)
throws BadPaddingException, IllegalBlockSizeException {
Map format = getStringFormat(cipherText);
String cipherTextNormal = cipherText.replaceAll("[- ]", "");
String stringNormal = this.ff3Cipher.decrypt(cipherTextNormal);
String stringText = formatString(stringNormal, format);
return stringText;
}
public Map getStringFormat(final String value) {
Map format = new TreeMap();
for (int i = 0; i < value.length(); i++) {
char c = value.charAt(i);
if (c == '-' || c == ' ') {
format.put(i, c);
}
}
return format;
}
public String formatString(final String str, final Map format) {
final StringBuffer buf = new StringBuffer(str);
for (Map.Entry e : format.entrySet()) {
int idx = e.getKey();
char ch = e.getValue();
buf.insert(idx, ch);
}
return buf.toString();
}
}