【问题标题】:Android Sdk: BASE64 Encoder/Decoder not importingAndroid Sdk:BASE64 编码器/解码器未导入
【发布时间】:2013-07-31 01:00:08
【问题描述】:

所以我正在尝试实现从link to code 获得的字符串加密类

当我尝试将其放入我的 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;
    }
}

【问题讨论】:

  • 你有哪个 API 级别?
  • 我使用的是 android 4.2.2 api,以及来自 android sdk bundle 的最新版本的 eclipse。
  • @JohnnyWineShirt 你找到解决方案了吗?提前致谢。

标签: java android encryption


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 2016-07-23
    • 1970-01-01
    • 2013-02-16
    • 2011-08-11
    • 2020-12-02
    • 2018-11-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多