com.samsung.knoxwsm.util.KnoxEncryptionUtility Maven / Gradle / Ivy
package com.samsung.knoxwsm.util;
import org.apache.commons.codec.binary.Base64;
import javax.crypto.Cipher;
import java.security.KeyFactory;
import java.security.PublicKey;
import java.security.spec.X509EncodedKeySpec;
/**
* @author e.jaucian 7/15/19
*
* To use KnoxEncryptionUtility, instantiate said class. Pass the text to be encrypted to
* encrypt(textToEncrypt) method. Said method will return an encrypted text.
* Text to be encrypted should not be greater than 245 bytes.
*
* ex:
* KnoxEncryptionUtility knoxEncryptionUtil = new KnoxEncryptionUtility();
* String encryptedText = knoxEncryptionUtil.encrypt(textToBeEncrypted);
*/
public class KnoxEncryptionUtility {
private static final String ENCRYPTION_PUBLIC_KEY = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAu4NECyudg9kYyLqdcfaOiRY+ImD3PYpnMXItzWR9YL1BeJOt1lwLG32aIix2SvED+5w8q0aLINeS8zDiJ28gsz5waUSIZHDzuPg9GOaDumua6FWcXxqI1i209lPF7rzbtHWU/2AngPX/hb5a/L7nYuTpDTNFMvQ1k1xw3fghtUb5lP+tRPYIgdKjRdS5WCRCR3I8ppyKABFisYHn1jm0op16AyIyX6lbCTb7HppkfDU2V0tdPBqTT5C1qNJKkPVLQzqN3lKQdY0bx+Ebf9zA+QPeorTTGurmnAe4JuNYO3G26WtFZ91RaMaKXogT1l+2++oaoSGZk1fm6z2ojLdz4wIDAQAB";
private static final String ALGORITHM = "RSA";
private PublicKey publicKey;
private Cipher encryptionCipher;
private static final String EXCEPTION_MESSAGE = "Exception encountered while encrypting text.";
public KnoxEncryptionUtility() throws Exception {
try {
publicKey = getPublicKey();
encryptionCipher = Cipher.getInstance(ALGORITHM);
encryptionCipher.init(Cipher.ENCRYPT_MODE, publicKey);
} catch (Exception e) {
throw new Exception(EXCEPTION_MESSAGE);
}
}
private static PublicKey getPublicKey() throws Exception {
byte[] publicKeyBytes = Base64.decodeBase64(ENCRYPTION_PUBLIC_KEY);
X509EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(publicKeyBytes);
KeyFactory publicKeyFactory = KeyFactory.getInstance(ALGORITHM);
return publicKeyFactory.generatePublic(publicKeySpec);
}
/**
* A method used to encrypt texts. Text to be encrypted should not be greater than 245 bytes.
*
* @param text text to be encrypted.
* @return Encrypted text.
* @throws Exception When the text couldn't be encrypted properly
*/
public String encrypt(String text) throws Exception {
if(text == null || text.trim().length() == 0) {
throw new IllegalArgumentException("Text cannot be null or empty.");
}
try {
if (encryptionCipher == null) {
encryptionCipher = Cipher.getInstance(ALGORITHM);
encryptionCipher.init(Cipher.ENCRYPT_MODE, publicKey);
}
byte[] cipherText = encryptionCipher.doFinal(text.getBytes());
return Base64.encodeBase64String(cipherText);
} catch (Exception e) {
throw new Exception(EXCEPTION_MESSAGE);
}
}
}