为了账号安全,请及时绑定邮箱和手机立即绑定

使用相同的密钥在 C# 中加密并在 Java 中解密

使用相同的密钥在 C# 中加密并在 Java 中解密

MMTTMM 2023-03-02 10:28:31
我正准备在服务器端 (c#) 进行加密,并在 android 端 (Java) 为我的 api 密钥进行解密。c# 中的加密/解密都可以。而且,在 Java 中,加密/解密也可以。主要问题是用 C# 生成的密文与 java 不同,尽管我使用了相同的密钥。C# 生成的密文无法在 Java 中解密。我试过如下。在爪哇 public static String key = "aaaaaaaabbccccbbaaaaaaaabbccccbb";    private static byte[] key_Array = Base64.decode(key,Base64.DEFAULT);    public static String encrypt(String plainText)    {        try        {            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING");            // Initialization vector.            // It could be any value or generated using a random number generator.            byte[] iv = { 1, 2, 3, 4, 5, 6, 6, 5, 4, 3, 2, 1, 7, 7, 7, 7 };            IvParameterSpec ivspec = new IvParameterSpec(iv);            Key secretKey = new SecretKeySpec(key_Array, "AES");            cipher.init(Cipher.ENCRYPT_MODE, secretKey, ivspec);            return Base64.encodeToString(cipher.doFinal(plainText.getBytes()),Base64.DEFAULT);        }        catch (Exception e)        {            System.out.println("[Exception]:"+e.getMessage());        }        return null;    }    public static String decrypt(String encryptedMessage)    {        try        {            //Cipher _Cipher = Cipher.getInstance("AES");            //Cipher _Cipher = Cipher.getInstance("AES/ECB/PKCS5PADDING");            Cipher _Cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING");            // Initialization vector.            // It could be any value or generated using a random number generator.            byte[] iv = { 1, 2, 3, 4, 5, 6, 6, 5, 4, 3, 2, 1, 7, 7, 7, 7 };            IvParameterSpec ivspec = new IvParameterSpec(iv);            Key SecretKey = new SecretKeySpec(key_Array, "AES");            _Cipher.init(Cipher.DECRYPT_MODE, SecretKey, ivspec);            byte decodedMessage[] = Base64.decode(encryptedMessage,Base64.DEFAULT);            return new String(_Cipher.doFinal(decodedMessage));        }
查看完整描述

1 回答

?
慕娘9325324

TA贡献1783条经验 获得超4个赞

问题在于,在您的 Java 代码中,您仅使用 192 位密钥,而在 C# 版本中,您使用的是 256 位密钥。


您的 base64 编码密钥是 32 个字符,转换为 24 个字节,即只有 192 位。


这些是 Java 中有问题的行:


public static String key = "aaaaaaaabbccccbbaaaaaaaabbccccbb"; // 32 characters

private static byte[] key_Array = Base64.decode(key, Base64.DEFAULT); // 24 bytes

只需更改 Java 键数组的创建即可解决问题。就像是:


public static String key = "aaaaaaaabbccccbbaaaaaaaabbccccbb"; // 32 characters

private static byte[] key_Array = new byte[32]; // 32 bytes


static {

    // copy the 24 base64-decoded bytes to the key array

    System.arraycopy(Base64.decode(key, Base64.DEFAULT), 0, key_Array, 0, 24);

}


查看完整回答
反对 回复 2023-03-02
  • 1 回答
  • 0 关注
  • 86 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信