AES加密Java到c# [英] AES encryption Java to c#

查看:203
本文介绍了AES加密Java到c#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码,用于在java中加密/解密数据。



我需要在Windows Phone(8)设备上对C#中的数据进行加密/解密,相同的数据应该能够使用这个java代码解密/加密。



Windows Phone中C#中的这个java代码的等效代码将是什么?

  public class AESencrp {
private static final String ALGO =AES;
private static final byte [] keyValue = new byte [] {'S','D','P','i','b','m','B','H' A','R','T','I','P','K','e','y'};

public static String encrypt(String Data)throws异常{
System.out.println(.............加密开始..... ......。);
Key key = generateKey();
System.out.println(Key:+ key);
密码c = Cipher.getInstance(ALGO);
c.init(Cipher.ENCRYPT_MODE,key);
byte [] encVal = c.doFinal(Data.getBytes());
//System.out.println(\"encVal in byte []:+ encVal);
String encryptedValue = new BASE64Encoder()。encode(encVal);
System.out.println(encryptedValue byusing base64:+ encryptedValue);
System.out.println(..............加密结束............);
return encryptedValue;
}

public static String decrypt(String encryptedData)throws异常{
// final byte [] keyValue1 = new byte [] {'T','h',' e','B','e','s','t','S','e','c','r','e','t' ,'y'};
System.out.println();
System.out.println();
System.out.println(..............解密开始............);
Key key = generateKey();
// Key key = new SecretKeySpec(keyValue1,ALGO);
//System.out.println(\"Key:+ key);
密码c = Cipher.getInstance(ALGO);
c.init(Cipher.DECRYPT_MODE,key);
byte [] decordedValue = new BASE64Decoder()。decodeBuffer(encryptedData);
//System.out.println(\"decryptedValue byusing base64:+ decordedValue);
byte [] decValue = c.doFinal(decordedValue);
// System.out.println(decValue in byte []:+ decValue);
String decryptptedValue = new String(decValue);
System.out.println(解密值的字符串表示形式+ decryptptedValue);
System.out.println(..............解密结束............);
return decryptptedValue;
}
private static Key generateKey()throws Exception {
Key key = new SecretKeySpec(keyValue,ALGO);
System.out.println(key is+ keyValue);
返回键;
}


public static void main(String [] args)throws异常{
String password =encrypt_this;
String passwordEnc = AESencrp.encrypt(password);
String passwordDec = AESencrp.decrypt(passwordEnc);
System.out.println(); System.out.println();
System.out.println(纯文本:+密码);
System.out.println(Encrypted Text:+ passwordEnc);
System.out.println(解密文本:+ passwordDec);
}
}

在这段代码中,我只需要一个字符串是 -

  private static final byte [] keyValue = new byte [] {'S','D',' P','I','B','M','B','H','A','R','T','I','P' ,'y'}; 

加密数据。



休息一切都是自动完成的。



我已经看到了这个链接的一些解决方案。



http://robtiffany.com/dont-forget-to-encrypt-your-windows -phone-7-data /



但是它需要SALT值(我真的不知道是什么???)



此外,该网站表示可以跳过一些步骤,并使用预先创建的密钥和初始化向量。



在此方面的任何帮助? ?

解决方案

您可以使用本机库以与Java代码相同的方式对字符串进行加密。
您只需要将IV(Salt)设置为所需大小为16的空数组。



我已经创建了一个类来进行加密/解密和转换( byte [] string 并反转)。


$ b $我希望你不介意德国的意见。只是没有时间来翻译他们。

 静态类AesClass 
{
public static byte [] EncryptStringToBytes (string plainText,byte [] Key)
{
//Überprüfe,ob alle参数gefülltsind
if((String.IsNullOrEmpty(plainText)||(Key.Length <= 0 || Key == null)))
throw new Exception(Both values must not be null or empty);

byte []加密;

// Erstelle ein Objekt der Klasse Aes und
// belege denSchlüssel,sowie den Salt(Initalisierungsvektor)mit den Parametern
using(AesManaged aesAlgo = new AesManaged())
{
aesAlgo.Key = Key;
aesAlgo.IV​​ =新字节[16];
//Verschlüsselerzur Umwandlung erstellen
ICryptoTransform encryptor = aesAlgo.CreateEncryptor();

// Erstelle Streams,欢迎使用(MemoryStream msEncrypt = new MemoryStream())
{
using(CryptoStream csEncrypt = new CryptoStream msEncrypt,加密器,CryptoStreamMode.Write))
{
using(StreamWriter swEncrypt = new StreamWriter(csEncrypt))
{
// Schreibe die Daten in den Stream
swEncrypt.Write(明文);
}
encrypted = msEncrypt.ToArray();
}
}
}
// Gebe dieverschlüsseltenBytes aus dem Streamzurück
返回加密;
}

public static string DecryptStringFromBytes(byte [] cipherText,byte [] Key)
{
//Überprüfe,ob alle参数gefülltsind
if(((cipherText.Length< = 0 || cipherText == null)||(Key.Length< = 0 || Key == null)))
throw new Exception(Both values mustn' t为null或空);

// Erstelle eine变量,在welcherspäterderentschlüsselte文本gespeichert wird
string plaintext = null;

try
{
// Erstelle ein Objekt von AES mit begrenzterGültigkeitund
//weißedemSchlüssel(Key)und Salt(IV),die als Parameter übergebenenWerte zu
使用(AesManaged aesAlgo = new AesManaged())
{
aesAlgo.Key = Key;
aesAlgo.IV​​ =新字节[16];

// Erstelle einenEntschlüsseler,welcher denSchlüsselund Salt nutzt,
// um den ByteArray-Stream zuverändern(entschlüsseln)
ICryptoTransform decryptor = aesAlgo.CreateDecryptor(aesAlgo。 Key,aesAlgo.IV​​);

// Erstelle Stream,welche zuEntschlüsselunggenutzt werden
// Ein Stream ist eine Darstellung einer geordneten Abfolge von Bytes
using(MemoryStream msDecrypt = new MemoryStream(cipherText))
{
using(CryptoStream csDecrypt = new CryptoStream(msDecrypt,decryptor,CryptoStreamMode.Read))
{
using(StreamReader srDecrypt = new StreamReader(csDecrypt))
{
// Lese dieentschlüsseltenBytes aus dementschlüsseltenStream
// undfügesie komplett in die Variable,welche denentschlüsselteText speichert。
plaintext = srDecrypt.ReadToEnd();
}
}
}
}

}
catch(Exception ex)
{
// MessageBox 。显示(ex.Message +\r\\\
Möglichweisepasst der aktuelleSchlüsseloder Salt nicht mit jenemüberein,welcher die Datenverschlüsselthat);
返回null;
}
返回明文;
}

///
/// Wandle den String in ein ByteArray mit Base64
/// Base64 ist ein Verfahren zur Kodierung vonBinärdaten
///
public static byte [] AESStringToByteArray(string cipher)
{
byte [] encByteArray = Convert.FromBase64String(cipher);
return encByteArray;
}

///
/// Wandelt dasübergebeneBytearray in einen menschenlesbaren String。
/// Base64 ist ein Verfahren umBinärdatenzu kodieren
///
/// DieBinärdaten
/// Den gewandelten String
public static string AESByteArrayToString( byte [] arr)
{
string base64 = Convert.ToBase64String(arr);
return base64;
}
}

您可以使用以下方式的类(I猜测你在一个页面上打电话):

  private static byte [] keyValue = new byte [] {(int)'S ''(int)''''''('int''' ,(int)'',(int)'',(int)'' 'e',(int)'y'}; 


private void Button_Encrypt_Click(object sender,RoutedEventArgs e)
{
byte [] Data = AesClass.EncryptStringToBytes(TextBox_UnecryptedString.Text,keyValue);
TextBox_EncryptedString.Text = AesClass.AESByteArrayToString(Data);
}

private void Button_Decrypt_Click(object sender,RoutedEventArgs e)
{
byte [] cipherText = AesClass.AESStringToByteArray(TextBox_EncryptedString.Text);
TextBox_DecryptedString.Text = AesClass.DecryptStringFromBytes(cipherText,keyValue);
}

结果:



Java:





C#/ WP7:




I have the following code which encrypts/decrypts data for me in java

I need to encrypt/decrypt data in C# on a windows phone(8) device and same data should be able to decrypt/encrypt using this java code.

what would be the equivalent code of this java code in C# in Windows Phone??

public class AESencrp {
private static final String ALGO = "AES";
private static final byte[] keyValue = new byte[] { 'S', 'D', 'P', 'i', 'b', 'm', 'B','H', 'A', 'R', 'T','I', 'P', 'K', 'e', 'y' };

public static String encrypt(String Data) throws Exception {
    System.out.println(".............Encryption start............");
    Key key = generateKey();
    System.out.println("Key : " + key);
    Cipher c = Cipher.getInstance(ALGO);
    c.init(Cipher.ENCRYPT_MODE, key);
    byte[] encVal = c.doFinal(Data.getBytes());
    //System.out.println("encVal in byte[] : " + encVal);
    String encryptedValue = new BASE64Encoder().encode(encVal);
    System.out.println("encryptedValue byusing base64 : " + encryptedValue);
    System.out.println("..............Encryption End............");
    return encryptedValue;
}

public static String decrypt(String encryptedData) throws Exception {
    //final byte[] keyValue1 =  new byte[] { 'T', 'h', 'e', 'B', 'e', 's', 't','S', 'e', 'c', 'r','e', 't', 'K', 'e', 'y' };
    System.out.println("");
    System.out.println("");
    System.out.println(".............Decryption start............");
    Key key = generateKey();
    //Key key = new SecretKeySpec(keyValue1, ALGO);
    //System.out.println("Key : " + key);
    Cipher c = Cipher.getInstance(ALGO);
    c.init(Cipher.DECRYPT_MODE, key);
    byte[] decordedValue = new BASE64Decoder().decodeBuffer(encryptedData);
    //System.out.println("decryptedValue byusing base64 : " + decordedValue);
    byte[] decValue = c.doFinal(decordedValue);
   // System.out.println("decValue in byte[] : " + decValue);
    String decryptedValue = new String(decValue);
    System.out.println("String representation of decrypted value: " + decryptedValue);
    System.out.println(".............Decryption End............");
    return decryptedValue;
}
private static Key generateKey() throws Exception {
    Key key = new SecretKeySpec(keyValue, ALGO);
    System.out.println("key is " + keyValue  );
    return key;
}


public static void main(String[] args) throws Exception {
    String password = "encrypt_this";
    String passwordEnc = AESencrp.encrypt(password);
    String passwordDec = AESencrp.decrypt(passwordEnc);
    System.out.println("");System.out.println("");
    System.out.println("Plain Text : " + password);
    System.out.println("Encrypted Text : " + passwordEnc);
    System.out.println("Decrypted Text : " + passwordDec);
   }
}

It seems in this code I only need one piece of string which is -

private static final byte[] keyValue = new byte[] { 'S', 'D', 'P', 'i', 'b', 'm', 'B','H', 'A', 'R', 'T','I', 'P', 'K', 'e', 'y' };

to encrypt the data.

Rest everything is done automatically.

I have seen some solution on this link

http://robtiffany.com/dont-forget-to-encrypt-your-windows-phone-7-data/

But it requires SALT value (I dont really know what it is???)

also, the site says that one can skip some steps and use pre-created Key and Initialization Vector.

any help in this matter??

解决方案

You can use the native libraries to encrypt your string the same way your Java code does. You just need to set the IV(Salt) to an empty array with the needed size of 16.

I have created a class to do the encryption/decryption and converting (byte[] to string and reverse).

I hope you don't mind the german comments. Just had no time to translate them yet

static class AesClass
{
    public static byte[] EncryptStringToBytes(string plainText, byte[] Key)
    {
        // Überprüfe, ob alle Parameter gefüllt sind
        if ((String.IsNullOrEmpty(plainText) || (Key.Length <= 0 || Key == null)))
            throw new Exception("Both values mustn't be null or empty");

        byte[] encrypted;

        // Erstelle ein Objekt der Klasse Aes und
        // belege den Schlüssel, sowie den Salt (Initalisierungsvektor) mit den Parametern
        using (AesManaged aesAlgo = new AesManaged())
        {
            aesAlgo.Key = Key;
            aesAlgo.IV = new byte[16];
            //Verschlüsseler zur Umwandlung erstellen
            ICryptoTransform encryptor = aesAlgo.CreateEncryptor();

            // Erstelle Streams, welche für die Verschlüsselung genutzt werden
            using (MemoryStream msEncrypt = new MemoryStream())
            {
                using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
                {
                    using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))
                    {
                        //Schreibe die Daten in den Stream
                        swEncrypt.Write(plainText);
                    }
                    encrypted = msEncrypt.ToArray();
                }
            }
        }
        // Gebe die verschlüsselten Bytes aus dem Stream zurück
        return encrypted;
    }

    public static string DecryptStringFromBytes(byte[] cipherText, byte[] Key)
    {
        //Überprüfe, ob alle Parameter gefüllt sind
        if (((cipherText.Length <= 0 || cipherText == null) || (Key.Length <= 0 || Key == null)))
            throw new Exception("Both values mustn't be null or empty");

        //Erstelle eine Variable, in welcher später der entschlüsselte Text gespeichert wird
        string plaintext = null;

        try
        {
            // Erstelle ein Objekt von AES mit begrenzter Gültigkeit und
            // weiße dem Schlüssel (Key) und Salt (IV), die als Parameter übergebenen Werte zu
            using (AesManaged aesAlgo = new AesManaged())
            {
                aesAlgo.Key = Key;
                aesAlgo.IV = new byte[16];

                // Erstelle einen Entschlüsseler, welcher den Schlüssel und Salt nutzt,
                // um den ByteArray-Stream zu verändern (entschlüsseln)
                ICryptoTransform decryptor = aesAlgo.CreateDecryptor(aesAlgo.Key, aesAlgo.IV);

                // Erstelle Stream, welche zu Entschlüsselung genutzt werden
                // Ein Stream ist eine Darstellung einer geordneten Abfolge von Bytes
                using (MemoryStream msDecrypt = new MemoryStream(cipherText))
                {
                    using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
                    {
                        using (StreamReader srDecrypt = new StreamReader(csDecrypt))
                        {
                            // Lese die entschlüsselten Bytes aus dem entschlüsselten Stream
                            // und füge sie komplett in die Variable, welche den entschlüsselte Text speichert.
                            plaintext = srDecrypt.ReadToEnd();
                        }
                    }
                }
            }

        }
        catch (Exception ex)
        {
            //MessageBox.Show(ex.Message + "\r\nMöglichweise passt der aktuelle Schlüssel oder Salt nicht mit jenem überein, welcher die Daten verschlüsselt hat");
            return null;
        }
        return plaintext;
    }

    ///
    /// Wandle den String in ein ByteArray mit Base64
    /// Base64 ist ein Verfahren zur Kodierung von Binärdaten
    ///
    public static byte[] AESStringToByteArray(string cipher)
    {
        byte[] encByteArray = Convert.FromBase64String(cipher);
        return encByteArray;
    }

    ///
    /// Wandelt das übergebene Bytearray in einen menschenlesbaren String.
    /// Base64 ist ein Verfahren um Binärdaten zu kodieren
    ///
    ///Die Binärdaten
    /// Den gewandelten String
    public static string AESByteArrayToString(byte[] arr)
    {
        string base64 = Convert.ToBase64String(arr);
        return base64;
    }
}

You can use the class in the following way (I guess you call in on a page):

private static byte[] keyValue = new byte[] { (int)'S', (int)'D', (int)'P', (int)'i', (int)'b', (int)'m', (int)'B', (int)'H', 
        (int)'A', (int)'R', (int)'T', (int)'I', (int)'P', (int)'K', (int)'e', (int)'y' };


private void Button_Encrypt_Click(object sender, RoutedEventArgs e)
{
    byte[] Data = AesClass.EncryptStringToBytes(TextBox_UnecryptedString.Text, keyValue);
    TextBox_EncryptedString.Text = AesClass.AESByteArrayToString(Data);
}

private void Button_Decrypt_Click(object sender, RoutedEventArgs e)
{
    byte[] cipherText = AesClass.AESStringToByteArray(TextBox_EncryptedString.Text); 
    TextBox_DecryptedString.Text = AesClass.DecryptStringFromBytes(cipherText, keyValue);
}

Result:

Java:

C#/WP7:

这篇关于AES加密Java到c#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆