加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

java – AES加密j2me

发布时间:2020-12-14 19:23:54 所属栏目:Java 来源:网络整理
导读:我正在尝试在j2me中进行AES加密.我使用几乎相同的 android代码,它在那里工作正常.以下是代码块.我输出为null package cartoon;import javax.crypto.Cipher;import javax.crypto.spec.IvParameterSpec;import javax.crypto.spec.SecretKeySpec;public class M
我正在尝试在j2me中进行AES加密.我使用几乎相同的 android代码,它在那里工作正常.以下是代码块.我输出为null
package cartoon;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

public class MCrypt {

private String iv = "0123456789abcdef";// iv 
private IvParameterSpec ivspec;
private SecretKeySpec keyspec;
private Cipher cipher;
private String SecretKey = "fedcba9876543210";// secretKey 

public MCrypt() {
    ivspec = new IvParameterSpec(iv.getBytes(),iv.getBytes().length);

    keyspec = new SecretKeySpec(SecretKey.getBytes(),iv.getBytes().length,"AES");

}

String Decrypt(String text) throws Exception {
    cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");

    cipher.init(Cipher.DECRYPT_MODE,keyspec,ivspec);
    byte[] results = null;
    int results1 = cipher.doFinal(Base64.decode(text),Base64.decode(text).length,results,0);
    System.out.println("String resultssssssssssssss " + results1);
    return new String(results,"UTF-8");
}

String Encrypt(String text)
        throws Exception {
    cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");

    System.out.println("String input : " + text);

    cipher.init(Cipher.ENCRYPT_MODE,ivspec);
    byte[] results = null;
    int results1 = cipher.doFinal(text.getBytes(),text.getBytes().length,0);
    return Base64.encode(results);
}
}

打印结果

MCrypt mcrypt = new MCrypt();
    try {
        encrypted = mcrypt.Encrypt("id=450");

        decrypted = new String(mcrypt.Decrypt(encrypted));
        System.out.println("Encrypted Text : " + encrypted);
        System.out.println("Decrypted Text : " + decrypted);

    } catch (Exception e) {
        e.printStackTrace();
    }

我哪里错了?

解决方法

请尝试以下方法

您应该首先适当地初始化字节数组

String Decrypt(String text) throws Exception {
    cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");

    cipher.init(Cipher.DECRYPT_MODE,ivspec);

    // here
    byte[] results = cipher.doFinal(Base64.decode(text));

    int results1 = cipher.doFinal(Base64.decode(text),"UTF-8");
}

String Encrypt(String text)
    throws Exception {
    cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");

    System.out.println("String input : " + text);

    cipher.init(Cipher.ENCRYPT_MODE,ivspec);

    // and here
    byte[] results = cipher.doFinal(text.getBytes());

    int results1 = cipher.doFinal(text.getBytes(),0);
    return Base64.encode(results);
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读