Tony Vu
Tony Vu

Reputation: 4371

Encountered InvalidKeyException on RSA encryption

I encountered the exception above while trying to encrypt with my public key.

java.security.InvalidKeyException: IOException: DerInputStream.getLength(): lengthTag=111, too big

The code is as below:

    public static String encryptWithMyPubKey (String text) throws Exception {
        if (myPubKey == null) {
            URL path = RSAUtils.class.getResource("pub.der");
            System.out.println("Path to private key file" + path.getFile());
            File f = new File(path.getFile());  
            FileInputStream fis = new FileInputStream(f);
            DataInputStream dis = new DataInputStream(fis);
            byte[] keyBytes = new byte[(int)f.length()];
            dis.readFully(keyBytes);
            dis.close();

            KeyFactory.getInstance("RSA").generatePublic(new    X509EncodedKeySpec(keyBytes));
        } 
    }

What does that mean?

Upvotes: 0

Views: 1943

Answers (1)

Tony Vu
Tony Vu

Reputation: 4371

I have fixed this issue. It is due to the wrong format of the der binary file. Maven build applied the filter on the .der files when copying them from resources folder to classpath. In order to retain the files, you need to exclude the .der files (or any binary files for that matter) by chaging your pom.xml as follows:

<plugin>
            <artifactId>maven-resources-plugin</artifactId>
            <version>2.6</version>
            <executions>
                <execution>
                    <id>copy-resources</id>
                    <!-- here the phase you need -->
                    <phase>validate</phase>
                    <goals>
                        <goal>copy-resources</goal>
                    </goals>
                    <configuration>
                        <outputDirectory>${webappDirectory}/WEB-INF/classes</outputDirectory>
                        <resources>
                            <resource>
                                <directory>src/main/java</directory>
                                <filtering>true</filtering>
                                <excludes>
                                    <exclude>**/*.der</exclude>
                                </excludes>
                            </resource>
                            <resource>
                                <directory>src/main/java</directory>
                                <filtering>false</filtering>
                                <includes>
                                    <include>**/*.der</include>
                                </includes>
                            </resource>
                        </resources>
                    </configuration>
                </execution>
            </executions>
        </plugin>

Upvotes: 5

Related Questions