-2

I'm working with Java, and my colleague is working with .NET. We each have to link to a page on each other's websites. When connecting, SSO processing is required, and at this time, 'current time (yyyy-MM-dd HH:mm:ss)' must be sent and received through RSA encryption.

First of all, I'm testing whether RSA encryption and decryption work properly. My colleague shared a public key. When I encrypt and decrypt with this, I keep getting the error "Data must not be longer than 256 bytes". What's wrong with my code?

I read other similar posts. But those are not what I'm looking for. I want to implement this function without using AES algorithm.

The shared public key is like this: (I can't show you all, so I'll show you some.)

-xml type

<RSAKeyValue><Modulus>0Lvg8dDJA5z0VbYLVfzXT1pC7PJIY[...]AHuFqh/TQSuDENoLlOYfk4MSiNq2P5J6HMrj4MQ==</Modulus><Exponent>AQAB</Exponent><P>+IvTFBd3ldPsx5MYvxV[...]+kJQ==</D></RSAKeyValue>

-pem type

MIIBIjANBgkqhkiG9w0BAQ[...]5J6HMrj4MQIDAQAB

Encryption Code

    @RequestMapping(value="/ezConn/getEncryptedAkey1.do")
    @ResponseBody
        public String getEncryptedAkey1(@RequestParam String userId, HttpServletRequest request, HttpServletResponse response) {
        logger.debug("getEncryptedAkey1 started. userId=" + userId);
        
        String encryptedAkey = "";
        
        try {
            //Modulus
            String modulusInBase64 = "0Lvg8dDJA5z0VbYLVfzXT1pC7PJIY[...]AHuFqh/TQSuDENoLlOYfk4MSiNq2P5J6HMrj4MQ==";
            //Exponent
            String exponentInBase64 = "AQAB";

            java.util.Base64.Decoder decoder = java.util.Base64.getDecoder();
            String modulusInHex = toHexString(decoder.decode(modulusInBase64));
            String exponentInHex = toHexString(decoder.decode(exponentInBase64));

            BigInteger modulus = new BigInteger(modulusInHex, 16);
            BigInteger pubExp = new BigInteger(exponentInHex, 16);

            KeyFactory keyFactory = KeyFactory.getInstance("RSA");
            RSAPublicKeySpec pubKeySpec = new RSAPublicKeySpec(modulus, pubExp);
            RSAPublicKey key = (RSAPublicKey) keyFactory.generatePublic(pubKeySpec);
            Cipher cipher = Cipher.getInstance("RSA");
            cipher.init(Cipher.ENCRYPT_MODE, key);

            //the current time
            String now = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());

            byte[] cipherData = cipher.doFinal(now.getBytes());
            
            encryptedAkey = toHexString(cipherData);
                                                            
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        
        logger.debug("encryptedAkey=" + encryptedAkey);
        logger.debug("getEncryptedAkey1 ended.");
        
        return encryptedAkey;
    }
    
    private String toHexString(byte[] array) {
        return DatatypeConverter.printHexBinary(array);
    }

Decryption Code

    @RequestMapping(value = "/ezConn/getDecryptedAkey.do")
    public String getDecryptedAkey(@RequestParam String Akey, HttpServletRequest request, HttpServletResponse response) throws Exception {
        logger.debug("getDecryptedAkey started");
        
        logger.debug("Akey=" + Akey);
        String decryptedAkey = "";

        try {
            String modulusInBase64 = "0Lvg8dDJA5z0VbYLVfzXT1pC7PJIY[...]AHuFqh/TQSuDENoLlOYfk4MSiNq2P5J6HMrj4MQ==";
            String exponentInBase64 = "AQAB";

            java.util.Base64.Decoder decoder = java.util.Base64.getDecoder();
            String modulusInHex = toHexString(decoder.decode(modulusInBase64));
            String exponentInHex = toHexString(decoder.decode(exponentInBase64));

            BigInteger modulus = new BigInteger(modulusInHex, 16);
            BigInteger pubExp = new BigInteger(exponentInHex, 16);
            
            KeyFactory keyFactory = KeyFactory.getInstance("RSA");
            RSAPrivateKeySpec privateKeySpec = new RSAPrivateKeySpec(modulus, pubExp);
            RSAPrivateKey key = (RSAPrivateKey) keyFactory.generatePrivate(privateKeySpec);
            Cipher cipher = Cipher.getInstance("RSA");
            cipher.init(Cipher.DECRYPT_MODE, key);

            byte[] cipherData = cipher.doFinal(Akey.getBytes());                        
            descryptedAkey = toHexString(cipherData);
            
        }
        catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        
        logger.debug("decryptedAkey=" + decryptedAkey);
        logger.debug("getDecryptedAkey ended");
        return decryptedAkey;
    }

Error Code

2023-08-03 13:53:10,221 ERROR [http-nio-8080-exec-111] [egovframework.ezEKP.ezConn.web.EzConnController] Data must not be longer than 256 bytes
javax.crypto.IllegalBlockSizeException: Data must not be longer than 256 bytes
    at com.sun.crypto.provider.RSACipher.doFinal(RSACipher.java:347) ~[sunjce_provider.jar:1.8.0_332]
    at com.sun.crypto.provider.RSACipher.engineDoFinal(RSACipher.java:404) ~[sunjce_provider.jar:1.8.0_332]
    at javax.crypto.Cipher.doFinal(Cipher.java:2168) ~[?:1.8.0_332]
    at egovframework.ezEKP.ezConn.web.RsaTestController.getDecryptedAkey(RsaTestController.java:165) [classes/:?]

  • Paste the exact error including any line numbers (ensure the line numbers 'line up' with the code snippets, or indicate which line it is pointing at). Give us a fully self contained test-case, for example by generating a key for that purpose and including them in the question. Without that, you're asking folks to either do that work (I doubt someone would), or just stare at it and get a eureka moment. Which can happen, but, odds are a lot higher someone can figure this out for you if you help them help you. – rzwitserloot Aug 03 '23 at 05:08
  • I added the error code too. 'doFinal' in decryption code doesn't work. Do you need more information? Thank you for answering. – Sophie Cho Aug 03 '23 at 05:14
  • Why do you add the asp.net tag? That question is about java as i can see – Jens Aug 03 '23 at 05:28
  • BTW: STop using outdated classes like `SimpleDateFormat` move to the more modern `java.time` API – Jens Aug 03 '23 at 05:28
  • Take care of java naming conventions. variable names should be lower case – Jens Aug 03 '23 at 05:30
  • What is `Akey`? – Jens Aug 03 '23 at 05:31
  • Akey is an encrypted sentence. Thank you for your answering! – Sophie Cho Aug 03 '23 at 05:43
  • 1
    @SophieCho You've turned your output into a 'hex string'. However, you parse the input not as a hex string, but as ascii bytes. You'd have a reverse toHexString function and toss your input through that. – rzwitserloot Aug 03 '23 at 06:20
  • In addition to the duplicate link which answers the current problem, it appears you're also trying to make a private key out of a public key in your `getDecryptedAkey` method. That won't work. – President James K. Polk Aug 03 '23 at 11:42

0 Answers0