· 7 years ago · Nov 21, 2018, 10:02 PM
1CREATE OR REPLACE JAVA SOURCE NAMED KFS.ENCRYPTIONSERVICE AS
2import sun.misc.BASE64Decoder;
3import sun.misc.BASE64Encoder;
4
5import java.io.ByteArrayInputStream;
6import java.io.FileInputStream;
7import java.util.Properties;
8
9import java.io.UnsupportedEncodingException;
10import java.security.GeneralSecurityException;
11import java.security.MessageDigest;
12
13import javax.crypto.Cipher;
14import javax.crypto.KeyGenerator;
15import javax.crypto.SecretKey;
16import javax.crypto.SecretKeyFactory;
17import javax.crypto.spec.DESKeySpec;
18
19
20/**
21 * Encrypts/Decrypts a string
22 *
23 * @author Leo Przybylski (leo [at] rsmart.com)
24 */
25public class EncryptionService {
26 public final static String ALGORITHM = "DES/ECB/PKCS5Padding";
27 public final static String HASH_ALGORITHM = "SHA";
28
29 private final static String CHARSET = "UTF-8";
30
31 protected SecretKey unwrapEncodedKey() throws Exception {
32 final byte[] bytes = new byte[] {-20, -128, -70, -29, 14, -92, 0, 0, 0};
33
34 final SecretKeyFactory desFactory = SecretKeyFactory.getInstance("DES");
35
36 final DESKeySpec keyspec = new DESKeySpec(bytes);
37 final SecretKey k = desFactory.generateSecret(keyspec);
38
39 return k;
40 }
41
42 public String decrypt(final String ciphertext) throws Exception {
43 SecretKey desKey = null;
44 try {
45 desKey = this.unwrapEncodedKey();
46
47 final Cipher cipher = Cipher.getInstance(ALGORITHM);
48 cipher.init((Cipher.WRAP_MODE), desKey);
49 }
50 catch (Exception e) {
51 e.printStackTrace();
52 }
53
54 // Initialize the same cipher for decryption
55 final Cipher cipher = Cipher.getInstance(ALGORITHM);
56 cipher.init(Cipher.DECRYPT_MODE, desKey);
57
58 try {
59 // un-Base64 encode the encrypted data
60 final byte[] encryptedData = new BASE64Decoder().decodeBuffer(new ByteArrayInputStream(ciphertext.getBytes()));
61
62 // Decrypt the ciphertext
63 final byte[] cleartext1 = cipher.doFinal(encryptedData);
64 return new String(cleartext1, CHARSET);
65 }
66 catch (UnsupportedEncodingException e) {
67 throw new RuntimeException(e);
68 }
69 }
70
71 public static void main(final String[] args) {
72 try {
73 Properties props = new Properties();
74 props.load(new FileInputStream("encrypted.properties"));
75 System.out.println("Decrypted String: " + new EncryptionService().decrypt(args[0]));
76 }
77 catch (Exception e) {
78 e.printStackTrace();
79 }
80 }
81}
82
83
84public class Decrypt {
85 public static String execute(final String toDecrypt) {
86 try {
87 return new EncryptionService().decrypt(toDecrypt);
88 }
89 catch (Exception e) {
90 e.printStackTrace();
91 throw new RuntimeException(e);
92 }
93 }
94}
95
96GO
97
98CREATE OR REPLACE FUNCTION decrypt_string(encrypted varchar2) RETURN VARCHAR2 AS
99LANGUAGE JAVA NAME 'Decrypt.execute(java.lang.String) return java.lang.String';