Java中的ECC加密和解密

时间:2014-11-24 19:02:04

标签: java encryption public-key-encryption

我们可以使用ECC加密大型文件,还是像RSA只能用于小型文件?任何人都可以推荐一个很好的ECC Java实施网站。

由于

2 个答案:

答案 0 :(得分:3)

通常,您必需使用ECC执行hybrid encryption。例如,ECIES基本上是一个密钥协议,其后是对称加密。因此,您不能直接使用ECIES加密任何内容,这是最常用的加密ECC方法。基本上你应该把它耦合到对称密码。实际上,这也是RSA加密的最佳方案,大部分时间都是如此。


正如您所看到的,您可以使用CBC模式直接将其用作Cipher& PKCS#7填充,但要注意大标题(384曲线的117个字节,不少)。这是执行密钥派生所必需的。确保公钥正确验证 (我不确定这方面的Bouncy Castle代码,还没看过它。)

public static void main(String[] args) throws Exception {
    Security.addProvider(new BouncyCastleProvider());

    KeyPairGenerator ecKeyGen = KeyPairGenerator.getInstance("EC", BouncyCastleProvider.PROVIDER_NAME);
    ecKeyGen.initialize(new ECGenParameterSpec("brainpoolP384r1"));

    // doesn't work, which means we are dancing on the leading edge :)
    // KeyPairGenerator ecKeyGen = KeyPairGenerator.getInstance("EC");
    // ecKeyGen.initialize(new ECGenParameterSpec("secp384r1"));

    KeyPair ecKeyPair = ecKeyGen.generateKeyPair();
    System.out.println("What is slow?");

    Cipher iesCipher = Cipher.getInstance("ECIESwithAES");
    iesCipher.init(Cipher.ENCRYPT_MODE, ecKeyPair.getPublic());

    byte[] ciphertext = iesCipher.doFinal(com.google.common.base.Strings.repeat("owlstead", 1000).getBytes());

    iesCipher.init(Cipher.DECRYPT_MODE, ecKeyPair.getPrivate());
    byte[] plaintext = iesCipher.doFinal(ciphertext);

    System.out.println(Hex.toHexString(ciphertext));
    System.out.println(new String(plaintext));
}

答案 1 :(得分:1)

public static void main(String[] args) throws Exception
    {
        Security.addProvider(new BouncyCastleProvider());

        KeyPairGenerator ecKeyGen = KeyPairGenerator.getInstance("EC", BouncyCastleProvider.PROVIDER_NAME);
        ecKeyGen.initialize(new ECGenParameterSpec("secp256r1"));

        KeyPair ecKeyPair = ecKeyGen.generateKeyPair();
        System.out.println("What is slow?");

        Cipher iesCipher = Cipher.getInstance("ECIESwithAES-CBC");
        Cipher iesDecipher = Cipher.getInstance("ECIESwithAES-CBC");
        iesCipher.init(Cipher.ENCRYPT_MODE, ecKeyPair.getPublic());

        String message = "Hello World";

        byte[] ciphertext = iesCipher.doFinal(message.getBytes());
        System.out.println(Hex.toHexString(ciphertext));

        iesDecipher.init(Cipher.DECRYPT_MODE, ecKeyPair.getPrivate(), iesCipher.getParameters());
        byte[] plaintext = iesDecipher.doFinal(ciphertext);

        System.out.println(new String(plaintext));
    }