我使用以下C#源代码使用AES(ECB 256)加密纯文本:
public static string Encode(string PlainText) { byte[] Key = ASCIIEncoding.UTF8.GetBytes("12345678901234567890123456789012"); string encrypted = null; RijndaelManaged rj = new RijndaelManaged(); rj.BlockSize = 256; rj.KeySize = 256; rj.Key = Key; rj.GenerateIV(); byte[] IV = rj.IV; rj.Mode = CipherMode.ECB; rj.Padding = PaddingMode.Zeros; try { using (MemoryStream ms = new MemoryStream()) { using (CryptoStream cs = new CryptoStream(ms,rj.CreateEncryptor(Key,IV),CryptoStreamMode.Write)) { using (StreamWriter sw = new StreamWriter(cs)) { sw.Write(PlainText); sw.Close(); sw.Dispose(); } cs.Close(); cs.Dispose(); } byte[] encryptArray = ms.ToArray(); encrypted = (Convert.ToBase64String(encryptArray)); ms.Close(); ms.Dispose(); } } catch (Exception ex) { throw ex; } finally { rj.Clear(); } return encrypted; }
我需要通过相同的算法解密/加密数据,但我不知道如何.
这是我的Java类(不工作):
public static String encrypt(byte[] key,String cleartext,boolean base64) throws Exception { byte[] rawKey = key; byte[] result = encrypt(rawKey,cleartext.getBytes()); // Base 64 if (base64) return toBase64(result); // Hex return toHex(result); } public static String decrypt(byte[] key,String encrypted) throws Exception { byte[] rawKey = key; byte[] enc = toByte(encrypted); byte[] result = decrypt(rawKey,enc); return new String(result); } private static byte[] encrypt(byte[] raw,byte[] clear) throws Exception { SecretKeySpec skeySpec = new SecretKeySpec(raw,"AES"); Cipher cipher = Cipher.getInstance("AES/ECB/NoPadding"); cipher.init(Cipher.ENCRYPT_MODE,skeySpec); byte[] encrypted = cipher.doFinal(clear); return encrypted; }
Java调用:
encrypt("12345678901234567890123456789012".getBytes(),"Example Message",true);
我不知道如何在Java中选择块大小或PaddingMode.Zeros.
任何的想法?
提前致谢
解决方法
是的,问题是AES中128位块大小的限制(参见“强对比无限强度加密”).
最后,我使用了GNU Crypto并且它有效!我已经导入了所有源代码,并且删除了我没有使用的代码.
如果有人想要清理过的源代码,他只需要问我.
谢谢您的帮助.