Come vedi questo è l'esempio che sto facendo basandomi sui due metodi che mi hai passato. La stringa cryptText = "ZQeUG/fd0nsExLrdbwYZMg==" è la codifica base64 che ottengo dalla cifratura in AS3 del testo "ciao a tutti" usando la chiave "4b8fdd91f44a7a4e762bb3f3b85e5838"
codice:
import javax.crypto.*;
import javax.crypto.spec.*;
import java.lang.Object;
import java.security.Key;
import java.security.KeyFactory;
import sun.misc.BASE64Encoder;
import sun.misc.BASE64Decoder;
public class prova2
{
/**
* Decrypt BASE64 encoded text using private key
* @param text The encrypted text, encoded as BASE64
* @param key The private key
* @return The unencrypted text encoded as UTF8
* @throws java.lang.Exception
*/
public static String decrypt(String text, Key key) throws Exception
{
String result;
try
{
// decrypt the text using the private key
BASE64Decoder decoder = new BASE64Decoder();
byte[] dectyptedText = decrypt(decoder.decodeBuffer(text),key);
result = new String(dectyptedText, "UTF8");
System.out.println("Decrypted text is: " + result);
}
catch (Exception e)
{
e.printStackTrace();
throw e;
}
return result;
}
public static byte[] decrypt(byte[] text, Key key) throws Exception
{
byte[] dectyptedText = null;
try
{
// decrypt the text using the private key
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
System.out.println("Start decryption");
cipher.init(Cipher.DECRYPT_MODE, key);
dectyptedText = cipher.doFinal(text);
}
catch (Exception e)
{
e.printStackTrace();
throw e;
}
return dectyptedText;
}
public static void main(String[] args) throws Exception
{
String keyStr = "4b8fdd91f44a7a4e762bb3f3b85e5838";
SecretKeySpec keySpec = new SecretKeySpec(keyStr.getBytes(), "AES");
String cryptText = "ZQeUG/fd0nsExLrdbwYZMg==";
String output = decrypt(cryptText, keySpec);
System.out.println("OUT: " + output);
}
}
So che siamo nello spazio del forum dedicato a Java ma vorrei postarvi anche il codice AS3 che effettua la cifratura
codice:
var type:String='aes-128-ecb';
var key:ByteArray;
function init():void
{
key = Hex.toArray('4b8fdd91f44a7a4e762bb3f3b85e5838';
trace("----------: " + encrypt('ciao a tutti'));
}
function encrypt(txt:String):String
{
var cleartextBytes:ByteArray = new ByteArray();
cleartextBytes.writeUTF(txt);
var pad:IPad = Crypto.getPad("pkcs5");
var cipher:ICipher = Crypto.getCipher(type, key, pad);
cipher.encrypt(cleartextBytes);
return Base64.encodeByteArray(cleartextBytes);
}
Intanto ti ringrazio per i tentativi di aiuto sinora fornitomi. Ciao