首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >DESede-ECB加密-解密

DESede-ECB加密-解密
EN

Stack Overflow用户
提问于 2021-07-17 19:57:11
回答 1查看 170关注 0票数 0

我正在尝试使用以下代码对java中的字符串进行加密和解密:

代码语言:javascript
复制
public byte[] encrypt(String message) throws Exception {
    final MessageDigest md = MessageDigest.getInstance("md5");
    final byte[] digestOfPassword = md.digest("MYKEY12345"
            .getBytes("utf-8"));
    final byte[] keyBytes = Arrays.copyOf(digestOfPassword, 24);
    for (int j = 0, k = 16; j < 8;) {
        keyBytes[k++] = keyBytes[j++];
    }

    final SecretKey key = new SecretKeySpec(keyBytes, "DESede");
//        final IvParameterSpec iv = new IvParameterSpec(new byte[8]);
    final Cipher cipher = Cipher.getInstance("DESede/ECB/PKCS5Padding");
    cipher.init(Cipher.ENCRYPT_MODE, key);

    final byte[] plainTextBytes = message.getBytes("utf-8");
    final byte[] cipherText = cipher.doFinal(plainTextBytes);
    // final String encodedCipherText = new sun.misc.BASE64Encoder()
    // .encode(cipherText);



    Log.d("base64", Base64.getEncoder().encodeToString(cipherText));

    return cipherText;
}


public String decrypt(byte[] message) throws Exception {
    final MessageDigest md = MessageDigest.getInstance("md5");
    final byte[] digestOfPassword = md.digest("MYKEY12345"
            .getBytes("utf-8"));
    final byte[] keyBytes = Arrays.copyOf(digestOfPassword, 24);
    for (int j = 0, k = 16; j < 8;) {
        keyBytes[k++] = keyBytes[j++];
    }

    final SecretKey key = new SecretKeySpec(keyBytes, "DESede");
//    final IvParameterSpec iv = new IvParameterSpec(new byte[8]);
    final Cipher decipher = Cipher.getInstance("DESede/ECB/PKCS5Padding");
    decipher.init(Cipher.DECRYPT_MODE, key);

    // final byte[] encData = new
    // sun.misc.BASE64Decoder().decodeBuffer(message);
    final byte[] plainText = decipher.doFinal(message);

    return new String(plainText, "UTF-8");
}

用法:

代码语言:javascript
复制
byte[] codedtext = new Common().encrypt("HELLOWORLD!"); // Function to get the Encrption

输出:

代码语言:javascript
复制
 base64: Ya9zBTukyOmdOh5/5vCaGA== // encrypted string converted to base64
 Encrypted : [B@d41c149 

ToDecrypt:

代码语言:javascript
复制
 String decodedtext = new Common().decrypt(codedtext); // To decrypt String

输出:

代码语言:javascript
复制
Decrypted : HELLOWORLD!  // from Encrypted string

现在,如果我使用相同的密钥和字符串在线获取加密密钥,我会得到不同的值。

验证我的加密/解密的Using this link

我刚刚开始学习加密/解密,所以对于我在这里做错的任何事情,我都很感激。

EN

回答 1

Stack Overflow用户

发布于 2021-07-17 22:36:37

你需要

代码语言:javascript
复制
final byte[] plainText = decipher.doFinal(Base64.getDecoder().decode(message));
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/68420294

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档