java - 这个加密代码有什么问题吗?

标签 java encryption cryptography public-key-encryption

我有以下代码可以生成 AES-128 一次性 key 。之后,我使用从证书读取的 RSA 公钥加密该一次性 key 。加密后的字节始终为0。为什么?

    // Generate a one-time key
    KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
    keyGenerator.init(128);
    SecretKey oneTimeKey = keyGenerator.generateKey();
    System.out.println("Encrypted bytes length: " + oneTimeKey.getEncoded().length); // prints "Plain bytes length: 16"

    // Retrieve public key from certificate
    FileInputStream fileInputStream = new FileInputStream("D:\\test.cer");
    CertificateFactory factory = CertificateFactory.getInstance("X.509");
    X509Certificate certificate = (X509Certificate) factory.generateCertificate(fileInputStream);
    PublicKey publicKey = certificate.getPublicKey();

    // Encrypt one-time key using the public key.
    Cipher cipher = Cipher.getInstance("RSA");
    cipher.init(Cipher.ENCRYPT_MODE, publicKey);
    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    CipherOutputStream cipherOutputStream = new CipherOutputStream(byteArrayOutputStream, cipher);
    cipherOutputStream.write(oneTimeKey.getEncoded(), 0, oneTimeKey.getEncoded().length);

    // Retrieve the encrypted bytes.
    System.out.println("Encrypted bytes length: " + byteArrayOutputStream.toByteArray().length); // prints "Encrypted bytes length: 0"
    cipherOutputStream.close();

最佳答案

在获取字节数组之前尝试刷新密码输出流。

关于java - 这个加密代码有什么问题吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28450929/

相关文章:

hash - Golang md5 Sum() 函数

java - AWS 高级运行状况报告显示内存警告 - 是我的 Java 内存设置造成的吗?

java - 在 linux 机器上使用 java 调用 Excel 宏

ios - 在 iOS 中保护数据。钥匙串(keychain)或任何其他方法?

java - 密码 block 链接 : XOR implementation in Java

math - SHA(-1-2-3) 是一对一的函数,输入的长度与输出的长度相同吗?

java - 在java中创建我自己的paint方法

java - 首次在 Google AppEngine Standard 项目上运行 gradle 时出现 NullPointerException

java - 如何保护android中的sqlite db不被盗

encryption - 仅使用n e和c进行RSA解密