title: java.security.spec.InvalidKeySpecException: java.security.InvalidKeyException: IOException: algid parse error, not a sequence
body: <p>I have the following code implemented in java service class inside a spring microservices arquitecture:</p>
  <pre><code>@Autowired
  private UsuarioRepository usuarioRepository;
  
  public String prueba(String data) {
      
      generateKeys(data); 
      
      byte[] text=encryptPrivate(&quot;texto de prueba lala&quot;,data);
      String texto=decryptPublic(text,data);
      
      return texto;
  }
  
  public String generateKeys(String username) {
  
      KeyPairGenerator keyPairGenerator = null;
      try {
          keyPairGenerator = KeyPairGenerator.getInstance(&quot;RSA&quot;);
      } catch (NoSuchAlgorithmException e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
      }
  
      keyPairGenerator.initialize(512); // múltiplo de 64, 512 ~ 65536
  
      KeyPair keyPair = keyPairGenerator.generateKeyPair();
  
      RSAPrivateKey rsaPrivateKey = (RSAPrivateKey) keyPair.getPrivate();
      System.out.println(&quot;Private: &quot; + rsaPrivateKey);
  
      RSAPublicKey rsaPublicKey = (RSAPublicKey) keyPair.getPublic();
      System.out.println(&quot;Public: &quot; + rsaPublicKey);
      
      byte[] publicKeyBytes = keyPair.getPublic().getEncoded();
      byte[] privateKeyBytes = keyPair.getPrivate().getEncoded();
      System.out.println(&quot;Encoded: &quot; + publicKeyBytes);
      
      usuarioRepository.add(publicKeyBytes, privateKeyBytes, username);
  
      return &quot;ok&quot;;
  }
  
  public byte[] encryptPrivate(String data, String username) {
      
      //sacar clave de BBDD
      byte[] keyBytes = getPrKey(username); //new byte[(int)f.length()]; 
      EncodedKeySpec spec = new PKCS8EncodedKeySpec(keyBytes);
     
      try {
           KeyFactory kf = KeyFactory.getInstance(&quot;RSA&quot;); 
           RSAPrivateKey rsaPrivateKey = (RSAPrivateKey) kf.generatePrivate(spec);
           Cipher cipher = Cipher.getInstance(&quot;RSA&quot;);
           cipher.init(Cipher.ENCRYPT_MODE, rsaPrivateKey);
           byte[] cipherText = cipher.doFinal(data.getBytes());
           
           return cipherText;
           
      } catch (InvalidKeySpecException e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
      } catch (NoSuchAlgorithmException e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
      } catch (NoSuchPaddingException e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
      } catch (InvalidKeyException e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
      } catch (IllegalBlockSizeException e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
      } catch (BadPaddingException e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
      }
      
      
      return null;
  }
  
  public String decryptPublic(byte[] data, String username) {
  
      byte[] keyBytes = getPuKey(username); //new byte[(int)f.length()]; 
      X509EncodedKeySpec spec = new X509EncodedKeySpec(keyBytes);
      try {
           KeyFactory kf = KeyFactory.getInstance(&quot;RSA&quot;); 
           RSAPublicKey rsaPublicKey = (RSAPublicKey) kf.generatePublic(spec);
           Cipher cipher = Cipher.getInstance(&quot;RSA&quot;);
           cipher.init(Cipher.DECRYPT_MODE, rsaPublicKey); 
           byte[] plainText = cipher.doFinal(data);
           //new String(plainText);
           return new String(plainText);
           
      } catch (InvalidKeySpecException e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
      } catch (NoSuchAlgorithmException e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
      } catch (NoSuchPaddingException e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
      } catch (InvalidKeyException e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
      } catch (IllegalBlockSizeException e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
      } catch (BadPaddingException e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
      }
      return &quot;fail&quot;;      
              
  }
  </code></pre>
  <p>The problem comes when I try to recover the private key from the DDBB:</p>
  <pre><code> RSAPrivateKey rsaPrivateKey = (RSAPrivateKey) kf.generatePrivate(spec);
  </code></pre>
  <p>Im storing the key in a varbinary. I got the following error:</p>
  <p>java.security.spec.InvalidKeySpecException: java.security.InvalidKeyException: IOException : DerValue.getBigIntegerInternal, not expected 48
  at java.base/sun.security.rsa.RSAKeyFactory.engineGeneratePrivate(RSAKeyFactory.java:252)
  at java.base/java.security.KeyFactory.generatePrivate(KeyFactory.java:390)
  at com.iasec.wallet.service.WalletServiceImpl.encryptPrivate(WalletServiceImpl.java:134)
  at com.iasec.wallet.service.WalletServiceImpl.prueba(WalletServiceImpl.java:50)
  at com.iasec.wallet.controller.WalletController.encrypt1(WalletController.java:43)
  at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
  at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:78)
  at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
  at java.base/java.lang.reflect.Method.invoke(Method.java:567)
  at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:205)
  at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:150)
  at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:117)
  at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:895)
  at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:808)
  at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87)
  at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1067)
  at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:963)
  at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1006)
  at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:909)
  at javax.servlet.http.HttpServlet.service(HttpServlet.java:681)
  at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:883)
  at javax.servlet.http.HttpServlet.service(HttpServlet.java:764)
  at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:227)
  at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
  at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
  at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)
  at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
  at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:100)
  at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
  at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)
  at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
  at org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:93)
  at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
  at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)
  at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
  at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:201)
  at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
  at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)
  at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
  at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:197)
  at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:97)
  at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:540)
  at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:135)
  at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)
  at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:78)
  at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:357)
  at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:382)
  at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65)
  at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:895)
  at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1722)
  at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
  at org.apache.tomcat.util.threads.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1191)
  at org.apache.tomcat.util.threads.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:659)
  at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
  at java.base/java.lang.Thread.run(Thread.java:831)
  Caused by: java.security.InvalidKeyException: IOException : DerValue.getBigIntegerInternal, not expected 48
  at java.base/sun.security.pkcs.PKCS8Key.decode(PKCS8Key.java:133)
  at java.base/sun.security.pkcs.PKCS8Key.(PKCS8Key.java:94)
  at java.base/sun.security.rsa.RSAPrivateCrtKeyImpl.(RSAPrivateCrtKeyImpl.java:152)
  at java.base/sun.security.rsa.RSAPrivateCrtKeyImpl.newKey(RSAPrivateCrtKeyImpl.java:89)
  at java.base/sun.security.rsa.RSAKeyFactory.generatePrivate(RSAKeyFactory.java:343)
  at java.base/sun.security.rsa.RSAKeyFactory.engineGeneratePrivate(RSAKeyFactory.java:248)
  ... 54 more
  java.security.spec.InvalidKeySpecException: java.security.InvalidKeyException: IOException: algid parse error, not a sequence
  at java.base/sun.security.rsa.RSAKeyFactory.engineGeneratePublic(RSAKeyFactory.java:240)
  at java.base/java.security.KeyFactory.generatePublic(KeyFactory.java:352)
  at com.iasec.wallet.service.WalletServiceImpl.decryptPublic(WalletServiceImpl.java:209)
  at com.iasec.wallet.service.WalletServiceImpl.prueba(WalletServiceImpl.java:51)
  at com.iasec.wallet.controller.WalletController.encrypt1(WalletController.java:43)
  at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
  at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:78)
  at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
  at java.base/java.lang.reflect.Method.invoke(Method.java:567)
  at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:205)
  at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:150)
  at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:117)
  at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:895)
  at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:808)
  at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87)
  at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1067)
  at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:963)
  at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1006)
  at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:909)
  at javax.servlet.http.HttpServlet.service(HttpServlet.java:681)
  at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:883)
  at javax.servlet.http.HttpServlet.service(HttpServlet.java:764)
  at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:227)
  at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
  at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
  at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)
  at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
  at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:100)
  at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
  at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)
  at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
  at org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:93)
  at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
  at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)
  at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
  at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:201)
  at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
  at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)
  at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
  at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:197)
  at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:97)
  at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:540)
  at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:135)
  at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)
  at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:78)
  at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:357)
  at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:382)
  at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65)
  at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:895)
  at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1722)
  at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
  at org.apache.tomcat.util.threads.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1191)
  at org.apache.tomcat.util.threads.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:659)
  at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
  at java.base/java.lang.Thread.run(Thread.java:831)
  Caused by: java.security.InvalidKeyException: IOException: algid parse error, not a sequence
  at java.base/sun.security.x509.X509Key.decode(X509Key.java:397)
  at java.base/sun.security.x509.X509Key.decode(X509Key.java:402)</p>