java 代码加密解密(二)

import com.company.manage.util.FileUtils;

import javax.crypto.*;
import javax.crypto.spec.DESKeySpec;
import java.io.*;
import java.security.GeneralSecurityException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.spec.InvalidKeySpecException;
import java.util.Arrays;


public class DecryptStart extends ClassLoader {

    // 这些对象在构造函数中设置,
    // 以后loadClass()方法将利用它们解密类
    private SecretKey key;
    private Cipher cipher;

    // 构造函数:设置解密所需要的对象
    public DecryptStart(SecretKey key) throws GeneralSecurityException, IOException {
        this.key = key;
        String algorithm = "DES";
        SecureRandom sr = new SecureRandom();
        System.err.println("[DecryptStart:creating cipher]");
        cipher = Cipher.getInstance(algorithm);
        cipher.init(Cipher.DECRYPT_MODE, key, sr);
    }

    @Override
    public Class loadClass(String name, boolean resolve) throws ClassNotFoundException {
        try {
            // 我们要创建的Class对象
            Class clasz = null;
            // 必需的步骤1:如果类已经在系统缓冲之中
            // 我们不必再次装入它
            clasz = findLoadedClass(name);
            if (clasz != null) {
                return clasz;
            }

            // 下面是定制部分
            // 读取经过加密的类文件
//             byte classData[] = Util.readFile(name + ".class");
            byte classData[] = getFileToByte(name + ".class");
            if (classData != null) {
                // 解密...
                byte decryptedClassData[] = cipher.doFinal(classData);

                // ...再把它转换成一个类
                clasz = defineClass(name, decryptedClassData, 0, decryptedClassData.length);
                System.err.println("[DecryptStart:decrypting class" + name + "]");
            }


            // 必需的步骤2:如果上面没有成功
            //我们尝试用默认的ClassLoader装入它
            if (clasz == null) {
                clasz = findSystemClass(name);
            }

            // 必需的步骤3:如有必要,则装入相关的类
            if (resolve && clasz != null) {
                resolveClass(clasz);
            }

            //把类返回给调用者
            return clasz;
        } catch (GeneralSecurityException gse) {
            throw new ClassNotFoundException(gse.toString());
        }
    }

    /**
     * 获取文件转字节
     *
     * @param pathName 文件路径
     */
    private static byte[] getFileToByte(String pathName) {
        File file = new File(pathName);
        try {
            FileInputStream fis = new FileInputStream(file);
            //转成 n 英型大小的数组
            byte[] fileBytes = new byte[(int) file.length()];
            //01将 pdt 内容款到数组当中
            fis.read(fileBytes);
            //1关闭文件流
            fis.close();
            System.out.println(Arrays.toString(fileBytes));
            return fileBytes;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 步骤1:生成一个密匙
     * 在加密或解密任何数据之前需要有一个密匙。密匙是随同被加密的应用一起发布的一小段数据
     *
     * @throws Exception
     */
    public static String generateSecretKey() throws NoSuchAlgorithmException, IOException {
        // DES算法要求有一个可信任的随机数源
        SecureRandom sr = new SecureRandom();

        // 为我们选择的DES算法生成一个KeyGenerator对象
        KeyGenerator kg = KeyGenerator.getInstance("DES");
        kg.init(sr);

        // 生成密匙
        SecretKey key = kg.generateKey();

        // 获取密匙数据
        byte rawKeyData[] = key.getEncoded();

        /* TODO 接下来就可以用密匙进行加密或解密,或者把它保存为文件供以后使用 */
        // doSomething(rawKeyData );
        saveToFile("E:\\usr\\local\\temp\\new3s-windPvElecIntg\\generateSecret.txt", rawKeyData);
        // [B@1bce4f0a
        System.out.println(rawKeyData.toString());
        return rawKeyData.toString();
    }

    /**
     * 步骤2:加密数据
     * 得到密匙之后,接下来就可以用它加密数据。除了解密的ClassLoader之外,一般还要有一个加密待发布应用的独立程序
     *
     * @throws InvalidKeyException
     * @throws NoSuchAlgorithmException
     * @throws InvalidKeySpecException
     * @throws NoSuchPaddingException
     * @throws IllegalBlockSizeException
     * @throws BadPaddingException
     */
    private static String encryptData() throws InvalidKeyException, NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException,
            IOException {
        // DES算法要求有一个可信任的随机数源
        SecureRandom sr = new SecureRandom();
        /* TODO 用某种方法获得密匙数据 */
        byte rawKeyData[] = getFileToByte("E:\\usr\\local\\temp\\new3s-windPvElecIntg\\generateSecret.txt");

        // 从原始密匙数据创建DESKeySpec对象
        DESKeySpec dks = new DESKeySpec(rawKeyData);

        // 创建一个密匙工厂,然后用它把DESKeySpec转换成
        // 一个SecretKey对象
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
        SecretKey key = keyFactory.generateSecret(dks);

        // Cipher对象实际完成加密操作
        Cipher cipher = Cipher.getInstance("DES");

        // 用密匙初始化Cipher对象
        cipher.init(Cipher.ENCRYPT_MODE, key, sr);

        // 现在,获取数据并加密
        /* TODO 用某种方法获取数据 */
        // 获取所有的Java文件
        byte data[] = getFileToByte("src/main/java/com/new3s/manage/WindPowerManageApplication.java");

        // 正式执行加密操作
        byte encryptedData[] = cipher.doFinal(data);

        // TODO 进一步处理加密后的数据
        // doSomething( encryptedData );
        FileUtils.byteToFile(encryptedData, "E:\\usr\\local\\temp\\new3s-windPvElecIntg\\WindPowerManageApplication_encryptData.java");
        return encryptedData.toString();
    }

    /**
     * 步骤3:解密数据
     * 运行经过加密的应用时,ClassLoader分析并解密类文件。
     *
     * @throws InvalidKeyException
     * @throws NoSuchAlgorithmException
     * @throws InvalidKeySpecException
     * @throws NoSuchPaddingException
     * @throws IllegalBlockSizeException
     * @throws BadPaddingException
     */
    private static String decryptData() throws InvalidKeyException, NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException,
            IOException {
        // DES算法要求有一个可信任的随机数源
        SecureRandom sr = new SecureRandom();
        /* TODO 用某种方法获取原始密匙数据 */
        byte rawKeyData[] = getFileToByte("E:\\usr\\local\\temp\\new3s-windPvElecIntg\\generateSecret.txt");
        // 从原始密匙数据创建一个DESKeySpec对象
        DESKeySpec dks = new DESKeySpec(rawKeyData);

        // 创建一个密匙工厂,然后用它把DESKeySpec对象转换成
        // 一个SecretKey对象
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
        SecretKey key = keyFactory.generateSecret(dks);

        // Cipher对象实际完成解密操作
        Cipher cipher = Cipher.getInstance("DES");

        // 用密匙初始化Cipher对象
        cipher.init(Cipher.DECRYPT_MODE, key, sr);

        // 现在,获取数据并解密
        /* TODO 获得经过加密的数据 */
        byte encryptedData[] = getFileToByte("E:\\usr\\local\\temp\\new3s-windPvElecIntg\\WindPowerManageApplication_encryptData.java");;

        // 正式执行解密操作
        byte decryptedData[] = cipher.doFinal(encryptedData);

        // TODO 进一步处理解密后的数据
        // doSomething( decryptedData );
        FileUtils.byteToFile(decryptedData, "E:\\usr\\local\\temp\\new3s-windPvElecIntg\\WindPowerManageApplication_decryptedData.java");
        return decryptedData.toString();
    }

    /**
     * byte数组转file文件
     *
     * @param byt
     * @param filePath
     * @return
     * @throws IOException
     */
    public static File byteToFile(byte[] byt, String filePath) throws IOException {
        File file = new File(filePath);
        OutputStream output = new FileOutputStream(file);
        BufferedOutputStream bufferedOutput = new BufferedOutputStream(output);
        bufferedOutput.write(byt);
        output.close();
        bufferedOutput.close();
        return file;
    }

    public static void main(String[] args) throws NoSuchAlgorithmException, IOException, NoSuchPaddingException, IllegalBlockSizeException, InvalidKeySpecException, BadPaddingException, InvalidKeyException {
        // 步骤1:生成一个密匙
        generateSecretKey();
        // 步骤2:加密数据
        encryptData();
        // 步骤3:解密数据
        decryptData();
    }

    /**
     * 将字节数组写入到新建文件中。
     *
     * @param pathname 文件地址
     * @param msg      数据
     * @return boolean
     */
    public static void saveToFile(String pathname, byte[] msg) throws IOException {
        File outputFile = new File(pathname);
        FileOutputStream outputFileStream = null;
        try {
            outputFileStream = new FileOutputStream(outputFile);
            outputFileStream.write(msg);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException ioException) {
            ioException.printStackTrace();
        } finally {
            outputFileStream.close();
        }
    }

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
当然可以!以下是一个示例的完整代码,用于在Android中使用Java实现AES加密和解密: ```java import javax.crypto.Cipher; import javax.crypto.spec.IvParameterSpec; import javax.crypto.spec.SecretKeySpec; import android.util.Base64; public class AESUtil { private static final String AES_ALGORITHM = "AES/CBC/PKCS5Padding"; private static final String CHARSET = "UTF-8"; private static byte[] encrypt(byte[] key, byte[] initVector, byte[] value) { try { SecretKeySpec secretKeySpec = new SecretKeySpec(key, "AES"); IvParameterSpec ivParameterSpec = new IvParameterSpec(initVector); Cipher cipher = Cipher.getInstance(AES_ALGORITHM); cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec, ivParameterSpec); return cipher.doFinal(value); } catch (Exception e) { e.printStackTrace(); } return null; } private static byte[] decrypt(byte[] key, byte[] initVector, byte[] encrypted) { try { SecretKeySpec secretKeySpec = new SecretKeySpec(key, "AES"); IvParameterSpec ivParameterSpec = new IvParameterSpec(initVector); Cipher cipher = Cipher.getInstance(AES_ALGORITHM); cipher.init(Cipher.DECRYPT_MODE, secretKeySpec, ivParameterSpec); return cipher.doFinal(encrypted); } catch (Exception e) { e.printStackTrace(); } return null; } public static String encrypt(String key, String initVector, String value) { try { byte[] encrypted = encrypt(key.getBytes(CHARSET), initVector.getBytes(CHARSET), value.getBytes(CHARSET)); return Base64.encodeToString(encrypted, Base64.DEFAULT); } catch (Exception e) { e.printStackTrace(); } return null; } public static String decrypt(String key, String initVector, String encrypted) { try { byte[] decoded = Base64.decode(encrypted, Base64.DEFAULT); byte[] decrypted = decrypt(key.getBytes(CHARSET), initVector.getBytes(CHARSET), decoded); return new String(decrypted, CHARSET); } catch (Exception e) { e.printStackTrace(); } return null; } } ``` 使用示例: ```java String key = "0123456789abcdef"; // 16字节的密钥 String initVector = "ABCDEF0123456789"; // 16字节的初始向量 String originalText = "Hello, AES!"; String encryptedText = AESUtil.encrypt(key, initVector, originalText); String decryptedText = AESUtil.decrypt(key, initVector, encryptedText); System.out.println("Original Text: " + originalText); System.out.println("Encrypted Text: " + encryptedText); System.out.println("Decrypted Text: " + decryptedText); ``` 请注意,这只是一个简单的示例代码,并不涵盖所有的错误处理和最佳实践。在实际使用中,请根据需要进行适当的异常处理和安全性考虑。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值