由于输入字符串,RSA解密失败

时间:2015-02-03 09:23:22

标签: java encryption rsa badpaddingexception

我有以下问题。 我的代码中有2个函数用于加密/解密简单字符串。

SO:

我必须传递一个字符串" someString "功能:

public static String doEncryption(String input) {


    try {

        if (!RSAService.areKeysPresent()) {
            RSAService.generateKey();
        }


        ObjectInputStream inputStream;

        // Encrypt the string using the public key
        inputStream = new ObjectInputStream(new FileInputStream(PUBLIC_KEY_FILE));
        PublicKey publicKey = (PublicKey) inputStream.readObject();
        byte[] cipherText = RSAService.encrypt(input, publicKey);
        return cipherText.toString();

    } catch (Exception e) {
        e.printStackTrace();
    }
    return "ERROR: Public key file is probably missing";
}

函数doEncryption("someString")返回" [B @ 61decc8c"

现在我必须将此字符串嵌入到URL中,服务器端代码应该从那里获取它。

到目前为止一切都很好,但是当我调用函数时

public static String doDecryption(String input) {

           try {

        if (!RSAService.areKeysPresent()) {
            RSAService.generateKey();
        }

        ObjectInputStream inputStream;


        // Decrypt the cipher text using the private key.
        inputStream = new ObjectInputStream(new FileInputStream(PRIVATE_KEY_FILE));
        PrivateKey privateKey = (PrivateKey) inputStream.readObject();
        String out = decrypt(input.getBytes(), privateKey);
        return out;

    } catch (Exception e) {
        e.printStackTrace();
    }
    return "ERROR: Private key file is probably missing or doesn't match the public key";
}

doDecryption("[B@61decc8c")尖叫,但有以下异常:

javax.crypto.BadPaddingException: Data must start with zero
    at sun.security.rsa.RSAPadding.unpadV15(RSAPadding.java:325)
    at sun.security.rsa.RSAPadding.unpad(RSAPadding.java:272)
    at com.sun.crypto.provider.RSACipher.doFinal(RSACipher.java:356)
    at com.sun.crypto.provider.RSACipher.engineDoFinal(RSACipher.java:382)
    at javax.crypto.Cipher.doFinal(Cipher.java:2087)
    at rsaendecryptor.RSAService.decrypt(RSAService.java:132)
    at rsaendecryptor.RSAService.doDecryption(RSAService.java:180)
    at rsaendecryptor.RSAEnDecrypt.main(RSAEnDecrypt.java:20)
java.lang.NullPointerException
    at java.lang.String.<init>(String.java:556)
    at rsaendecryptor.RSAService.decrypt(RSAService.java:138)
    at rsaendecryptor.RSAService.doDecryption(RSAService.java:180)
    at rsaendecryptor.RSAEnDecrypt.main(RSAEnDecrypt.java:20)

有什么方法可以解决这个问题吗?我必须在客户端和服务器端之间传递字符串,因为它们甚至可以在不同的域中。更不用说字符串将实际从.Net逻辑生成并发送到Java服务器端。对字符串的加密工作正常......我该怎么做才能修复解密。

以下是完整的类代码:

public class RSAService {

/**
 * String to hold name of the encryption algorithm.
 */
public static final String ALGORITHM = "RSA";

/**
 * String to hold the name of the private key file.
 */
public static final String PRIVATE_KEY_FILE = "private.key";

/**
 * String to hold name of the public key file.
 */
public static final String PUBLIC_KEY_FILE = "public.key";

/**
 * Generate key which contains a pair of private and public key using 1024
 * bytes. Store the set of keys in Prvate.key and Public.key files.
 *
 */
public static void generateKey() {

    try {
        final KeyPairGenerator keyGen = KeyPairGenerator.getInstance(ALGORITHM);
        keyGen.initialize(1024);
        final KeyPair key = keyGen.generateKeyPair();

        File privateKeyFile = new File(PRIVATE_KEY_FILE);
        File publicKeyFile = new File(PUBLIC_KEY_FILE);

        // Create files to store public and private key
        privateKeyFile.createNewFile();

        if (publicKeyFile.getParentFile() != null) {
            publicKeyFile.getParentFile().mkdirs();
        }
        publicKeyFile.createNewFile();

        // Saving the Public key in a file
        ObjectOutputStream publicKeyOS = new ObjectOutputStream(
                new FileOutputStream(publicKeyFile));
        publicKeyOS.writeObject(key.getPublic());
        publicKeyOS.close();

        // Saving the Private key in a file
        ObjectOutputStream privateKeyOS = new ObjectOutputStream(
                new FileOutputStream(privateKeyFile));
        privateKeyOS.writeObject(key.getPrivate());
        privateKeyOS.close();
    } catch (Exception e) {
        e.printStackTrace();
    }

}

/**
 * The method checks if the pair of public and private key has been
 * generated.
 *
 * @return flag indicating if the pair of keys were generated.
 */
public static boolean areKeysPresent() {

    File privateKey = new File(PRIVATE_KEY_FILE);
    File publicKey = new File(PUBLIC_KEY_FILE);

    if (privateKey.exists() && publicKey.exists()) {
        return true;
    }
    return false;
}

/**
 * Encrypt the plain text using public key.
 *
 * @param text : original plain text
 * @param key :The public key
 * @return Encrypted text
 * @throws java.lang.Exception
 */
public static byte[] encrypt(String text, PublicKey key) {
    byte[] cipherText = null;
    try {
        // get an RSA cipher object and print the provider
        final Cipher cipher = Cipher.getInstance(ALGORITHM);
        // encrypt the plain text using the public key
        cipher.init(Cipher.ENCRYPT_MODE, key);
        cipherText = cipher.doFinal(text.getBytes());
    } catch (Exception e) {
        e.printStackTrace();
    }
    return cipherText;
}

/**
 * Decrypt text using private key.
 *
 * @param text :encrypted text
 * @param key :The private key
 * @return plain text
 * @throws java.lang.Exception
 */
public static String decrypt(byte[] text, PrivateKey key) {
    byte[] dectyptedText = null;
    try {
        // get an RSA cipher object and print the provider
        final Cipher cipher = Cipher.getInstance(ALGORITHM);

        // decrypt the text using the private key
        cipher.init(Cipher.DECRYPT_MODE, key);
        dectyptedText = cipher.doFinal(text);

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

    return new String(dectyptedText);
}

public static String doEncryption(String input) {


    try {

        if (!RSAService.areKeysPresent()) {
            RSAService.generateKey();
        }


        ObjectInputStream inputStream;

        // Encrypt the string using the public key
        inputStream = new ObjectInputStream(new FileInputStream(PUBLIC_KEY_FILE));
        PublicKey publicKey = (PublicKey) inputStream.readObject();
        byte[] cipherText = RSAService.encrypt(input, publicKey);
        return cipherText.toString();

    } catch (Exception e) {
        e.printStackTrace();
    }
    return "ERROR: Public key file is probably missing";
}


public static String doDecryption(String input) {

           try {

        if (!RSAService.areKeysPresent()) {
            RSAService.generateKey();
        }

        ObjectInputStream inputStream;


        // Decrypt the cipher text using the private key.
        inputStream = new ObjectInputStream(new FileInputStream(PRIVATE_KEY_FILE));
        PrivateKey privateKey = (PrivateKey) inputStream.readObject();
        String out = decrypt(input.getBytes(), privateKey);
        return out;

    } catch (Exception e) {
        e.printStackTrace();
    }
    return "ERROR: Private key file is probably missing or doesn't match the public key";
}

}

2 个答案:

答案 0 :(得分:2)

public static String doEncryption(String input)

停在那儿。 String不是二进制数据的容器,因此不应该首先用于包含密文。它本应作为byte[]传递。

注意当你得到一个例外时,不要猜测条件是什么,并返回一个字符串,说明它可能是什么。它让调试成为一种猜测。使用异常附带的消息。

答案 1 :(得分:1)

感谢 shikjohari 和本文here我能够修复我的代码!

doEncryption()方法中我按如下方式修改了回报:

return (Base64.encode(cipherText)).toString();

并在doDecryption()方法中我修改了返回如下:

String out = decrypt(Base64.decode(input), privateKey);
return out;

您可以从我的第一篇文章中获取完整代码,然后根据这篇文章编辑两种方法的返回值。希望这会有所帮助。

相关问题