Skip to content

Instantly share code, notes, and snippets.

@adam-skelton
Last active May 23, 2018 05:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save adam-skelton/8e38e8a7d3673cadb4814efda438f860 to your computer and use it in GitHub Desktop.
Save adam-skelton/8e38e8a7d3673cadb4814efda438f860 to your computer and use it in GitHub Desktop.
public void encryptDecryptLicense() throws Exception
{
String encryptedFilePath = getMyDir + "EncryptedLicense.txt";
// Load the contents of the license into a byte array.
byte[] licBytes = readAllBytesFromFile("YourLicense.lic");
// Use this key only once for this license file.
//To protect another file first generate a new key.
byte[] key = generateKey(licBytes.Length);
// Write the encrypted license to disk.
BufferedOutputStream output = new BufferedOutputStream(new FileOutputStream(
encryptedFilePath));
output.write(encryptDecryptLicese(licBytes, key));
output.close();
// Load the encrypted license and decrypt it using the key.
byte[] decryptedLicense = encryptDecryptLicense(
readAllBytesFromFile(encryptedFilePath), key);
// Load the decrypted license into a stream and set the license.
ByteArrayInputStream licenseStream = new ByteArrayInputStream(decryptedLicense);
License license = new License();
license.SetLicense(licenseStream);
}
// A method used for encrypting and decrypting data using XOR.
public byte[] encryptDecryptLicense(byte[] licBytes, byte[] key)
{
byte[] output = new byte[licBytes.Length];
for (int i = 0; i < licBytes.Length; i++)
output[i] = (byte)(licBytes[i] ^ key[i]);
return output;
}
// Generates a random key the same length as the license (a one time pad).
public byte[] generateKey(int size)
{
SecureRandom rng = new SecureRandom();
byte[] strongBytes = new byte[size];
rng.nextBytes(strongBytes);
return strongBytes;
}
public byte[] readAllBytesFromFile(String filePath) Throws IOException
{
int pos;
InputStream inputStream = new FileInputStream(filePath);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
while ((pos = inputStream.Read() != -1)
bos.write(pos);
inputStream.close();
return bos.toByteArray();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment