场景

  • 对接一个第三方api接口,其中签名部分用的是JDK8的编码。我们线上采用JDK7,导致项目无法编译
  • 替换编解码部分为1.7的代码,然后签名又不对
  • 所以坑就在这里,结论,1.7的编解码有换行符导致签名失败

贴代码

import sun.misc.BASE64Decoder;
import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.Signature;
import java.security.spec.PKCS8EncodedKeySpec;
import java.util.Base64;

public class Base64EncodeDemo {

    public static final String CHARSET_UTF_8 = "UTF-8";
    public static final String ALGORITHM_RSA = "RSA";
    public static final String ALGORITHM_SHA1_WITH_RSA = "SHA1withRSA";
    private static String signWithRSAJdk7(String source, String privateKey, String algorithm) {
        String result = null;
        try {
            // 修改为 1.7语法
            // PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(Base64.getDecoder().decode(privateKey));
            PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(new BASE64Decoder().decodeBuffer(privateKey));
            KeyFactory keyFactory = KeyFactory.getInstance(ALGORITHM_RSA);
            PrivateKey pk = keyFactory.generatePrivate(spec);
            Signature signature = Signature.getInstance(algorithm);
            signature.initSign(pk);
            signature.update(source.getBytes(CHARSET_UTF_8));

            // 修改为 1.7语法
            //result = Base64.getEncoder().encodeToString(signature.sign());
            result = new sun.misc.BASE64Encoder().encode(signature.sign());
            System.out.println("jdk7解码签名换行符去掉前:"+result);

            // 1.7语法需要去掉换行符 这里是重点
            result = result.replaceAll("\\n","");
            System.out.println("jdk7解码签名换行符去掉后:"+result);
        } catch (Exception e) {
            System.out.println("RSA 签名出错!");
            e.printStackTrace();
        }
        return result;
    }

    private static String signWithRSAJdk8(String source, String privateKey, String algorithm) {
        String result = null;
        try {
            PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(Base64.getDecoder().decode(privateKey));
            KeyFactory keyFactory = KeyFactory.getInstance(ALGORITHM_RSA);
            PrivateKey pk = keyFactory.generatePrivate(spec);
            Signature signature = Signature.getInstance(algorithm);
            signature.initSign(pk);
            signature.update(source.getBytes(CHARSET_UTF_8));
            result = Base64.getEncoder().encodeToString(signature.sign());
            System.out.println("jdk8解码签名:"+result);
        } catch (Exception e) {
            System.out.println("RSA 签名出错!");
            e.printStackTrace();
        }
        return result;
    }

       public static void main(String[] args) throws Exception {
            String source = "app_id=89be0bb80a7a4e219b4011168c478f0c&biz_content={\"user_id\":\"17681865480\",\"idcard\":\"09612707419874225X\",\"name\":\"张三\",\"mobile\":\"17681865480\"}&format=JSON&method=moxie.api.risk.magicwand3.enhance-multi-info&sign_type=RSA&timestamp=1567593061041&version=1.0";

            String privatekey= "MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQDjAKaU7DbXOMoa63pF1ArcyMPWmMxmmfpBlewFHDnqFee5Gm3XdLR+fvGj+ZwddEx27ZJkkjVoXmk1/NqT+9nFXvXSctfHu6OsmYaWguCCHDjMLzuWKhuTtFohFUJQLIyfuVImzGKPv1WMoPsjouz1trTXHwpF5oj0mqI1B0HZDBsb55Dyl3DkfIaZBkr7s0tuJ/LBIhengMp2gBc9d61Qr1S6mSAv1Hj6IrL34gkZv0U0+bdDO227/r14KS4MTaHudYM7fb43f0+VEcBXUKnQgR+f6yCq67JJyPaPQYtvrf+J6azrr1+hlX6FFGWNYwaKRblgg+b5ICw5hrR2H97LAgMBAAECggEAPH565isA/mAC9COWxS8Z6faSwgicSCd2mq3SZRY9lNVbmGejqAxQ4XkA+lrVsL/CdNsg7S5Nj0/BqAKHWXJ/eWqyBfBW8sJdfuy3AjtEi0fsFvXrYjw8dyNT9YcN0gHdQ9+GNhK3nWk26jAoXTnY/i4/iSibez9RdiYTXiBd+vIPXC/KpjyN8GXiDNg2Zc9aSK6M7Bqvy5w7QDyl+YHw55DIAjdXYkGR645xO3rhMaLcQ1SiUN0lvjKqGaHIjSYBPRjPuk4GFz6Ews0d+xdl3cMNodVosx3yNjKLTSYbJlwIYrcSMlBDjN3h6ZwY4znrehNuWAjhUvn0SI2NUupRAQKBgQD7BLyJXWsItGZPFTa8KBlg1GHphzmFXO6izZNb7CQPEklyDYKsrU2ZgMWtNJ2vDJ2d8PyzO5qILp8WUFOKgQTK7NJNemH1c2dcRVINRgiK5wN7xwp4mpm396X8flbArYYkHFXzFrt62DeJtvOWDgnUTETA/fvs2HdbUuQgLYBzSwKBgQDngeeTkKumR4NAFD7pC6galxB1vlzl3cAYQyCPE/DNo9INX+TmFPH1/JrSwSPUqC6KBTIJ2zkUpJm1XpGb4QZnlx4xNWwpjE+1fpjjer1a60t9V7Jur2DOiR83kzhE7NJ2ymnVv94v9wje1yhDnMyHY9KOppWeSIoam6XSB8+SgQKBgHHJd92c50QO4sG+kA1C8B4gqDHABqcZtWM/ZSkqJj5ev8Rfs3irJp4K7ZDSZRhQ07Ig56wnvKk22Q64YuZKDe4e5EYS0Az/vz7ofYVe1ciBZ+bYFzsMedoW/Ls0WgcFoeUEo0GKcHoDQUnAETNYMcR2vkPt3iFDDvfq31Zmye95AoGBALoQ1U/ryZnGBj49R2bEoKJmYatQiZeSR274nLWCIFsW3J81QGKP2PyMvt6+ro6fcXAqxtHXKSRnOsbjsAHptN0TPwfr2Pf3tqS3kCfcoU3uqOif0GBXgmXdHYLsRyBWer1Q6AkMwYYpdS6tHMZiwpvaZgOS7dOel6jVCkwpTPKBAoGBALu3R6ABaZx8c4C56ucL79akf1iw7s/3tpS3h3FJ5NzNeovtkmCuHosFWQkA4VKXQvL0S1zwWVd9/YJot5q05o5xn13yDhhmXqd8Da+ZMQJH0PMMyVlKF9tj7o6G5ZhFCTqZdVDdKE05De89d9ybNH3dGWU4ZycfbRa3pHmRuaHO";
            String sign7 = signWithRSAJdk7(source, privatekey, ALGORITHM_SHA1_WITH_RSA);
            String sign8 = signWithRSAJdk8(source, privatekey, ALGORITHM_SHA1_WITH_RSA);
            // System.out.println(msg);
            System.out.println("--------------");
            System.out.println(sign7.equals(sign8));
    }
}

  • 运行结果:
jdk7解码签名换行符去掉前:QXEvl/xDLanJ6GfB+eeZbawiKZwF3m1HzUr6r0GIk7DtWzI1GlOLt2au5aeqiIREwEi2sErRU/gU
HCJFH1h1SfhADsw1i0xEC3C9lBU+SQCy8asEYZKnLMEsodVB2XhpBo0VkbR2dQad06kfPZoQ8qD5
jTs/3xVJswATiGIVw7tGZaTO0VUwTt2v091MRMq3L80dg765QH2JMc/VzVoVCbYzcElzdwi9tNme
zkzqtRnWIwCkc6gwfTsr+3mh4zIfyeB78/vTfdY84tYxh0Lxy1PXKP4SBUktaGUvuKDDsnycpoMK
hCJU/WgCsmBe4Aj6+4IbnK2gUSMBOba06Cm6cA==
jdk7解码签名换行符去掉后:QXEvl/xDLanJ6GfB+eeZbawiKZwF3m1HzUr6r0GIk7DtWzI1GlOLt2au5aeqiIREwEi2sErRU/gUHCJFH1h1SfhADsw1i0xEC3C9lBU+SQCy8asEYZKnLMEsodVB2XhpBo0VkbR2dQad06kfPZoQ8qD5jTs/3xVJswATiGIVw7tGZaTO0VUwTt2v091MRMq3L80dg765QH2JMc/VzVoVCbYzcElzdwi9tNmezkzqtRnWIwCkc6gwfTsr+3mh4zIfyeB78/vTfdY84tYxh0Lxy1PXKP4SBUktaGUvuKDDsnycpoMKhCJU/WgCsmBe4Aj6+4IbnK2gUSMBOba06Cm6cA==
jdk8解码签名:QXEvl/xDLanJ6GfB+eeZbawiKZwF3m1HzUr6r0GIk7DtWzI1GlOLt2au5aeqiIREwEi2sErRU/gUHCJFH1h1SfhADsw1i0xEC3C9lBU+SQCy8asEYZKnLMEsodVB2XhpBo0VkbR2dQad06kfPZoQ8qD5jTs/3xVJswATiGIVw7tGZaTO0VUwTt2v091MRMq3L80dg765QH2JMc/VzVoVCbYzcElzdwi9tNmezkzqtRnWIwCkc6gwfTsr+3mh4zIfyeB78/vTfdY84tYxh0Lxy1PXKP4SBUktaGUvuKDDsnycpoMKhCJU/WgCsmBe4Aj6+4IbnK2gUSMBOba06Cm6cA==
--------------
true

结论

  • JDK1.7 编解码
编码
new sun.misc.BASE64Encoder().encode(byte[] array)
解码
new BASE64Decoder().decodeBuffer(String str)
  • JDK1.8 编解码
编码
Base64.getEncoder().encodeToString(byte[] array)
解码
Base64.getDecoder().decode(String str)
  • 注意换行这个坑
  • 1.8 变单例,线程安全提升了

版权声明:本文为Profound原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://www.cnblogs.com/Profound/p/11463335.html