0

所以我正在尝试实现一个从链接到代码的字符串加密类

当我尝试将其放入我的 android 项目时,我收到以下错误:

说明 资源路径 位置 类型 导入 sun 无法解析 SimpleProtector.java /EncryptedSMS/src/com/nsaers/encryptedsms 第 7 行 Java 问题 BASE64Decoder 无法解析为类型 SimpleProtector.java /EncryptedSMS/src/com/nsaers/encryptedsms 第29行Java 问题 BASE64Encoder 无法解析为 SimpleProtector.java /EncryptedSMS/src/com/nsaers/encryptedsms 第 21 行 Java 问题

有任何想法吗?

这是我的课程代码:

package com.nsaers.encryptedsms;

import java.security.Key;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

public class SimpleProtector {
    private static final String ALGORITHM = "AES";
    private static final byte[] keyValue = new byte[] { 'T', 'h', 'i', 's',
            'I', 's', 'A', 'S', 'e', 'c', 'r', 'e', 't', 'K', 'e', 'y' };

    public static String encrypt(String valueToEnc) throws Exception {
        Key key = generateKey();
        Cipher c = Cipher.getInstance(ALGORITHM);
        c.init(Cipher.ENCRYPT_MODE, key);
        byte[] encValue = c.doFinal(valueToEnc.getBytes());
        String encryptedValue = new BASE64Encoder().encode(encValue);
        return encryptedValue;
    }

    public static String decrypt(String encryptedValue) throws Exception {
        Key key = generateKey();
        Cipher c = Cipher.getInstance(ALGORITHM);
        c.init(Cipher.DECRYPT_MODE, key);
        byte[] decordedValue = new BASE64Decoder().decodeBuffer(encryptedValue);
        byte[] decValue = c.doFinal(decordedValue);
        String decryptedValue = new String(decValue);
        return decryptedValue;
    }

    private static Key generateKey() throws Exception {
        Key key = new SecretKeySpec(keyValue, ALGORITHM);
        // SecretKeyFactory keyFactory =
        // SecretKeyFactory.getInstance(ALGORITHM);
        // key = keyFactory.generateSecret(new DESKeySpec(keyValue));
        return key;
    }
}
4

1 回答 1

4

使用Base64Android SDK 中的类而不是BASE64Encoder/ BASE64Decoder。API 可能略有不同,但它会满足您的需求。

但是,您的代码仍然不是理想的:任何时候您使用String.getBytes或使用String字节数组的构造函数,您都应该指定要使用的编码 - UTF-8 可能是最合适的。目前您将使用系统默认编码,它可能是 UTF-8(我感觉它总是在 Android 中),但会使您的代码非常脆弱。

于 2013-07-30T17:00:08.200 回答