AES Java Encryption C # decryption (128-ECB encryption mode) __java

Source: Internet
Author: User
Tags pkcs7

One of the problems encountered in the project:

Java end needs to have some data AES encrypted to C # end, find a lot of information, be solved, share:

Import Sun.misc.BASE64Decoder;

Import Sun.misc.BASE64Encoder;
Import Javax.crypto.Cipher;
Import Javax.crypto.KeyGenerator;

Import Java.security.SecureRandom;

  public class Aesencodeutil {private final static String Transferkey = "qazwsxedcrfv12345";
    public static void Main (string[] args) throws Exception {String a = Aestransferencrypt ("qazwsx123!@#$%^&*");
    System.out.println (a);

  System.out.println (Aestransferdncrypt (a)); /** * The encryption * @param content * @return * @throws Exception/public static String Aestransferencryp
  T (String content) throws Exception {return Base64Encode (aesencrypttobytes (content, Transferkey)); /** * @param content * @return * @throws Exception/public static String Aestransferdncryp
  T (String encryptstr) throws Exception {return aesdecryptbybytes (Base64decode (ENCRYPTSTR), Transferkey); /** * Base encode * @param bytes to be encoded byte[] * @return Encoded BASE CODe */private static String base64encode (byte[] bytes) {return new Base64encoder (). Encode (bytes);
  /** * Base decode * @param base64code decoded byte[] * @throws Exception * * * @return to be decoded * private static byte[] Base64decode (String base64code) throws Exception {return new Base64decoder (). Decodebuffer (BAS
  E64code);
   /** * AES Encryption * @param content to be encrypted * @param encryptkey encryption Key * @return encrypted byte[] * @throws Exception */private static byte[] Aesencrypttobytes (string content, String Encryptkey) throws Exception {Keygenerator kge
    n = keygenerator.getinstance ("AES");
    SecureRandom securerandom = securerandom.getinstance ("sha1prng");
    Securerandom.setseed (Encryptkey.getbytes ());
    Kgen.init (128, SecureRandom);
    Cipher Cipher = cipher.getinstance ("AES");
    Cipher.init (Cipher.encrypt_mode, Kgen.generatekey ());
  Return cipher.dofinal (Content.getbytes ("UTF-8")); /** * AES Decryption * @param ENCRYPTbytes to be decrypted byte[] * @param decryptkey decryption Key * @return decrypted String * @throws Exception/private static string Aesdecryptbybytes (byte[] encryptbytes, String decryptkey) throws Exception {Keygenerator KGen = Keygenerator.getinst
    ance ("AES");
    SecureRandom securerandom = securerandom.getinstance ("sha1prng");
    Securerandom.setseed (Decryptkey.getbytes ());
    Kgen.init (128, SecureRandom);
    Cipher Cipher = cipher.getinstance ("AES");
    Cipher.init (Cipher.decrypt_mode,kgen.generatekey ());
    byte[] decryptbytes = cipher.dofinal (encryptbytes);
  return new String (Decryptbytes, "UTF-8"); }
}

Java code encryption/decryption run Result:

Encryption Result: bkscor7ek4jto5hcw5oxqs8hwg2srhtgfmctz8t/45g=
decryption Result: qazwsx123!@#$%^&*

Look at the C # code again:

<summary>///AES Encryption (128-ECB encryption mode)///</summary>///<param name= "Toencrypt"
        Content </param>///<param name= "key" > Secret key </param>///<returns></returns> public static string Aesencrypt (string toencrypt, String key) {byte[] Keyarray = convert.frombase64s
            Tring (key);

            byte[] Toencryptarray = Encoding.UTF8.GetBytes (Toencrypt);
            RijndaelManaged Rdel = new RijndaelManaged ();
            Rdel.key = Keyarray;
            Rdel.mode = CIPHERMODE.ECB;

            rdel.padding = PADDINGMODE.PKCS7;
            ICryptoTransform ctransform = Rdel.createencryptor ();

            byte[] Resultarray = Ctransform.transformfinalblock (toencryptarray, 0, toencryptarray.length);
        Return convert.tobase64string (resultarray, 0, resultarray.length); ///<summary>///AES decryption (128-ECB encryption mode)///</summary>///<param Name= "Todecrypt" > redaction </param>///<param name= "key" > Secret key (base64string) </param>///<r 
            eturns></returns> public static string Aesdecrypt (string todecrypt, string key) {try {byte[] Keyarray = convert.frombase64string (key);//128bit byte[] Toencrypta
                Rray = convert.frombase64string (Todecrypt);
                RijndaelManaged Rdel = new RijndaelManaged (); Rdel.key = Keyarray; Gets or sets the key Rdel.mode = Ciphermode.ecb of the symmetric algorithm; Gets or sets the operation mode of the symmetric algorithm, which must be set to the ECB rdel.padding = PADDINGMODE.PKCS7; Gets or sets the fill pattern used in the symmetric algorithm, which must be set to PKCS7 icryptotransform ctransform = Rdel.createdecryptor (); Creates a symmetric decryption object with the current Key property and initialization vector (IV) byte[] resultarray = Ctransform.transformfinalblock (Toencryptarray, 0,
                Toencryptarray.length);
            Return Encoding.UTF8.GetString (resultarray);
            Catch{return null; }
        }

But if you direct the Transferkey = "qazwsxedcrfv12345" and Encrypt the result: bkscor7ek4jto5hcw5oxqs8hwg2srhtgfmctz8t/45g=

To the c#,c# is unable to decrypt, because rdel.key = Keyarray; Will complain.

So what to do. In fact, we have to take Transferkey = "qazwsxedcrfv12345" treatment,

Import java.security.NoSuchAlgorithmException;
Import Javax.crypto.KeyGenerator;
Import Javax.crypto.SecretKey;
Import Sun.misc.BASE64Encoder;

public class T1 {public

static void Main (string[] args) throws nosuchalgorithmexception {
String transferkey = "BT nm018idnwtyatnnkkdtnd11_!@ $TTASdg 212c21_djtdj ";
Keygenerator KGen = keygenerator.getinstance ("AES");
Java.security.SecureRandom random = java.security.SecureRandom.getInstance ("sha1prng");
Random.setseed (Transferkey.getbytes ());
Kgen.init (128, random);
Secretkey Secretkey = Kgen.generatekey ();
byte[] Encodeformat = secretkey.getencoded ();
Base64encoder coder = new Base64encoder ();

System.out.println (Coder.encode (Encodeformat));

}

Run Result: 0ukizmhsxb0buql/l3r6aw== is the key that C # needs

See C # calls and results:

The above is just a simple example.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.