cert-encoder.git

ref: 5a022a3b36dc2ce532f11aa5044a4850ee54f512

src/test/java/EncryptionTest.java


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
import net.lulli.encrypt.Pems;
import net.lulli.encrypt.pki.PkiEncryptionManager;
import net.lulli.encrypt.symmetric.SymmetricEncryptionManager;
import org.junit.Ignore;
import org.junit.Test;

import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.security.PrivateKey;
import java.security.cert.X509Certificate;
import java.util.Arrays;

public class EncryptionTest {

    @Test
    public void symmetricEncryptDecrypt() {
        var symmetricEncryptionManager = SymmetricEncryptionManager.INSTANCE;
        var plainTest = "This is some long cleartext";
        var key = "abcdefghijklmnopqrstuvz".getBytes(Charset.forName("UTF-8"));

        byte[] encrypted = symmetricEncryptionManager.encrypt(plainTest, key);

        byte[] decrypted = symmetricEncryptionManager.decrypt(encrypted, key);

        assert Arrays.equals(plainTest.getBytes(), decrypted);
    }


    @Test
    public void pkiEncryptDecrypt() throws Exception {
        var pkiEncryptionManager = PkiEncryptionManager.INSTANCE;

        File outputEncryptedFile = File.createTempFile("pkiEncrDecr.", ".enc");
        File outputDencryptedFile = File.createTempFile("pkiEncrDecr", ".dec");
        var plainText = "this is a sample text";
        String certString = Files.readString(Paths.get(getClass().getResource("local.crt").toURI()), Charset.forName("utf-8"));

        String keyString = Files.readString(Paths.get(getClass().getResource("local.key").toURI()), Charset.forName("utf-8"));
        X509Certificate x509Certificate = Pems.readX509Certificate(certString);

        byte[] enc = pkiEncryptionManager.encryptData(plainText.getBytes(), x509Certificate);
        System.out.printf("Cleartext: [%s]\n Encrypted: [%s]\n", plainText, new String(enc));

        Files.write(Paths.get(outputEncryptedFile.getAbsolutePath()), enc);

        PrivateKey privateKey = Pems.readPKCS8PrivateKey(keyString);

        long millis = System.currentTimeMillis();
        pkiEncryptionManager.decryptCms(privateKey, enc, outputDencryptedFile.getAbsolutePath()+millis);
    }
}