首页 > 解决方案 > Java 密码在不同的环境中表现不同

问题描述

我已经编写了一个带有加密的 netty 服务器-客户端系统,但是如果我在笔记本电脑上使用该程序,它就无法工作,没有错误,所以我不知道问题出在哪里,我的加密工具类:

public static ByteBuf decryptWithRSA(ByteBuf encrypted, PrivateKey mykey) throws Exception {
    Cipher cipher = Cipher.getInstance("RSA");
    cipher.init(Cipher.DECRYPT_MODE, mykey);
    return wrightbytes(encrypted.alloc().buffer(), cipher.doFinal(readbytes(encrypted))); 
}

public static ByteBuf encryptWithRSA(ByteBuf encrypted, PublicKey mykey) throws Exception {
    Cipher cipher = Cipher.getInstance("RSA");
    cipher.init(Cipher.ENCRYPT_MODE, mykey);
    return wrightbytes(encrypted.alloc().buffer(), cipher.doFinal(readbytes(encrypted))); 
}






public static ByteBuf encryptWithAES(SecretKey key, ByteBuf message) throws Exception  {
    Cipher cipher = Cipher.getInstance("AES");
    cipher.init(Cipher.ENCRYPT_MODE, key);
    return wrightbytes(message.alloc().buffer(), cipher.doFinal(readbytes(message)));
}

public static ByteBuf dycryptWithAES(SecretKey key, ByteBuf message) throws Exception {
    Cipher cipher = Cipher.getInstance("AES");
    cipher.init(Cipher.DECRYPT_MODE, key);
    return wrightbytes(message.alloc().buffer(), cipher.doFinal(readbytes(message)));
}

public static SecretKey generateAESKey(int size) throws NoSuchAlgorithmException {
     KeyGenerator kgen = KeyGenerator.getInstance("AES");
        kgen.init(size);
        return kgen.generateKey();
}

private static ByteBuf wrightbytes(ByteBuf wright, byte[] data) {
    int i = 0;
    while (i < data.length) {
        wright.writeByte(data[i]);
        i++;
    }
    return wright;
}

private static byte[] readbytes(ByteBuf buf) {
    int read = buf.readableBytes();
    byte[] data = new byte[read];
    int i = buf.readerIndex();
    while (i < read) {
        data[i] = buf.readByte();
        i++;
    }
    return data;
}

也许有人发现我没有得到的错误?那是你的帮助

标签: javaencryption

解决方案


推荐阅读