java.security.InvalidKeyException: Wrong key size 5C

java.security.InvalidKeyException: Wrong key size
at javax.crypto.spec.DESedeKeySpec.(DESedeKeySpec.java:85) ~[na:1.8.0_121]
at javax.crypto.spec.DESedeKeySpec.(DESedeKeySpec.java:62) ~[na:1.8.0_121]
at com.eastcom.ipnet.agent.util.ThreeDESUtil.des3EncodeECB(ThreeDESUtil.java:37) ~[classes/:na]
at com.eastcom.ipnet.agent.service.impl.LdapAccountServiceImpl.passwordOperator(LdapAccountServiceImpl.java:246) ~[classes/:na]
at com.eastcom.ipnet.agent.service.impl.LdapAccountServiceImpl$$FastClassBySpringCGLIB$$c64b97cc.invoke() ~[classes/:na]
at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:204) ~[spring-core-4.3.8.RELEASE.jar:4.3.8.RELEASE]
at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:669) ~[spring-aop-4.3.8.RELEASE.jar:4.3.8.RELEASE]
at com.eastcom.ipnet.agent.service.impl.LdapAccountServiceImpl$$EnhancerBySpringCGLIB$$55ac0a20.passwordOperator() ~[classes/:na]
at com.eastcom.ipnet.agent.controller.AccountController.test(AccountController.java:81) ~[classes/:na]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_144]
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_144]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_144]
at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_144]
at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:205) ~[spring-web-4.3.8.RELEASE.jar:4.3.8.RELEASE]
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:133) ~[spring-web-4.3.8.RELEASE.jar:4.3.8.RELEASE]
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:97) ~[spring-webmvc-4.3.8.RELEASE.jar:4.3.8.RELEASE]
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:827) ~[spring-webmvc-4.3.8.RELEASE.jar:4.3.8.RELEASE]
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:738) ~[spring-webmvc-4.3.8.RELEASE.jar:4.3.8.RELEASE]
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85) ~[spring-webmvc-4.3.8.RELEASE.jar:4.3.8.RELEASE]
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:963) ~[spring-webmvc-4.3.8.RELEASE.jar:4.3.8.RELEASE]
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:897) ~[spring-webmvc-4.3.8.RELEASE.jar:4.3.8.RELEASE]
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970) ~[spring-webmvc-4.3.8.RELEASE.jar:4.3.8.RELEASE]
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:861) ~[spring-webmvc-4.3.8.RELEASE.jar:4.3.8.RELEASE]
at javax.servlet.http.HttpServlet.service(HttpServlet.java:635) ~[tomcat-embed-core-8.5.14.jar:8.5.14]
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846) ~[spring-webmvc-4.3.8.RELEASE.jar:4.3.8.RELEASE]
at javax.servlet.http.HttpServlet.service(HttpServlet.java:742) ~[tomcat-embed-core-8.5.14.jar:8.5.14]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231) ~[tomcat-embed-core-8.5.14.jar:8.5.14]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-8.5.14.jar:8.5.14]
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52) ~[tomcat-embed-websocket-8.5.14.jar:8.5.14]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-8.5.14.jar:8.5.14]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-8.5.14.jar:8.5.14]
at com.alibaba.druid.support.http.WebStatFilter.doFilter(WebStatFilter.java:123) ~[druid-1.1.6.jar:1.1.6]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-8.5.14.jar:8.5.14]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-8.5.14.jar:8.5.14]
at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:99) ~[spring-web-4.3.8.RELEASE.jar:4.3.8.RELEASE]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-4.3.8.RELEASE.jar:4.3.8.RELEASE]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-8.5.14.jar:8.5.14]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-8.5.14.jar:8.5.14]
at org.springframework.web.filter.HttpPutFormContentFilter.doFilterInternal(HttpPutFormContentFilter.java:105) ~[spring-web-4.3.8.RELEASE.jar:4.3.8.RELEASE]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-4.3.8.RELEASE.jar:4.3.8.RELEASE]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-8.5.14.jar:8.5.14]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-8.5.14.jar:8.5.14]
at org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:81) ~[spring-web-4.3.8.RELEASE.jar:4.3.8.RELEASE]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-4.3.8.RELEASE.jar:4.3.8.RELEASE]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-8.5.14.jar:8.5.14]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-8.5.14.jar:8.5.14]
at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:197) ~[spring-web-4.3.8.RELEASE.jar:4.3.8.RELEASE]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-4.3.8.RELEASE.jar:4.3.8.RELEASE]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-8.5.14.jar:8.5.14]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-8.5.14.jar:8.5.14]
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:198) ~[tomcat-embed-core-8.5.14.jar:8.5.14]
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96) [tomcat-embed-core-8.5.14.jar:8.5.14]
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:478) [tomcat-embed-core-8.5.14.jar:8.5.14]
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140) [tomcat-embed-core-8.5.14.jar:8.5.14]
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:80) [tomcat-embed-core-8.5.14.jar:8.5.14]
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87) [tomcat-embed-core-8.5.14.jar:8.5.14]
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:342) [tomcat-embed-core-8.5.14.jar:8.5.14]
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:799) [tomcat-embed-core-8.5.14.jar:8.5.14]
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66) [tomcat-embed-core-8.5.14.jar:8.5.14]
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:861) [tomcat-embed-core-8.5.14.jar:8.5.14]
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1455) [tomcat-embed-core-8.5.14.jar:8.5.14]
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) [tomcat-embed-core-8.5.14.jar:8.5.14]
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149) [na:1.8.0_144]
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624) [na:1.8.0_144]
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) [tomcat-embed-core-8.5.14.jar:8.5.14]
at java.lang.Thread.run(Thread.java:748) [na:1.8.0_144]

图片说明测试运行到图中标注的这行代码是就报上面的这个错了,求各路大神,看到的帮忙解答下,谢谢

bug

2个回答

传过来的keys是否是24位秘钥,但是一些实现支持16字节密钥,其中前8个字节在场景后“自动重复”。
public static byte[] encrypt3DESECB(byte[] keyBytes, byte[] dataBytes) {
try {
if (keyBytes.length == 16) { // short key ? .. extend to 24 byte key
byte[] tmpKey = new byte[24];
System.arraycopy(keyBytes, 0, tmpKey, 0, 16);
System.arraycopy(keyBytes, 0, tmpKey, 16, 8);
keyBytes = tmpKey;
}
SecretKeySpec newKey = new SecretKeySpec(keyBytes, "DESede");

            应该就可以了

不知道你传入的keys是什么,按照你的写法,应该是base64的,但是长度够么?如果不是base64,而是字符串,那么用

new DESedeKeySpec(keys.getBytes());

caozhy
贵阳老马马善福专业维修游泳池堵漏防水工程 那你试试我写的。
接近 2 年之前 回复
qq_34177910
星 少 回复caozhy: 应该用什么去解码这个key
接近 2 年之前 回复
qq_34177910
星 少 回复caozhy: 不是,,key就是这个,不能换的,,纳雍什么区解码这个key
接近 2 年之前 回复
caozhy
贵阳老马马善福专业维修游泳池堵漏防水工程 回复qq_34177910: key我怎么知道,这个要问你自己啊。
接近 2 年之前 回复
qq_34177910
星 少 回复caozhy: 那应该换成什么
接近 2 年之前 回复
caozhy
贵阳老马马善福专业维修游泳池堵漏防水工程 回复qq_34177910: 对啊,显然不是base64的
接近 2 年之前 回复
qq_34177910
星 少 byte[] key = new BASE64Decoder().decodeBuffer(keys);里面的keys是#s^un2ye31<cn%|aoXpR,+vh这个密钥,字符串的
接近 2 年之前 回复
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
其他相关推荐
Shiro认证产生的 java.security.InvalidKeyException: Invalid AES key length: 58 bytes

这个错误是咋回事呢? org.apache.shiro.crypto.CryptoException: Unable to init cipher instance. at org.apache.shiro.crypto.JcaCipherService.init(JcaCipherService.java:495) ~[shiro-all-1.2.3.jar:1.2.3] at org.apache.shiro.crypto.JcaCipherService.initNewCipher(JcaCipherService.java:598) ~[shiro-all-1.2.3.jar:1.2.3] at org.apache.shiro.crypto.JcaCipherService.crypt(JcaCipherService.java:444) ~[shiro-all-1.2.3.jar:1.2.3] at org.apache.shiro.crypto.JcaCipherService.encrypt(JcaCipherService.java:324) ~[shiro-all-1.2.3.jar:1.2.3] at org.apache.shiro.crypto.JcaCipherService.encrypt(JcaCipherService.java:313) ~[shiro-all-1.2.3.jar:1.2.3] at org.apache.shiro.mgt.AbstractRememberMeManager.encrypt(AbstractRememberMeManager.java:473) ~[shiro-all-1.2.3.jar:1.2.3] at org.apache.shiro.mgt.AbstractRememberMeManager.convertPrincipalsToBytes(AbstractRememberMeManager.java:362) ~[shiro-all-1.2.3.jar:1.2.3] at org.apache.shiro.mgt.AbstractRememberMeManager.rememberIdentity(AbstractRememberMeManager.java:346) ~[shiro-all-1.2.3.jar:1.2.3] at org.apache.shiro.mgt.AbstractRememberMeManager.rememberIdentity(AbstractRememberMeManager.java:321) ~[shiro-all-1.2.3.jar:1.2.3] at org.apache.shiro.mgt.AbstractRememberMeManager.onSuccessfulLogin(AbstractRememberMeManager.java:297) ~[shiro-all-1.2.3.jar:1.2.3] at org.apache.shiro.mgt.DefaultSecurityManager.rememberMeSuccessfulLogin(DefaultSecurityManager.java:206) [shiro-all-1.2.3.jar:1.2.3] at org.apache.shiro.mgt.DefaultSecurityManager.onSuccessfulLogin(DefaultSecurityManager.java:291) [shiro-all-1.2.3.jar:1.2.3] at org.apache.shiro.mgt.DefaultSecurityManager.login(DefaultSecurityManager.java:285) [shiro-all-1.2.3.jar:1.2.3] at org.apache.shiro.subject.support.DelegatingSubject.login(DelegatingSubject.java:256) [shiro-all-1.2.3.jar:1.2.3] at org.apache.shiro.web.filter.authc.AuthenticatingFilter.executeLogin(AuthenticatingFilter.java:53) [shiro-all-1.2.3.jar:1.2.3] at org.apache.shiro.web.filter.authc.FormAuthenticationFilter.onAccessDenied(FormAuthenticationFilter.java:154) [shiro-all-1.2.3.jar:1.2.3] at org.apache.shiro.web.filter.AccessControlFilter.onAccessDenied(AccessControlFilter.java:133) [shiro-all-1.2.3.jar:1.2.3] at org.apache.shiro.web.filter.AccessControlFilter.onPreHandle(AccessControlFilter.java:162) [shiro-all-1.2.3.jar:1.2.3] at org.apache.shiro.web.filter.PathMatchingFilter.isFilterChainContinued(PathMatchingFilter.java:203) [shiro-all-1.2.3.jar:1.2.3] at org.apache.shiro.web.filter.PathMatchingFilter.preHandle(PathMatchingFilter.java:178) [shiro-all-1.2.3.jar:1.2.3] at org.apache.shiro.web.servlet.AdviceFilter.doFilterInternal(AdviceFilter.java:131) [shiro-all-1.2.3.jar:1.2.3] at org.apache.shiro.web.servlet.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:125) [shiro-all-1.2.3.jar:1.2.3] at org.apache.shiro.web.servlet.ProxiedFilterChain.doFilter(ProxiedFilterChain.java:66) [shiro-all-1.2.3.jar:1.2.3] at org.apache.shiro.web.servlet.AbstractShiroFilter.executeChain(AbstractShiroFilter.java:449) [shiro-all-1.2.3.jar:1.2.3] at org.apache.shiro.web.servlet.AbstractShiroFilter$1.call(AbstractShiroFilter.java:365) [shiro-all-1.2.3.jar:1.2.3] at org.apache.shiro.subject.support.SubjectCallable.doCall(SubjectCallable.java:90) [shiro-all-1.2.3.jar:1.2.3] at org.apache.shiro.subject.support.SubjectCallable.call(SubjectCallable.java:83) [shiro-all-1.2.3.jar:1.2.3] at org.apache.shiro.subject.support.DelegatingSubject.execute(DelegatingSubject.java:383) [shiro-all-1.2.3.jar:1.2.3] at org.apache.shiro.web.servlet.AbstractShiroFilter.doFilterInternal(AbstractShiroFilter.java:362) [shiro-all-1.2.3.jar:1.2.3] at org.apache.shiro.web.servlet.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:125) [shiro-all-1.2.3.jar:1.2.3] at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:343) [spring-web-3.2.8.RELEASE.jar:3.2.8.RELEASE] at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:260) [spring-web-3.2.8.RELEASE.jar:3.2.8.RELEASE] at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241) [catalina.jar:7.0.53] at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208) [catalina.jar:7.0.53] at org.springframework.orm.jpa.support.OpenEntityManagerInViewFilter.doFilterInternal(OpenEntityManagerInViewFilter.java:180) [spring-orm-3.2.8.RELEASE.jar:3.2.8.RELEASE] at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) [spring-web-3.2.8.RELEASE.jar:3.2.8.RELEASE] at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241) [catalina.jar:7.0.53] at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208) [catalina.jar:7.0.53] at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:88) [spring-web-3.2.8.RELEASE.jar:3.2.8.RELEASE] at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) [spring-web-3.2.8.RELEASE.jar:3.2.8.RELEASE] at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241) [catalina.jar:7.0.53] at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208) [catalina.jar:7.0.53] at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:220) [catalina.jar:7.0.53] at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122) [catalina.jar:7.0.53] at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:501) [catalina.jar:7.0.53] at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:170) [catalina.jar:7.0.53] at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:98) [catalina.jar:7.0.53] at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:950) [catalina.jar:7.0.53] at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116) [catalina.jar:7.0.53] at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408) [catalina.jar:7.0.53] at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1040) [tomcat-coyote.jar:7.0.53] at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:607) [tomcat-coyote.jar:7.0.53] at org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.doRun(AprEndpoint.java:2441) [tomcat-coyote.jar:7.0.53] at org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.run(AprEndpoint.java:2430) [tomcat-coyote.jar:7.0.53] at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145) [na:1.7.0_51] at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615) [na:1.7.0_51] at java.lang.Thread.run(Thread.java:744) [na:1.7.0_51] Caused by: java.security.InvalidKeyException: Invalid AES key length: 58 bytes at com.sun.crypto.provider.AESCipher.engineGetKeySize(AESCipher.java:372) ~[sunjce_provider.jar:1.7.0_51] at javax.crypto.Cipher.passCryptoPermCheck(Cipher.java:1052) ~[na:1.7.0_51] at javax.crypto.Cipher.checkCryptoPerm(Cipher.java:1023) ~[na:1.7.0_51] at javax.crypto.Cipher.implInit(Cipher.java:790) ~[na:1.7.0_51] at javax.crypto.Cipher.chooseProvider(Cipher.java:849) ~[na:1.7.0_51] at javax.crypto.Cipher.init(Cipher.java:1348) ~[na:1.7.0_51] at javax.crypto.Cipher.init(Cipher.java:1282) ~[na:1.7.0_51] at org.apache.shiro.crypto.JcaCipherService.init(JcaCipherService.java:488) ~[shiro-all-1.2.3.jar:1.2.3] ... 56 common frames omitted

支付宝java服务端 测试报错 大神来救

根本不理解支付宝提供的demo 从网上使用别人的源码 String orderStr=""; try { Map<String, String> orderMap = new LinkedHashMap<String, String>(); // 订单实体 Map<String, String> bizModel = new LinkedHashMap<String, String>(); // 公共实体 /****** 2.商品参数封装开始 *****/ // 手机端用 // 商户订单号,商户网站订单系统中唯一订单号,必填 orderMap.put("out_trade_no", "100000"); // 订单名称,必填 orderMap.put("subject", "***支付"); // 付款金额,必填 orderMap.put("total_amount", String.valueOf(10000)); // 销售产品码 必填 orderMap.put("product_code", "QUICK_WAP_PAY"); /****** --------------- 3.公共参数封装 开始 ------------------------ *****/ // 支付宝用 // 1.商户appid bizModel.put("app_id", AlipayConfig.APPID); // 2.请求网关地址 bizModel.put("method", AlipayConfig.URL); // 3.请求格式 bizModel.put("format", AlipayConfig.FORMAT); // 4.回调地址 bizModel.put("return_url", AlipayConfig.notify_url); // 5.私钥 bizModel.put("private_key", AlipayConfig.private_key); // 6.商家id bizModel.put("seller_id", AlipayConfig.partner); // 7.加密格式 bizModel.put("sign_type", AlipayConfig.sign_type + ""); /****** --------------- 3.公共参数封装 结束 ------------------------ *****/ // 实例化客户端 AlipayClient client = new DefaultAlipayClient(AlipayConfig.URL, AlipayConfig.APPID, AlipayConfig.private_key, AlipayConfig.FORMAT, AlipayConfig.input_charset, AlipayConfig.ali_public_key, AlipayConfig.sign_type); // 实例化具体API对应的request类,类名称和接口名称对应,当前调用接口名称:alipay.trade.app.pay AlipayTradeAppPayRequest ali_request = new AlipayTradeAppPayRequest(); // SDK已经封装掉了公共参数,这里只需要传入业务参数。以下方法为sdk的model入参方式(model和biz_content同时存在的情况下取biz_content)。 AlipayTradeAppPayModel model = new AlipayTradeAppPayModel(); // model.setPassbackParams(URLEncoder.encode((String)orderMap.get("body").toString()));; // //描述信息 添加附加数据 // model.setBody(orderMap.get("body")); //商品信息 model.setSubject(orderMap.get("subject")); // 商品名称 model.setOutTradeNo(orderMap.get("out_trade_no")); // 商户订单号(自动生成) model.setTotalAmount(orderMap.get("total_amount")); // 支付金额 model.setProductCode(orderMap.get("product_code")); // 销售产品码 model.setSellerId(AlipayConfig.partner); // 商家id ali_request.setBizModel(model); ali_request.setNotifyUrl(AlipayConfig.notify_url); // 回调地址 AlipayTradeAppPayResponse responses = client.sdkExecute(ali_request); orderStr = responses.getBody(); System.err.println(orderStr); // 就是orderString 可以直接给客户端请求,无需再做处理 } catch (Exception e) { e.printStackTrace(); } return orderStr; AlipayConfig是配置文件 包含密钥之类的 报错为 com.alipay.api.AlipayApiException: RSAcontent = alipay_sdk=alipay-sdk-java-dynamicVersionNo&app_id=2018030202299464&biz_content={"out_trade_no":"100000","product_code":"QUICK_WAP_PAY","seller_id":"2088031415344595","subject":"***支付","total_amount":"10000"}&charset=utf-8&format=json&method=alipay.trade.app.pay&sign_type=RSA2&timestamp=2018-04-12 11:55:38&version=1.0; charset = utf-8 at com.alipay.api.internal.util.AlipaySignature.rsa256Sign(AlipaySignature.java:141) at com.alipay.api.internal.util.AlipaySignature.rsaSign(AlipaySignature.java:102) at com.alipay.api.DefaultAlipayClient.getRequestHolderWithSign(DefaultAlipayClient.java:323) at com.alipay.api.DefaultAlipayClient.sdkExecute(DefaultAlipayClient.java:163) at com.yinuoapp.controller.Alipay00200009Controller.alipay(Alipay00200009Controller.java:83) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:497) at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:222) at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:137) at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:110) at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:814) at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:737) at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85) at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:959) at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:893) at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:969) at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:860) at javax.servlet.http.HttpServlet.service(HttpServlet.java:624) at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:845) at javax.servlet.http.HttpServlet.service(HttpServlet.java:731) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208) at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208) at com.yinuo.server.Filters.doFilter(Filters.java:50) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208) at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:121) at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:218) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122) at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:505) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:169) at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103) at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:958) at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:452) at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1087) at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:637) at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:316) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) at java.lang.Thread.run(Thread.java:745) Caused by: java.security.spec.InvalidKeySpecException: java.security.InvalidKeyException: IOException : DER input, Integer tag error at sun.security.rsa.RSAKeyFactory.engineGeneratePrivate(RSAKeyFactory.java:217) at java.security.KeyFactory.generatePrivate(KeyFactory.java:372) at com.alipay.api.internal.util.AlipaySignature.getPrivateKeyFromPKCS8(AlipaySignature.java:202) at com.alipay.api.internal.util.AlipaySignature.rsa256Sign(AlipaySignature.java:123) ... 48 more Caused by: java.security.InvalidKeyException: IOException : DER input, Integer tag error at sun.security.pkcs.PKCS8Key.decode(PKCS8Key.java:351) at sun.security.pkcs.PKCS8Key.decode(PKCS8Key.java:356) at sun.security.rsa.RSAPrivateCrtKeyImpl.<init>(RSAPrivateCrtKeyImpl.java:91) at sun.security.rsa.RSAPrivateCrtKeyImpl.newKey(RSAPrivateCrtKeyImpl.java:75) at sun.security.rsa.RSAKeyFactory.generatePrivate(RSAKeyFactory.java:316) at sun.security.rsa.RSAKeyFactory.engineGeneratePrivate(RSAKeyFactory.java:213) ... 51 more 根本不懂 求大神救我

websphere下的应用aes解密报错

java.security.InvalidKeyException: Illegal key size 网上搜的 是替换官方提供的无政策限制文件到本地jdk中 但是这个在was上行不通 换了以后不但不起作用...而且was的启动停止 都会报security的错..... 求大神啊.....帮帮忙= -

java对称解密问题

<pre name="code" class="java"> //encodedata BASE64编码后加密密文 //key BASE64编码后对称密钥对 //algorithmName 加密算法 public static String decodeforp1(String encodedata,String key,String algorithmName){ try { SecretKeySpec k = new SecretKeySpec(Base64.decode(key.getBytes()),algorithmName); //解密 Cipher cp = Cipher.getInstance(algorithmName); cp.init(Cipher.DECRYPT_MODE, k); byte[] ptext = cp.doFinal(Base64.decode(encodedata.getBytes())); String s = new String(Base64.encode(ptext)); return s; } catch (InvalidKeyException e) { e.printStackTrace(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (NoSuchPaddingException e) { e.printStackTrace(); } catch (IllegalBlockSizeException e) { e.printStackTrace(); } catch (BadPaddingException e) { e.printStackTrace(); } return null; }</pre> <br /> <br />调用过程 <br /><pre name="code" class="java">String key="HK6Jy6OrfB7ZkZg6WD/rQIZfNeFn+nrrXQCTfN7Cv3cAADoAAAAAAOPCv3cAAAAAAM35CFzU/wsIAAAAVNT/C8LWWgwUwXwDkMB8A+GrWgzEwXwDlFzAd3AgvncAAAAAZAYAAK8nVQwUwXwDZAAAAEAAAABn0/8LXNT/C9PAWgwUwXwDQAAAAATBfAMJTRN4SLuBCnzBfAMAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAABEWnGJorzX8xAuTW1+kKO3zOL5ESpEX3uYttX1BhgrP1RqgZmyzOcDID5dfY6gs8fc8gkhOlRvi6jG5QUWKDtPO7f8CyC1YQxQvmEMAAAAAASCwBckn0F6gAAAAGjT/ws="; String encodedata="MWY4OWQ5M2ZmMWFiNzk5N2VlOGViYzgwZGFlMDZhNTExYjBiNzk4Yd4j2eRQnsXNu5BWFsvJGXw="; String algorithmName="DESede"; String date=encodeforp1(data, key, algorithmName); System.out.println(date); </pre> <br /> <br />但会报错 <br /> <br />java.security.InvalidKeyException: Wrong key size <br /> at com.sun.crypto.provider.SunJCE_y.a(DashoA13*..) <br /> at com.sun.crypto.provider.SunJCE_g.a(DashoA13*..) <br /> at com.sun.crypto.provider.SunJCE_f.a(DashoA13*..) <br /> at com.sun.crypto.provider.SunJCE_f.a(DashoA13*..) <br /> at com.sun.crypto.provider.DESedeCipher.engineInit(DashoA13*..) <br /> at javax.crypto.Cipher.a(DashoA13*..) <br /> at javax.crypto.Cipher.a(DashoA13*..) <br /> at javax.crypto.Cipher.init(DashoA13*..) <br /> at javax.crypto.Cipher.init(DashoA13*..) <br /> at com.szca.authenti.util.CAUtil.encodeforp1(CAUtil.java:67) <br /> at com.szca.authenti.util.Test.main(Test.java:61) <br />求解<br/><strong>问题补充</strong><br/>没人自己顶下<br/><strong>问题补充</strong><br/>已经找出原因了 JDK对DESede算法密钥对长度是112位和168位 而我的这个密钥对是192位的<br/><strong>问题补充</strong><br/>谢谢 fastbo<br/><strong>问题补充</strong><br/>而且KEY也有很大的问题,KEY是C产生的密钥对,它把整个对象都包装在一起再返回的,所以用它来封装密钥是有问题的<br/><strong>问题补充</strong><br/>进行两天的努力已经把问题得到解决,学到的东西还真不少

java版支付宝支付demo

参数配置完毕后,运行main函数,付款成功,但是后台报异常,请问是怎么回事![图片说明](https://img-ask.csdn.net/upload/201803/29/1522329002_877596.png)

ping++ java验签(签名,公钥,charge)怎么获取

这是官网demo ``` package example; import java.io.FileInputStream; import java.security.InvalidKeyException; import java.security.KeyFactory; import java.security.NoSuchAlgorithmException; import java.security.PublicKey; import java.security.Signature; import java.security.SignatureException; import java.security.spec.X509EncodedKeySpec; import org.apache.commons.codec.binary.Base64; import Decoder.BASE64Decoder; /** * Created by sunkai on 15/5/19. webhooks 验证签名示例 * * 该实例演示如何对 ping++ webhooks 通知进行验证。 * 验证是为了让开发者确认该通知来自 ping++ ,防止恶意伪造通知。用户如果有别的验证机制,可以不进行验证签名。 * * 验证签名需要 签名、公钥、验证信息,该实例采用文件存储方式进行演示。 * 实际项目中,需要用户从异步通知的 HTTP header 中读取签名,从 HTTP body 中读取验证信息。公钥的存储方式也需要用户自行设定。 * * 该实例仅供演示如何验证签名,请务必不要直接 copy 到实际项目中使用。 * */ public class WebHooksVerifyExample { private static String filePath = "src/my-server.pub"; private static String eventPath = "src/charge"; private static String signPath = "src/sign"; /** * 验证webhooks 签名,仅供参考 * @param args * @throws Exception */ public static void main(String[] args) throws Exception { boolean result = verifyData(getByteFromFile(eventPath, false), getByteFromFile(signPath, true), getPubKey()); System.out.println("验签结果:"+result); } /** * 读取文件,部署web程序的时候,签名和验签内容需要从request中获得 * @param file * @param base64 * @return * @throws Exception */ public static byte[] getByteFromFile(String file, boolean base64) throws Exception { FileInputStream in = new FileInputStream(file); byte[] fileBytes = new byte[in.available()]; in.read(fileBytes); in.close(); String pubKey = new String(fileBytes, "UTF-8"); if (base64) { BASE64Decoder decoder = new BASE64Decoder(); fileBytes = decoder.decodeBuffer(pubKey); // fileBytes = Base64.decodeBase64(pubKey); } return fileBytes; } /** * 获得公钥 * @return * @throws Exception */ public static PublicKey getPubKey() throws Exception { // read key bytes FileInputStream in = new FileInputStream(filePath); byte[] keyBytes = new byte[in.available()]; in.read(keyBytes); in.close(); String pubKey = new String(keyBytes, "UTF-8"); pubKey = pubKey.replaceAll("(-+BEGIN PUBLIC KEY-+\\r?\\n|-+END PUBLIC KEY-+\\r?\\n?)", ""); keyBytes = Base64.decodeBase64(pubKey); // generate public key X509EncodedKeySpec spec = new X509EncodedKeySpec(keyBytes); KeyFactory keyFactory = KeyFactory.getInstance("RSA"); PublicKey publicKey = keyFactory.generatePublic(spec); return publicKey; } /** * 验证签名 * @param data * @param sigBytes * @param publicKey * @return * @throws NoSuchAlgorithmException * @throws InvalidKeyException * @throws SignatureException */ public static boolean verifyData(byte[] data, byte[] sigBytes, PublicKey publicKey) throws NoSuchAlgorithmException, InvalidKeyException, SignatureException { Signature signature = Signature.getInstance("SHA256withRSA"); signature.initVerify(publicKey); signature.update(data); return signature.verify(sigBytes); } } ```

RSA OAEP,Golang加密,Java Decrypt -BadPaddingException:解密错误

<div class="post-text" itemprop="text"> <p>I'm trying to decrypt a string which is encrypted in Golang using RSA-OAEP. but getting BadPaddingException: Decryption error. Having hard time to figure out what am I missing.. </p> <p>Here is the Golang encrypt method</p> <pre><code>func encryptString() { rootPEM := io_related.ReadFile("../../resources/pubkey.pem") //fmt.Printf("Cert String %q ", rootPEM) block, _ := pem.Decode([]byte(rootPEM)) var cert *x509.Certificate cert, _ = x509.ParseCertificate(block.Bytes) rsaPublicKey := cert.PublicKey.(*rsa.PublicKey) secretMessage := []byte("password") label := []byte("") // crypto/rand.Reader is a good source of entropy for randomizing the // encryption function. rng := rand.Reader ciphertext, err := rsa.EncryptOAEP(sha256.New(), rng, rsaPublicKey, secretMessage, label) if err != nil { fmt.Fprintf(os.Stderr, "Error from encryption: %s ", err) return } // Since encryption is a randomized function, ciphertext will be // different each time. base64EncodedString := base64.StdEncoding.EncodeToString(ciphertext) fmt.Println(base64EncodedString) } </code></pre> <p>and my java decrypt method as</p> <pre><code>public void decryptString(String base64String) throws NoSuchAlgorithmException, CertificateException, IOException, KeyStoreException, UnrecoverableKeyException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException{ FileInputStream is = new FileInputStream("priv.p12"); KeyStore keystore = KeyStore.getInstance("PKCS12"); keystore.load(is, "".toCharArray()); System.out.println("Successfully loaded"); String keyAlias = "1"; PrivateKey key = (PrivateKey)keystore.getKey(keyAlias, "".toCharArray()); System.out.println("key "+Base64.encodeBase64String(key.getEncoded())); Cipher rsaDecryptCipher; rsaDecryptCipher = Cipher.getInstance("RSA/ECB/OAEPWITHSHA-256ANDMGF1PADDING"); rsaDecryptCipher.init(Cipher.DECRYPT_MODE, key); final byte[] plainText = rsaDecryptCipher.doFinal(Base64.decodeBase64(base64String)); System.out.println("Plain : " + new String(plainText)); } </code></pre> <ol> <li>I made sure I'm using the same key pair and not a different private key</li> <li>Made sure hash algorithm used same in both encrypt and decrypt "SHA256"</li> </ol> <p>I might be missing something, Please let me know if anyone need more details. Appreciate the help!!. Thanks</p> </div>

解密(使用PHP)Java加密(PBEWithMD5AndDES)

<div class="post-text" itemprop="text"> <p>I need your help. I was asked to decrypt strings via PHP, starting by this java class:</p> <pre><code>import java.security.InvalidAlgorithmParameterException; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; import java.security.spec.AlgorithmParameterSpec; import java.security.spec.InvalidKeySpecException; import java.security.spec.KeySpec; import javax.crypto.Cipher; import javax.crypto.NoSuchPaddingException; import javax.crypto.SecretKey; import javax.crypto.SecretKeyFactory; import javax.crypto.spec.PBEKeySpec; import javax.crypto.spec.PBEParameterSpec; import com.sun.mail.util.BASE64DecoderStream; public class Decryptor { private Cipher dcipher; private static final int iterationCount = 10; private static byte[] salt = { (byte) 0xB2, (byte) 0x12, (byte) 0xD5, (byte) 0xB2, (byte) 0x44, (byte) 0x21, (byte) 0xC3, (byte) 0xC3 }; Decryptor(String passPhrase) { try { KeySpec keySpec = new PBEKeySpec(passPhrase.toCharArray(), salt, iterationCount); SecretKey key = SecretKeyFactory.getInstance("PBEWithMD5AndDES").generateSecret(keySpec); AlgorithmParameterSpec paramSpec = new PBEParameterSpec(salt, iterationCount); dcipher = Cipher.getInstance(key.getAlgorithm()); dcipher.init(Cipher.DECRYPT_MODE, key, paramSpec); } catch (InvalidAlgorithmParameterException e) { e.printStackTrace(); } catch (InvalidKeySpecException e) { e.printStackTrace(); } catch (NoSuchPaddingException e) { e.printStackTrace(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (InvalidKeyException e) { e.printStackTrace(); } } public String decrypt(String str) { try { byte[] dec = BASE64DecoderStream.decode(str.getBytes()); byte[] utf8 = dcipher.doFinal(dec); return new String(utf8, "UTF8"); } catch (Exception e) { e.printStackTrace(); } return null; } } </code></pre> <p>I don't know the Java language so I need some help to understand this encryption.</p> <p>I tried to use this code: <a href="https://github.com/KevinBusse/PBEWithMD5AndDES" rel="nofollow">https://github.com/KevinBusse/PBEWithMD5AndDES</a></p> <p>But I can't "translate" the salt to PHP string and it doesn't seem to work.</p> <p>Thank you!</p> </div>

跪求大神解答EDS的问题

package testNumber2; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; import java.security.Security; import javax.crypto.BadPaddingException; import javax.crypto.Cipher; import javax.crypto.IllegalBlockSizeException; import javax.crypto.KeyGenerator; import javax.crypto.NoSuchPaddingException; import javax.crypto.SecretKey; public class EncrypDES { // KeyGenerator 提供对称密匙生成器的功能,支持各种算法 private KeyGenerator keygen; // SecretKey 负责保存对称密匙 private SecretKey deskey; // Cipher 负责完成加密或解密的结果 private Cipher c; // 改字节数组负责保存加密的结果 private byte[] cipherByte; public EncrypDES() throws NoSuchAlgorithmException, NoSuchPaddingException { Security.addProvider(new com.sun.crypto.provider.SunJCE()); keygen = KeyGenerator.getInstance("DES"); deskey = keygen.generateKey(); c = Cipher.getInstance("DES"); } public byte[] Encrytor(String str) throws InvalidKeyException, IllegalBlockSizeException, BadPaddingException { c.init(Cipher.ENCRYPT_MODE, deskey); byte[] src = str.getBytes(); cipherByte = c.doFinal(src); return cipherByte; } public byte[] Decryptor(byte[] buff) throws InvalidKeyException,IllegalBlockSizeException,BadPaddingException { c.init(Cipher.DECRYPT_MODE, deskey); cipherByte = c.doFinal(buff); return cipherByte; } public static void main(String[] args) throws Exception { EncrypDES de1 = new EncrypDES (); String msg = "郭xx-搞笑相声全集"; byte[] encontent = de1.Encrytor(msg); // byte[] decontent = de1.Decryptor(encontent); System.out.println("明文是:"+msg); String s = new String(encontent); System.out.println("加密后:"+s); System.out.println("aaaa "+s); byte[] encontent2 = s.getBytes(); System.out.println("bbbb "+encontent2); byte[] decontent2 = de1.Decryptor(encontent2); // System.out.println("解密后:"+new String(decontent)); System.out.println("解密后:"+new String(decontent2)); } } 用EDS给注册时候的密码加密保存数据库,登陆时输入密码跟取出数据库的加密码解码后比较,用这上面的方法哪里不对,请大神帮忙

一段C#的AES加密代码,求高手指点对应的Java代码

以下C#的AES加密代码 ``` // key = "05d870d9be50f4786ac2941363abdcea"; // raw = "65220b2f8fba485590615c0b1aaea872|79e68b4638214e0e848ab2757ef2dcb"; // return "JTJ5WkDFvunfCxh9D3+1jkzabeWkOPnqrJiIztFY1v+S9H+BH/c0XkauCGCt3fewjGcGU4mkYqgQynlw4bjMTg==" ; public static string Encrypt(string encryptStr, string key) { var keyArray = Encoding.UTF8.GetBytes(key); var toEncryptArray = Encoding.UTF8.GetBytes(encryptStr); var rDel = new RijndaelManaged { Key = keyArray, Mode = CipherMode.ECB, Padding = PaddingMode.None }; var cTransform = rDel.CreateEncryptor(); var resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length); return Convert.ToBase64String(resultArray, 0, resultArray.Length); } ``` 求对应的Java代码。以下是我找到的AES加密,但运行结果不一致,求高手指点: ``` package cn.companyname.util; import java.io.UnsupportedEncodingException; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; import javax.crypto.BadPaddingException; import javax.crypto.Cipher; import javax.crypto.IllegalBlockSizeException; import javax.crypto.NoSuchPaddingException; import javax.crypto.spec.SecretKeySpec; import org.apache.commons.codec.binary.Base64; /** * 加密解密EncryptAES. */ public class EncryptAES { private static final String transform = "AES/ECB/NoPadding"; private static final String algorithm = "AES"; public static String decrypt(String content, String key) throws IllegalBlockSizeException, BadPaddingException, InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException, UnsupportedEncodingException { Cipher cipher = Cipher.getInstance(transform); byte[] encryptedBytes = Base64.decodeBase64(content.getBytes()); SecretKeySpec keySpec = new SecretKeySpec(getKey(key), algorithm); cipher.init(Cipher.DECRYPT_MODE, keySpec); byte[] decryptedBytes = cipher.doFinal(encryptedBytes); return new String(decryptedBytes, "UTF-8"); } public static String encrypt(String content, String key) throws NoSuchAlgorithmException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException, UnsupportedEncodingException, InvalidKeyException { Cipher cipher = Cipher.getInstance(transform); SecretKeySpec keySpec = new SecretKeySpec(getKey(key), algorithm); cipher.init(Cipher.ENCRYPT_MODE, keySpec); byte[] output = cipher.doFinal(content.getBytes("UTF-8")); return new String(Base64.encodeBase64(output)); } private static byte[] getKey(String strKey) throws UnsupportedEncodingException { byte[] arrBTmp = strKey.getBytes("UTF-8"); byte[] arrB = new byte[16]; // 创建一个空的16位字节数组(默认值为0) for (int i = 0; i < arrBTmp.length && i < arrB.length; i++) { arrB[i] = arrBTmp[i]; } return arrB; } public static void main(String[] args) throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException, UnsupportedEncodingException { // 以下数据是从C#程序的运行参数和结果,以期完全一致。 String key = "05d870d9be50f4786ac2941363abdcea"; String raw = "65220b2f8fba485590615c0b1aaea872|79e68b4638214e0e848ab2757ef2dcb"; String str = encrypt(raw, key); System.out.println(str); System.out.println("JTJ5WkDFvunfCxh9D3+1jkzabeWkOPnqrJiIztFY1v+S9H+BH/c0XkauCGCt3fewjGcGU4mkYqgQynlw4bjMTg=="); } } ```

在php中重新创建java hmac函数

<div class="post-text" itemprop="text"> <p><strong>This is the have code which i am currently looking into</strong></p> <pre><code>package com.security; import java.util.Map; import javax.xml.bind.DatatypeConverter; import javax.crypto.Mac; import javax.crypto.spec.SecretKeySpec; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.Iterator; public class Signature { private static final String HMAC_SHA256 = "HmacSHA256"; private static final String SECRET_KEY = "LF8np6Lk0PvQ8yQvOnsqvC5WOnRbLOEadpZOAYd22QNdXnSKI08VXfo6Kl0yV5wx"; public static String sign(Map&lt;String,String&gt; params) throws InvalidKeyException, NoSuchAlgorithmException, UnsupportedEncodingException { return sign(buildDataToSign(params), SECRET_KEY).trim(); } private static String sign(String data, String secretKey) throws InvalidKeyException, NoSuchAlgorithmException, UnsupportedEncodingException { SecretKeySpec secretKeySpec = new SecretKeySpec(secretKey.getBytes(), HMAC_SHA256); Mac mac = Mac.getInstance(HMAC_SHA256); mac.init(secretKeySpec); byte[] rawHmac = mac.doFinal(data.getBytes("UTF-8")); return DatatypeConverter.printBase64Binary(rawHmac).replace(" ", "").trim(); } private static String buildDataToSign(Map&lt;String,String&gt; params) { String[] signedFieldNames = String.valueOf(params.get("signed_fields")).split(","); ArrayList&lt;String&gt; dataToSign = new ArrayList&lt;String&gt;(); for (String signedFieldName : signedFieldNames) { dataToSign.add(signedFieldName + "=" + String.valueOf(params.get(signedFieldName)).trim()); } return commaSeparate(dataToSign); } private static String commaSeparate(ArrayList&lt;String&gt; dataToSign) { StringBuilder csv = new StringBuilder(); for (Iterator&lt;String&gt; it = dataToSign.iterator(); it.hasNext(); ) { csv.append(it.next()); if (it.hasNext()) { csv.append(","); } } return csv.toString(); } } </code></pre> <p>Here i understand that <code>hmac</code> ashing mechanism is being used and it generates <code>base64</code> like string in the end.</p> <p>I am planning to recreate the code in php which suppose to deliver the same output, can someone please explain what's actually happening here.</p> <p>Thanks in advance.</p> <p>At the end the above code generates a random string like:</p> <blockquote> <p>gPRbQMzGGu4ShTwS1NzhzObRWLuGuxvKJuVpSpOaFZk=</p> </blockquote> </div>

MCRYPT_RIJNDAEL_256 Java中的PHP加密[重复]

<div class="post-text" itemprop="text"> <div class="question-status question-originals-of-duplicate"> <p>This question already has an answer here:</p> <ul> <li> <a href="/questions/8083144/how-to-encrypt-or-decrypt-with-rijndael-and-a-block-size-of-256-bits" dir="ltr">How to encrypt or decrypt with Rijndael and a block-size of 256 bits?</a> <span class="question-originals-answer-count"> 2 answers </span> </li> </ul> </div> <p>I have the following source code provided by DHL that performs MCRYPT_RIJNDAEL_256 and MCRYPT_RIJNDAEL_128 encryption in PHP:</p> <pre><code>&lt;?php function encrypt_128($data, $key) { return base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $key, $data, MCRYPT_MODE_ECB)); } function encrypt_256($data, $key) { return base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_256, $key, $data, MCRYPT_MODE_ECB)); } $data = "sellerid=Company&amp;returnsreference=0003&amp;contents_value=101&amp;contents_description=clothes&amp;fullname=Joe%20Bloggs&amp;company=Company&amp;email=joe.bloggs@gmail.com&amp;email_confirm=joe.bloggs@gmail.com&amp;telephone=123&amp;address_line_1=1&amp;city=Acampo&amp;postcode=952200001&amp;country_code=US&amp;weight=1&amp;height=2&amp;length=3&amp;width=4"; $key = "b1U995YFbERWuzO72GmKSBWpACVIb3L9"; echo '128:' . PHP_EOL; echo encrypt_128($data, $key) . PHP_EOL; echo PHP_EOL; echo '256:' . PHP_EOL; echo encrypt_256($data, $key) . PHP_EOL; echo PHP_EOL; ?&gt; </code></pre> <p>Which outputs:</p> <pre><code>128: AEt1OHf8hjEnQYeJq07qIxj1j8M0Tyzbg4/5NCwzMwIAA72SecGEdi4XoxwXlgpTbNRyum642KVM3POo2pcPPiRiA6+WPEf6XB0eTAzIUVp8yt2Ibjk83SsNVHCK7n4lR5wXICQ4Go/zFdz68Uwc2Y2mu3SCdiferc2noyhLaInEtej8Q8yF2NwwsZreLtf/6zM7S4RKR6SDa7G2EM3wu0FjOhcyA+6HaTpl+3ZFSdMs5YwqksZjWD5SYQskVXks5y4wtw++sduJ77p2iMe/bLdIAtNwgwLHty9y7jFellxlWMeWmysmyYFNUPaoUPbXM4kDlBle3jz4sjpLiUdjQdLJIfCN6UWyQf47vFzxubt3IfsbiqHU2Qo9mHb7WQh4vtPC+U3wjM9kzV9eXcMCRQ== 256: BUMVdaCQoce//aQWEsMgSHNRsWVPvi02ljCtF1PUfEA8Wm0tTZ6EUBEGsAiTOSINwiWikaoGm5jyBRaajHgtgj4y/7R8t5KkxEwM5H9iU/X56c8H65p3pV2P7wNayLiu5eUcLJBXb+siqCCi2VFETgGOMC8o9zjXPQ0oNCYYy5+tT2NGxSGebjM7XMIOAkIKCKvSbF+lUdxPRS1vs5ILuvzx9LP4+461ZYGYmmDKX35qPbCnsx8xaYkXnhAO8W1ddm1ylcanyAFWb2hk6UUmS7SGpSmJMAVwyUDT2uFxaizL4Z6p+KeBRgjPW2i9b5gC/MpjphJO4IKhTqKfHwziinYQ6FZOtDKtD7JC8om1kINpaMIZEHLXHEHF/iuqRbaFcH+M1Qph4Uu95d0eJ0x1A2rs2zRdlWVR72RHVIWez0w= </code></pre> <p>I need to perform 256 bit Rijndael encryption in Java. I have written the following code:</p> <pre><code>import org.apache.commons.codec.binary.Base64; import javax.crypto.BadPaddingException; import javax.crypto.Cipher; import javax.crypto.IllegalBlockSizeException; import javax.crypto.NoSuchPaddingException; import javax.crypto.spec.IvParameterSpec; import javax.crypto.spec.SecretKeySpec; import java.io.UnsupportedEncodingException; import java.security.InvalidAlgorithmParameterException; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; import java.security.spec.AlgorithmParameterSpec; public class Encrypt { public static byte[] ivBytes = {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}; public static void main(String[] args) throws InvalidKeyException, UnsupportedEncodingException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException { String data = "sellerid=Company&amp;returnsreference=0003&amp;contents_value=101&amp;contents_description=clothes&amp;fullname=Joe%20Bloggs&amp;company=Company&amp;email=joe.bloggs@gmail.com&amp;email_confirm=joe.bloggs@gmail.com&amp;telephone=123&amp;address_line_1=1&amp;city=Acampo&amp;postcode=952200001&amp;country_code=US&amp;weight=1&amp;height=2&amp;length=3&amp;width=4"; String key = "b1U995YFbERWuzO72GmKSBWpACVIb3L9"; String encoded = encode(data, key); System.out.println("Encoded: " + encoded); String decoded = decode(encoded, key); System.out.println("Decoded: " + decoded); } public static String encode(String data, String key) throws java.io.UnsupportedEncodingException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException { byte[] textBytes = data.getBytes("UTF-8"); AlgorithmParameterSpec ivSpec = new IvParameterSpec(ivBytes); SecretKeySpec newKey = new SecretKeySpec(key.getBytes("UTF-8"), "AES"); Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); cipher.init(Cipher.ENCRYPT_MODE, newKey, ivSpec); return Base64.encodeBase64String(cipher.doFinal(textBytes)); } public static String decode(String data, String key) throws java.io.UnsupportedEncodingException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException { byte[] textBytes = Base64.decodeBase64(data); AlgorithmParameterSpec ivSpec = new IvParameterSpec(ivBytes); SecretKeySpec newKey = new SecretKeySpec(key.getBytes("UTF-8"), "AES"); Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); cipher.init(Cipher.DECRYPT_MODE, newKey, ivSpec); return new String(cipher.doFinal(textBytes), "UTF-8"); } } </code></pre> <p>Which is outputting:</p> <pre><code>Encoded: AEt1OHf8hjEnQYeJq07qIxtV0c4Zcfro0Yidrx/rb91OBcbyZ1RZ5id7dYCVhJe4WUvIb2OWyOVDqeVu7cHkM7zHrxRoY5hyQDWKsj4BIuxqxKO0grLYRgqQ2MZtm23D5Ko23h5sJetEYsKI1AxeXJLPQmUDB+RecELIDzJparWto9UcU6llik/v8ZX7DDmrg6K57xaSlCKWVkCKI2HivblAYwTirh7D9n/hO46c3MLngM1/Ao32S1y2XwkNX8k7PTFce5M6BLsDlzoZKjkv+t8n8GTAPPLheC0z9iLBHQbEs2WhzVY4UoCNStITWitn6QI9EwCuVX7oRVlQMi2pqow0GaGwFJ3kqGn5nbXlrbc5Lg4G8SUnM1NB01LbIEBVnVuzXQg8y+Zam47uMJ/0iQ== Decoded: sellerid=Company&amp;returnsreference=0003&amp;contents_value=101&amp;contents_description=clothes&amp;fullname=Joe%20Bloggs&amp;company=Company&amp;email=joe.bloggs@gmail.com&amp;email_confirm=joe.bloggs@gmail.com&amp;telephone=123&amp;address_line_1=1&amp;city=Acampo&amp;postcode=952200001&amp;country_code=US&amp;weight=1&amp;height=2&amp;length=3&amp;width=4 </code></pre> <p>i.e. It is encrypting it with 128 bit encryption. How do I get 256 bit Rijndael encryption?</p> </div>

关于RSA加密BUG问题懂这个的大神帮我看下谢谢

``` /** * 加密。注意密钥是可以获取到它适用的算法的。 * * @param plainText * @param privateKey * @return */ public static byte[] encode(byte[] plainFile, PrivateKey privateKey) { Cipher cipher; try { cipher = Cipher.getInstance(privateKey.getAlgorithm()); cipher.init(2, privateKey); int inputLen = plainFile.length; ByteArrayOutputStream out = new ByteArrayOutputStream(); int offSet = 0; for(int i = 0; inputLen - offSet > 0; offSet = i * 128) { byte[] cache; if(inputLen - offSet > 256) { cache = cipher.doFinal(plainFile, offSet, 128); } else { cache = cipher.doFinal(plainFile, offSet, inputLen - offSet); } out.write(cache, 0, cache.length); ++i; } byte[] decryptedData = out.toByteArray(); out.close(); return decryptedData; } 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 (IOException 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; } ``` ``` /** * 解密 * * @param encodedText * @param publicKey * @return */ public static byte[] decode(byte[] encodedText, PublicKey publicKey) { Cipher cipher; try { cipher = Cipher.getInstance(publicKey.getAlgorithm()); cipher.init(1, publicKey); int inputLen = encodedText.length; ByteArrayOutputStream out = new ByteArrayOutputStream(); int offSet = 0; for(int i = 0; inputLen - offSet > 0; offSet = i * 244) { byte[] cache; if(inputLen - offSet > 244) { cache = cipher.doFinal(encodedText, offSet, 244); } else { cache = cipher.doFinal(encodedText, offSet, inputLen - offSet); } out.write(cache, 0, cache.length); ++i; } byte[] encryptedData = out.toByteArray(); out.close(); return encryptedData; } 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(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; } ``` ``` import java.security.KeyStore; import java.security.PrivateKey; import java.security.PublicKey; import java.security.cert.X509Certificate; import com.insigma.siis.local.utils.ServerCertificateUtil; public class Test { private static final String CERT_PATH = "C:\\Users\\handong\\Downloads\\workspace\\myCer.cer"; // JDK6只支持X.509标准的证书 private static final String CERT_TYPE = "X.509"; public static void main(String[] args) throws IOException { // 接收证书 X509Certificate receivedCertificate = null; // 获取公钥 PublicKey publicKey = null; receivedCertificate = ClientCertificateUtil.getCertificateByCertPath(CERT_PATH, CERT_TYPE); publicKey = ClientCertificateUtil.getPublicKey(receivedCertificate); // 获取密钥库 KeyStore keyStore = ServerCertificateUtil.getKeyStore("Changeme123", "C:\\Users\\handong\\Downloads\\workspace\\myKeystore.keystore"); // 获取私钥 PrivateKey privateKey = ServerCertificateUtil.getPrivateKey(keyStore, "myCertificate", "Changeme123"); byte[] as = { 0x12 }; byte[] sdf = ServerCertificateUtil.encode(as, privateKey); byte[] fd = ClientCertificateUtil.decode(sdf, publicKey); for (int i = 0; i < fd.length; i++) { System.out.println(fd[1]); } } ``` ![图片说明](https://img-ask.csdn.net/upload/201708/06/1502007345_913484.png) 不知道问题出在哪了,我用的RSA

为什么小米手机谷歌验证码始终不正确,其他手机却可以通过验证

下面是代码 ``` package com.kuaiqian.miaofu.utils; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; import java.security.SecureRandom; import javax.crypto.Mac; import javax.crypto.spec.SecretKeySpec; import org.apache.commons.codec.binary.Base32; import org.apache.commons.codec.binary.Base64; public class GoogleAuthenticator { // taken from Google pam docs - we probably don't need to mess with these public static final int SECRET_SIZE = 10; public static final String SEED = "g8GjEvTbW5oVSV7avLBdwIHqGlUYNzKFI7izOF8GwLDVKs2m0QN7vxRs2im5MDaNCWGmcD2rvcZx"; public static final String RANDOM_NUMBER_ALGORITHM = "SHA1PRNG"; int window_size = 3; // default 3 - max 17 (from google docs)最多可偏移的时间 public void setWindowSize(int s) { if (s >= 1 && s <= 17) window_size = s; } public static Boolean authcode(String codes, String savedSecret) { // enter the code shown on device. Edit this and run it fast before the // code expires! long code = Long.parseLong(codes); long t = System.currentTimeMillis(); GoogleAuthenticator ga = new GoogleAuthenticator(); ga.setWindowSize(15); // should give 5 * 30 seconds of grace... boolean r = ga.check_code(savedSecret, code, t); return r; } public static String genSecret() { String secret = GoogleAuthenticator.generateSecretKey(); return secret; } public static String generateSecretKey() { SecureRandom sr = null; try { sr = SecureRandom.getInstance(RANDOM_NUMBER_ALGORITHM); sr.setSeed(Base64.decodeBase64(SEED)); byte[] buffer = sr.generateSeed(SECRET_SIZE); Base32 codec = new Base32(); byte[] bEncodedKey = codec.encode(buffer); String encodedKey = new String(bEncodedKey); return encodedKey; }catch (NoSuchAlgorithmException e) { // should never occur... configuration error } return null; } public static String getQRBarcodeURL(String user, String secret) { String format = "otpauth://totp/"+user+"?secret=" + secret; return format; } public boolean check_code(String secret, long code, long timeMsec) { Base32 codec = new Base32(); byte[] decodedKey = codec.decode(secret); // convert unix msec time into a 30 second "window" // this is per the TOTP spec (see the RFC for details) long t = (timeMsec / 1000L) / 30L; // Window is used to check codes generated in the near past. // You can use this value to tune how far you're willing to go. for (int i = -window_size; i <= window_size; ++i) { long hash; try { hash = verify_code(decodedKey, t + i); }catch (Exception e) { // Yes, this is bad form - but // the exceptions thrown would be rare and a static configuration problem e.printStackTrace(); throw new RuntimeException(e.getMessage()); //return false; } if (hash == code) { return true; } } // The validation code is invalid. return false; } private static int verify_code(byte[] key, long t) throws NoSuchAlgorithmException, InvalidKeyException { byte[] data = new byte[8]; long value = t; for (int i = 8; i-- > 0; value >>>= 8) { data[i] = (byte) value; } SecretKeySpec signKey = new SecretKeySpec(key, "HmacSHA1"); Mac mac = Mac.getInstance("HmacSHA1"); mac.init(signKey); byte[] hash = mac.doFinal(data); int offset = hash[20 - 1] & 0xF; // We're using a long because Java hasn't got unsigned int. long truncatedHash = 0; for (int i = 0; i < 4; ++i) { truncatedHash <<= 8; // We are dealing with signed bytes: // we just keep the first byte. truncatedHash |= (hash[offset + i] & 0xFF); } truncatedHash &= 0x7FFFFFFF; truncatedHash %= 1000000; return (int) truncatedHash; } } ```

Java与Golang for HOTP(RFC-4226)

<div class="post-text" itemprop="text"> <p>I'm trying to implement HOTP (rfc-4226) in Golang and I'm struggling to generate a valid HOTP. I can generate it in java but for some reason my implementation in Golang is different. Here are the samples:</p> <pre><code>public static String constructOTP(final Long counter, final String key) throws NoSuchAlgorithmException, DecoderException, InvalidKeyException { final Mac mac = Mac.getInstance("HmacSHA512"); final byte[] binaryKey = Hex.decodeHex(key.toCharArray()); mac.init(new SecretKeySpec(binaryKey, "HmacSHA512")); final byte[] b = ByteBuffer.allocate(8).putLong(counter).array(); byte[] computedOtp = mac.doFinal(b); return new String(Hex.encodeHex(computedOtp)); } </code></pre> <p>and in Go:</p> <pre><code>func getOTP(counter uint64, key string) string { str, err := hex.DecodeString(key) if err != nil { panic(err) } h := hmac.New(sha512.New, str) bs := make([]byte, 8) binary.BigEndian.PutUint64(bs, counter) h.Write(bs) return base64.StdEncoding.EncodeToString(h.Sum(nil)) } </code></pre> <p>I believe the issue is that the Java line: <code>ByteBuffer.allocate(8).putLong(counter).array();</code> generates a different byte array than the Go line: <code>binary.BigEndian.PutUint64(bs, counter)</code>.</p> <p>In Java, the following byte array is generated: <code>83 -116 -9 -98 115 -126 -3 -48</code> and in Go: <code>83 140 247 158 115 130 253 207</code>.</p> <p>Does anybody know the difference in the two lines and how I can port the java line to go?</p> </div>

亚马逊 mws对接系统时SignatureDoesNotMatch报错

错误内容: <?xml version="1.0"?> <ErrorResponse xmlns="https://mws.amazonservices.com/Orders/2013-09-01"> <Error> <Type>Sender</Type> <Code>SignatureDoesNotMatch</Code> <Message>The request signature we calculated does not match the signature you provided. Check your AWS Secret Access Key and signing method. Consult the service documentation for details.</Message> </Error> <RequestID>23142876-a0db-42f5-9ba9-527313c7bb78</RequestID> </ErrorResponse> 我的代码: public class TestUtl { private static final String CHARACTER_ENCODING = "UTF-8"; final static String ALGORITHM = "HmacSHA256"; public static void main(String[] args) throws Exception { String timestamp = AmazonTimeUtil.getAmaZonTime(); String secretKey = "iXvQ+bHDVSkaMBaXXXXXXXXXXXXXXXX"; // Use the endpoint for your marketplace String serviceUrl = "https://mws.amazonservices.com/"; // Create set of parameters needed and store in a map HashMap<String, String> parameters = new HashMap<String, String>(); // Add required parameters. Change these as needed. parameters.put("AWSAccessKeyId", urlEncode("AKIAJXAAD6Y2XXXXXXXX")); parameters.put("SignatureMethod", urlEncode("HmacSHA256")); parameters.put("SignatureVersion", urlEncode("2")); // parameters.put("SubmittedFromDate",urlEncode(submittedFromDate)); // parameters.put("SubmittedFromDate",getFormattedTimestamp()); parameters.put("Timestamp", urlEncode(timestamp)); parameters.put("Version", urlEncode("2013-09-01")); parameters.put("Action", urlEncode("ListOrders")); parameters.put("MarketplaceId",urlEncode("ATVPDKIKX0DER")); parameters.put("CreatedAfter", urlEncode("2016-05-25T10:56:00Z")); parameters.put("SellerId", urlEncode("A1VGN18HFINRY8")); parameters.put("MWSAuthToken", urlEncode("amzn.mws.b2a759cd-f24d-80f6-3cce-b543342ddd7a")); String formattedParameters = calculateStringToSignV2(parameters, serviceUrl); String signature = sign(formattedParameters, secretKey); Map<String, String> sorted = new TreeMap<String, String>(); sorted.putAll(parameters); // Add signature to the parameters and display final results parameters.put("Signature", urlEncode(signature)); System.out.println(calculateStringToSignV2(parameters, serviceUrl)); String pa = HttpUtils.prepareParam(sorted); System.out.println("url的值为:"+"https://mws.amazonservices.com/Orders/2013-09-01/?"+pa+"&Signature="+urlEncode(signature)+"\n"); try { URL url = new URL("https://mws.amazonservices.com/Orders/2013-09-01/?"+pa+"&Signature="+urlEncode(signature)); HttpsURLConnection conn = (HttpsURLConnection) url.openConnection(); conn.setConnectTimeout(50000); BufferedReader br = null; StringBuffer sbOrderResponse = new StringBuffer(); String order = ""; String str = ""; InputStream inputstream = null; if (conn.getResponseCode() != 200) { inputstream = conn.getErrorStream(); } else { inputstream = conn.getInputStream(); } br = new BufferedReader(new InputStreamReader((inputstream))); StringBuffer buffer = new StringBuffer(); while ((order = br.readLine()) != null) { sbOrderResponse.append(order); str = str + order + "\n"; } System.out.println(conn.getResponseCode() + " " + conn.getResponseMessage()); System.out.println(str); } catch (Exception e) { System.out.println("Error " + e); } } private static String calculateStringToSignV2(Map<String, String> parameters, String serviceUrl) throws SignatureException, URISyntaxException { // Sort the parameters alphabetically by storing // in TreeMap structure Map<String, String> sorted = new TreeMap<String, String>(); sorted.putAll(parameters); // Set endpoint value URI endpoint = new URI(serviceUrl.toLowerCase()); // Create flattened (String) representation StringBuilder data = new StringBuilder(); data.append("GET\n"); data.append(endpoint.getHost()); data.append("\n/Orders/2013-09-01"); // /Orders/2013-09-01 data.append("\n"); Iterator<Entry<String, String>> pairs = sorted.entrySet().iterator(); while (pairs.hasNext()) { Map.Entry<String, String> pair = pairs.next(); if (pair.getValue() != null) { data.append(pair.getKey() + "=" + pair.getValue()); } else { data.append(pair.getKey() + "="); } // Delimit parameters with ampersand (&) if (pairs.hasNext()) { data.append("&"); } } return data.toString(); } /* * Sign the text with the given secret key and convert to base64 */ private static String sign(String data, String secretKey) throws NoSuchAlgorithmException, InvalidKeyException, IllegalStateException, UnsupportedEncodingException { Mac mac = Mac.getInstance(ALGORITHM); mac.init(new SecretKeySpec(secretKey.getBytes(CHARACTER_ENCODING), ALGORITHM)); byte[] signature = mac.doFinal(data.getBytes(CHARACTER_ENCODING)); String signatureBase64 = new String(Base64.encodeBase64(signature), CHARACTER_ENCODING); return new String(signatureBase64); } private static String urlEncode(String rawValue) { String value = (rawValue == null) ? "" : rawValue; String encoded = null; try { encoded = URLEncoder.encode(value, CHARACTER_ENCODING).replace("+", "%20").replace("*", "%2A") .replace("%7E", "~"); } catch (UnsupportedEncodingException e) { System.err.println("Unknown encoding: " + CHARACTER_ENCODING); e.printStackTrace(); } return encoded; } }

下面Java的AES加密,用c#怎么实现?要一样的结果哦

public static String encrypt(String content, String key) { try { KeyGenerator kgen = KeyGenerator.getInstance("AES"); SecureRandom random = SecureRandom.getInstance("SHA1PRNG"); random.setSeed(key.getBytes()); kgen.init(128, random); SecretKey secretKey = kgen.generateKey(); byte[] enCodeFormat = secretKey.getEncoded(); SecretKeySpec secretKeySpec = new SecretKeySpec(enCodeFormat, "AES"); Cipher cipher = Cipher.getInstance("AES"); byte[] byteContent = content.getBytes("utf-8"); cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec); byte[] byteRresult = cipher.doFinal(byteContent); StringBuffer sb = new StringBuffer(); for (int i = 0; i < byteRresult.length; i++) { String hex = Integer.toHexString(byteRresult[i] & 0xFF); if (hex.length() == 1) { hex = '0' + hex; } sb.append(hex.toUpperCase()); } return sb.toString(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (NoSuchPaddingException e) { e.printStackTrace(); } catch (InvalidKeyException e) { e.printStackTrace(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (IllegalBlockSizeException e) { e.printStackTrace(); } catch (BadPaddingException e) { e.printStackTrace(); } return null; }

从文件加载加密的PKCS1私钥

<div class="post-text" itemprop="text"> <p>I have a PKCS1 private key in a file and I load it using </p> <pre><code>b, err := ioutil.ReadFile(path) if err != nil { return nil, err } </code></pre> <p>Then, I try to convert it into private key object</p> <pre><code>block, _ := pem.Decode(b) der, err := x509.DecryptPEMBlock(block, []byte("qwerty")) if err != nil { return nil, err } bytes := pem.EncodeToMemory(&amp;pem.Block{Type: "RSA PRIVATE KEY", Bytes: der}) return x509.ParsePKCS1PrivateKey(bytes) </code></pre> <p>But this code throws exception in <code>DecryptPEMBlock</code> </p> <pre><code>x509: no DEK-Info header in block </code></pre> <p>I didn't find any documentation about this in golang</p> </div>

Java / PHP加密CAST-256

<div class="post-text" itemprop="text"> <p>I have this legacy Code in PHP that I want to reproduce in Java:</p> <pre><code>function enCrypt($data = null) { $key = 'thisismysupersecretkeyglhf1'; $encoded=mcrypt_encrypt(MCRYPT_CAST_256, $key, $data, MCRYPT_MODE_ECB ); $encoded = base64_encode($encoded); return $encoded; } function deCrypt($data = null) { $key = 'thisismysupersecretkeyglhf1'; $decrypted= mcrypt_decrypt( MCRYPT_CAST_256, $key, base64_decode($data), MCRYPT_MODE_ECB ); return $decrypted; } </code></pre> <p>I am using Bouncy Castle CAST-6 Engine in the following way:</p> <pre><code>public static final String KEY = "thisismysupersecretkeyglhf1"; public static String encrypt(String toDecrypt) throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeySpecException, InvalidAlgorithmParameterException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException, DecoderException, UnsupportedEncodingException { Cipher cipher = Cipher.getInstance("CAST6/ECB/NoPadding"); SecretKeySpec key=new SecretKeySpec(KEY.getBytes(),"CAST6"); cipher.init(Cipher.ENCRYPT_MODE, key); String decoded=org.apache.commons.codec.binary.Base64.encodeBase64String(cipher.doFinal(toDecrypt.getBytes())); return decoded; } public static String decrypt(String toDecrypt) throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeySpecException, InvalidAlgorithmParameterException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException, DecoderException, UnsupportedEncodingException { Cipher cipher = Cipher.getInstance("CAST6/ECB/NoPadding"); SecretKeySpec key=new SecretKeySpec(KEY.getBytes(),"CAST6"); cipher.init(Cipher.DECRYPT_MODE, key); byte[] decoded=org.apache.commons.codec.binary.Base64.decodeBase64(toDecrypt); return new String(cipher.doFinal(decoded)); } </code></pre> <p>However, I'm not being able to produce the same encrypted results or decrypt anything encrypted in PHP using JAVA.</p> <p>What am I lacking? </p> <p>Is this a Padding Issue? Reading through mcrypt documentation, they seem to be doing a lot of padding to keys and data. My Key (legacy key) is 27chars long, which I believe should be padded to 32 bytes by mcrypt, since mcrypt_get_key_size(MCRYPT_CAST_256,MCRYPT_MODE_ECB) results in 32.</p> <p>For further info the string I'm trying to encrypt is "1111111111111111". I don't know if this get padded by PHP , but I would think it wouldn't because, mcrypt_get_block_size(MCRYPT_CAST_256,MCRYPT_MODE_ECB) returns 16, which is exactly the length Im using.</p> <p>I am very inexperienced in cryptography, so I'am a little bit lost. Maybe if I could debug mcrypt internals, I could have a better idea of what's happening. </p> <p>Any help implementing these functions in Java would be greatly appreciated.</p> <p>PD. I know this algorithm is not the best, and not using an IV as well as using ECB is somehow alarming, but this is only for legacy code integration. </p> </div>

大学四年自学走来,这些私藏的实用工具/学习网站我贡献出来了

大学四年,看课本是不可能一直看课本的了,对于学习,特别是自学,善于搜索网上的一些资源来辅助,还是非常有必要的,下面我就把这几年私藏的各种资源,网站贡献出来给你们。主要有:电子书搜索、实用工具、在线视频学习网站、非视频学习网站、软件下载、面试/求职必备网站。 注意:文中提到的所有资源,文末我都给你整理好了,你们只管拿去,如果觉得不错,转发、分享就是最大的支持了。 一、电子书搜索 对于大部分程序员...

在中国程序员是青春饭吗?

今年,我也32了 ,为了不给大家误导,咨询了猎头、圈内好友,以及年过35岁的几位老程序员……舍了老脸去揭人家伤疤……希望能给大家以帮助,记得帮我点赞哦。 目录: 你以为的人生 一次又一次的伤害 猎头界的真相 如何应对互联网行业的「中年危机」 一、你以为的人生 刚入行时,拿着傲人的工资,想着好好干,以为我们的人生是这样的: 等真到了那一天,你会发现,你的人生很可能是这样的: ...

Java基础知识面试题(2020最新版)

文章目录Java概述何为编程什么是Javajdk1.5之后的三大版本JVM、JRE和JDK的关系什么是跨平台性?原理是什么Java语言有哪些特点什么是字节码?采用字节码的最大好处是什么什么是Java程序的主类?应用程序和小程序的主类有何不同?Java应用程序与小程序之间有那些差别?Java和C++的区别Oracle JDK 和 OpenJDK 的对比基础语法数据类型Java有哪些数据类型switc...

我以为我学懂了数据结构,直到看了这个导图才发现,我错了

数据结构与算法思维导图

String s = new String(" a ") 到底产生几个对象?

老生常谈的一个梗,到2020了还在争论,你们一天天的,哎哎哎,我不是针对你一个,我是说在座的各位都是人才! 上图红色的这3个箭头,对于通过new产生一个字符串(”宜春”)时,会先去常量池中查找是否已经有了”宜春”对象,如果没有则在常量池中创建一个此字符串对象,然后堆中再创建一个常量池中此”宜春”对象的拷贝对象。 也就是说准确答案是产生了一个或两个对象,如果常量池中原来没有 ”宜春” ,就是两个。...

技术大佬:我去,你写的 switch 语句也太老土了吧

昨天早上通过远程的方式 review 了两名新来同事的代码,大部分代码都写得很漂亮,严谨的同时注释也很到位,这令我非常满意。但当我看到他们当中有一个人写的 switch 语句时,还是忍不住破口大骂:“我擦,小王,你丫写的 switch 语句也太老土了吧!” 来看看小王写的代码吧,看完不要骂我装逼啊。 private static String createPlayer(PlayerTypes p...

Linux面试题(2020最新版)

文章目录Linux 概述什么是LinuxUnix和Linux有什么区别?什么是 Linux 内核?Linux的基本组件是什么?Linux 的体系结构BASH和DOS之间的基本区别是什么?Linux 开机启动过程?Linux系统缺省的运行级别?Linux 使用的进程间通信方式?Linux 有哪些系统日志文件?Linux系统安装多个桌面环境有帮助吗?什么是交换空间?什么是root帐户什么是LILO?什...

Linux命令学习神器!命令看不懂直接给你解释!

大家都知道,Linux 系统有非常多的命令,而且每个命令又有非常多的用法,想要全部记住所有命令的所有用法,恐怕是一件不可能完成的任务。 一般情况下,我们学习一个命令时,要么直接百度去搜索它的用法,要么就直接用 man 命令去查看守冗长的帮助手册。这两个都可以实现我们的目标,但有没有更简便的方式呢? 答案是必须有的!今天给大家推荐一款有趣而实用学习神器 — kmdr,让你解锁 Linux 学习新姿势...

和黑客斗争的 6 天!

互联网公司工作,很难避免不和黑客们打交道,我呆过的两家互联网公司,几乎每月每天每分钟都有黑客在公司网站上扫描。有的是寻找 Sql 注入的缺口,有的是寻找线上服务器可能存在的漏洞,大部分都...

史上最全的 python 基础知识汇总篇,没有比这再全面的了,建议收藏

网友们有福了,小编终于把基础篇的内容全部涉略了一遍,这是一篇关于基础知识的汇总的文章,请朋友们收下,不用客气,不过文章篇幅肯能会有点长,耐心阅读吧爬虫(七十)多进程multiproces...

讲一个程序员如何副业月赚三万的真实故事

loonggg读完需要3分钟速读仅需 1 分钟大家好,我是你们的校长。我之前讲过,这年头,只要肯动脑,肯行动,程序员凭借自己的技术,赚钱的方式还是有很多种的。仅仅靠在公司出卖自己的劳动时...

女程序员,为什么比男程序员少???

昨天看到一档综艺节目,讨论了两个话题:(1)中国学生的数学成绩,平均下来看,会比国外好?为什么?(2)男生的数学成绩,平均下来看,会比女生好?为什么?同时,我又联想到了一个技术圈经常讨...

85后蒋凡:28岁实现财务自由、34岁成为阿里万亿电商帝国双掌门,他的人生底层逻辑是什么?...

蒋凡是何许人也? 2017年12月27日,在入职4年时间里,蒋凡开挂般坐上了淘宝总裁位置。 为此,时任阿里CEO张勇在任命书中力赞: 蒋凡加入阿里,始终保持创业者的冲劲,有敏锐的...

总结了 150 余个神奇网站,你不来瞅瞅吗?

原博客再更新,可能就没了,之后将持续更新本篇博客。

副业收入是我做程序媛的3倍,工作外的B面人生是怎样的?

提到“程序员”,多数人脑海里首先想到的大约是:为人木讷、薪水超高、工作枯燥…… 然而,当离开工作岗位,撕去层层标签,脱下“程序员”这身外套,有的人生动又有趣,马上展现出了完全不同的A/B面人生! 不论是简单的爱好,还是正经的副业,他们都干得同样出色。偶尔,还能和程序员的特质结合,产生奇妙的“化学反应”。 @Charlotte:平日素颜示人,周末美妆博主 大家都以为程序媛也个个不修边幅,但我们也许...

MySQL数据库面试题(2020最新版)

文章目录数据库基础知识为什么要使用数据库什么是SQL?什么是MySQL?数据库三大范式是什么mysql有关权限的表都有哪几个MySQL的binlog有有几种录入格式?分别有什么区别?数据类型mysql有哪些数据类型引擎MySQL存储引擎MyISAM与InnoDB区别MyISAM索引与InnoDB索引的区别?InnoDB引擎的4大特性存储引擎选择索引什么是索引?索引有哪些优缺点?索引使用场景(重点)...

新一代神器STM32CubeMonitor介绍、下载、安装和使用教程

关注、星标公众号,不错过精彩内容作者:黄工公众号:strongerHuang最近ST官网悄悄新上线了一款比较强大的工具:STM32CubeMonitor V1.0.0。经过我研究和使用之...

如果你是老板,你会不会踢了这样的员工?

有个好朋友ZS,是技术总监,昨天问我:“有一个老下属,跟了我很多年,做事勤勤恳恳,主动性也很好。但随着公司的发展,他的进步速度,跟不上团队的步伐了,有点...

我入职阿里后,才知道原来简历这么写

私下里,有不少读者问我:“二哥,如何才能写出一份专业的技术简历呢?我总感觉自己写的简历太烂了,所以投了无数份,都石沉大海了。”说实话,我自己好多年没有写过简历了,但我认识的一个同行,他在阿里,给我说了一些他当年写简历的方法论,我感觉太牛逼了,实在是忍不住,就分享了出来,希望能够帮助到你。 01、简历的本质 作为简历的撰写者,你必须要搞清楚一点,简历的本质是什么,它就是为了来销售你的价值主张的。往深...

大学一路走来,学习互联网全靠这几个网站,最终拿下了一把offer

大佬原来都是这样炼成的

离职半年了,老东家又发 offer,回不回?

有小伙伴问松哥这个问题,他在上海某公司,在离职了几个月后,前公司的领导联系到他,希望他能够返聘回去,他很纠结要不要回去? 俗话说好马不吃回头草,但是这个小伙伴既然感到纠结了,我觉得至少说明了两个问题:1.曾经的公司还不错;2.现在的日子也不是很如意。否则应该就不会纠结了。 老实说,松哥之前也有过类似的经历,今天就来和小伙伴们聊聊回头草到底吃不吃。 首先一个基本观点,就是离职了也没必要和老东家弄的苦...

为什么你不想学习?只想玩?人是如何一步一步废掉的

不知道是不是只有我这样子,还是你们也有过类似的经历。 上学的时候总有很多光辉历史,学年名列前茅,或者单科目大佬,但是虽然慢慢地长大了,你开始懈怠了,开始废掉了。。。 什么?你说不知道具体的情况是怎么样的? 我来告诉你: 你常常潜意识里或者心理觉得,自己真正的生活或者奋斗还没有开始。总是幻想着自己还拥有大把时间,还有无限的可能,自己还能逆风翻盘,只不是自己还没开始罢了,自己以后肯定会变得特别厉害...

什么时候跳槽,为什么离职,你想好了么?

都是出来打工的,多为自己着想

为什么程序员做外包会被瞧不起?

二哥,有个事想询问下您的意见,您觉得应届生值得去外包吗?公司虽然挺大的,中xx,但待遇感觉挺低,马上要报到,挺纠结的。

当HR压你价,说你只值7K,你该怎么回答?

当HR压你价,说你只值7K时,你可以流畅地回答,记住,是流畅,不能犹豫。 礼貌地说:“7K是吗?了解了。嗯~其实我对贵司的面试官印象很好。只不过,现在我的手头上已经有一份11K的offer。来面试,主要也是自己对贵司挺有兴趣的,所以过来看看……”(未完) 这段话主要是陪HR互诈的同时,从公司兴趣,公司职员印象上,都给予对方正面的肯定,既能提升HR的好感度,又能让谈判气氛融洽,为后面的发挥留足空间。...

面试阿里p7,被按在地上摩擦,鬼知道我经历了什么?

面试阿里p7被问到的问题(当时我只知道第一个):@Conditional是做什么的?@Conditional多个条件是什么逻辑关系?条件判断在什么时候执...

你期望月薪4万,出门右拐,不送,这几个点,你也就是个初级的水平

先来看几个问题通过注解的方式注入依赖对象,介绍一下你知道的几种方式@Autowired和@Resource有何区别说一下@Autowired查找候选者的...

面试了一个 31 岁程序员,让我有所触动,30岁以上的程序员该何去何从?

最近面试了一个31岁8年经验的程序猿,让我有点感慨,大龄程序猿该何去何从。

大三实习生,字节跳动面经分享,已拿Offer

说实话,自己的算法,我一个不会,太难了吧

程序员垃圾简历长什么样?

已经连续五年参加大厂校招、社招的技术面试工作,简历看的不下于万份 这篇文章会用实例告诉你,什么是差的程序员简历! 疫情快要结束了,各个公司也都开始春招了,作为即将红遍大江南北的新晋UP主,那当然要为小伙伴们做点事(手动狗头)。 就在公众号里公开征简历,义务帮大家看,并一一点评。《启舰:春招在即,义务帮大家看看简历吧》 一石激起千层浪,三天收到两百多封简历。 花光了两个星期的所有空闲时...

立即提问
相关内容推荐