SymmetricCrypt.java 2.5 KB
/*
 * Decompiled with CFR 0_118.
 * 
 * Could not load the following classes:
 *  com.day.text.Text
 *  org.slf4j.Logger
 *  org.slf4j.LoggerFactory
 */
package com.day.cq.commons;

import com.day.text.Text;
import java.io.ByteArrayOutputStream;
import java.security.Key;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class SymmetricCrypt {
    private static final Logger log = LoggerFactory.getLogger(SymmetricCrypt.class);
    private static final int KEY_LENGTH = 8;
    public static final String PREFIX = "{DES}";

    public static String encrypt(String s) {
        try {
            SecretKey key = KeyGenerator.getInstance("DES").generateKey();
            Cipher cipher = Cipher.getInstance("DES");
            byte[] keyBytes = key.getEncoded();
            byte[] data = s.getBytes("utf-8");
            ByteArrayOutputStream out = new ByteArrayOutputStream(keyBytes.length + data.length);
            out.write(keyBytes);
            cipher.init(1, key);
            out.write(cipher.update(data));
            out.write(cipher.doFinal());
            StringBuilder ret = new StringBuilder("{DES}");
            for (byte b : out.toByteArray()) {
                ret.append(Text.hexTable[b >> 4 & 15]).append(Text.hexTable[b & 15]);
            }
            return ret.toString();
        }
        catch (Exception e) {
            log.warn("Unable to encrypt string: " + e);
            return null;
        }
    }

    public static String decrypt(String s) {
        if (!s.startsWith("{DES}")) {
            return null;
        }
        try {
            byte[] data = new byte[(s.length() - "{DES}".length()) / 2];
            int i = "{DES}".length();
            int b = 0;
            while (i < s.length()) {
                data[b] = (byte)(Integer.parseInt(s.substring(i, i + 2), 16) & 255);
                i += 2;
                ++b;
            }
            SecretKeySpec key = new SecretKeySpec(data, 0, 8, "DES");
            Cipher cipher = Cipher.getInstance("DES");
            ByteArrayOutputStream out = new ByteArrayOutputStream(data.length);
            cipher.init(2, key);
            out.write(cipher.update(data, 8, data.length - 8));
            out.write(cipher.doFinal());
            return out.toString("utf-8");
        }
        catch (Exception e) {
            log.warn("Unable to decrypt data: " + e);
            return null;
        }
    }
}