Search in sources :

Example 21 with BASE64Encoder

use of sun.misc.BASE64Encoder in project jdk8u_jdk by JetBrains.

the class FtpClient method sendSecurityData.

private boolean sendSecurityData(byte[] buf) throws IOException {
    BASE64Encoder encoder = new BASE64Encoder();
    String s = encoder.encode(buf);
    return issueCommand("ADAT " + s);
}
Also used : BASE64Encoder(sun.misc.BASE64Encoder)

Example 22 with BASE64Encoder

use of sun.misc.BASE64Encoder in project jdk8u_jdk by JetBrains.

the class V3Certificate method test.

public static boolean test(String algorithm, String sigAlg, int keyLength) throws IOException, NoSuchAlgorithmException, InvalidKeyException, CertificateException, NoSuchProviderException, SignatureException {
    byte[] issuerId = { 1, 2, 3, 4, 5 };
    byte[] subjectId = { 6, 7, 8, 9, 10 };
    boolean testResult = true;
    // Subject and Issuer
    X500Name subject = new X500Name("test", "Oracle", "Santa Clara", "US");
    X500Name issuer = subject;
    // Generate keys and sign
    KeyPairGenerator keyGen = KeyPairGenerator.getInstance(algorithm);
    keyGen.initialize(keyLength);
    KeyPair pair = keyGen.generateKeyPair();
    PublicKey publicKey = pair.getPublic();
    PrivateKey privateKey = pair.getPrivate();
    MessageDigest md = MessageDigest.getInstance("SHA");
    byte[] keyId = md.digest(publicKey.getEncoded());
    Signature signature = Signature.getInstance(sigAlg);
    signature.initSign(privateKey);
    // Validity interval
    Date firstDate = new Date();
    Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("PST"));
    cal.set(2014, 03, 10, 12, 30, 30);
    Date lastDate = cal.getTime();
    CertificateValidity interval = new CertificateValidity(firstDate, lastDate);
    // Certificate Info
    X509CertInfo cert = new X509CertInfo();
    cert.set(X509CertInfo.VERSION, new CertificateVersion(CertificateVersion.V3));
    cert.set(X509CertInfo.SERIAL_NUMBER, new CertificateSerialNumber((int) (firstDate.getTime() / 1000)));
    cert.set(X509CertInfo.ALGORITHM_ID, new CertificateAlgorithmId(AlgorithmId.get(sigAlg)));
    cert.set(X509CertInfo.SUBJECT, subject);
    cert.set(X509CertInfo.KEY, new CertificateX509Key(publicKey));
    cert.set(X509CertInfo.VALIDITY, interval);
    cert.set(X509CertInfo.ISSUER, issuer);
    cert.set(X509CertInfo.ISSUER_ID, new UniqueIdentity(new BitArray(issuerId.length * 8 - 2, issuerId)));
    cert.set(X509CertInfo.SUBJECT_ID, new UniqueIdentity(subjectId));
    // Create Extensions
    CertificateExtensions exts = new CertificateExtensions();
    GeneralNameInterface mailInf = new RFC822Name("test@Oracle.com");
    GeneralName mail = new GeneralName(mailInf);
    GeneralNameInterface dnsInf = new DNSName("Oracle.com");
    GeneralName dns = new GeneralName(dnsInf);
    GeneralNameInterface uriInf = new URIName("http://www.Oracle.com");
    GeneralName uri = new GeneralName(uriInf);
    // localhost
    byte[] address = new byte[] { 127, 0, 0, 1 };
    GeneralNameInterface ipInf = new IPAddressName(address);
    GeneralName ip = new GeneralName(ipInf);
    int[] oidData = new int[] { 1, 2, 3, 4 };
    GeneralNameInterface oidInf = new OIDName(new ObjectIdentifier(oidData));
    GeneralName oid = new GeneralName(oidInf);
    SubjectAlternativeNameExtension subjectName = new SubjectAlternativeNameExtension();
    IssuerAlternativeNameExtension issuerName = new IssuerAlternativeNameExtension();
    GeneralNames subjectNames = (GeneralNames) subjectName.get(SubjectAlternativeNameExtension.SUBJECT_NAME);
    GeneralNames issuerNames = (GeneralNames) issuerName.get(IssuerAlternativeNameExtension.ISSUER_NAME);
    subjectNames.add(mail);
    subjectNames.add(dns);
    subjectNames.add(uri);
    issuerNames.add(ip);
    issuerNames.add(oid);
    cal.set(2000, 11, 15, 12, 30, 30);
    lastDate = cal.getTime();
    PrivateKeyUsageExtension pkusage = new PrivateKeyUsageExtension(firstDate, lastDate);
    KeyUsageExtension usage = new KeyUsageExtension();
    usage.set(KeyUsageExtension.CRL_SIGN, true);
    usage.set(KeyUsageExtension.DIGITAL_SIGNATURE, true);
    usage.set(KeyUsageExtension.NON_REPUDIATION, true);
    KeyIdentifier kid = new KeyIdentifier(keyId);
    SerialNumber sn = new SerialNumber(42);
    AuthorityKeyIdentifierExtension aki = new AuthorityKeyIdentifierExtension(kid, subjectNames, sn);
    SubjectKeyIdentifierExtension ski = new SubjectKeyIdentifierExtension(keyId);
    BasicConstraintsExtension cons = new BasicConstraintsExtension(true, 10);
    PolicyConstraintsExtension pce = new PolicyConstraintsExtension(2, 4);
    exts.set(SubjectAlternativeNameExtension.NAME, subjectName);
    exts.set(IssuerAlternativeNameExtension.NAME, issuerName);
    exts.set(PrivateKeyUsageExtension.NAME, pkusage);
    exts.set(KeyUsageExtension.NAME, usage);
    exts.set(AuthorityKeyIdentifierExtension.NAME, aki);
    exts.set(SubjectKeyIdentifierExtension.NAME, ski);
    exts.set(BasicConstraintsExtension.NAME, cons);
    exts.set(PolicyConstraintsExtension.NAME, pce);
    cert.set(X509CertInfo.EXTENSIONS, exts);
    // Generate and sign X509CertImpl
    X509CertImpl crt = new X509CertImpl(cert);
    crt.sign(privateKey, sigAlg);
    crt.verify(publicKey);
    try (FileOutputStream fos = new FileOutputStream(new File(V3_FILE));
        FileOutputStream fos_b64 = new FileOutputStream(new File(V3_B64_FILE));
        PrintWriter pw = new PrintWriter(fos_b64)) {
        crt.encode((OutputStream) fos);
        fos.flush();
        // Certificate boundaries/
        pw.println("-----BEGIN CERTIFICATE-----");
        pw.flush();
        new BASE64Encoder().encodeBuffer(crt.getEncoded(), fos_b64);
        fos_b64.flush();
        pw.println("-----END CERTIFICATE-----");
    }
    out.println("*** Certificate ***");
    out.println(crt);
    out.println("*** End Certificate ***");
    X509Certificate x2 = generateCertificate(V3_FILE);
    if (!x2.equals(crt)) {
        out.println("*** Certificate mismatch ***");
        testResult = false;
    }
    X509Certificate x3 = generateCertificate(V3_B64_FILE);
    if (!x3.equals(crt)) {
        out.println("*** Certificate mismatch ***");
        testResult = false;
    }
    return testResult;
}
Also used : PrivateKey(java.security.PrivateKey) BitArray(sun.security.util.BitArray) MessageDigest(java.security.MessageDigest) ObjectIdentifier(sun.security.util.ObjectIdentifier) PrintWriter(java.io.PrintWriter) KeyPair(java.security.KeyPair) PublicKey(java.security.PublicKey) Calendar(java.util.Calendar) BASE64Encoder(sun.misc.BASE64Encoder) KeyPairGenerator(java.security.KeyPairGenerator) Date(java.util.Date) X509Certificate(java.security.cert.X509Certificate) Signature(java.security.Signature) FileOutputStream(java.io.FileOutputStream) File(java.io.File)

Example 23 with BASE64Encoder

use of sun.misc.BASE64Encoder in project jdk8u_jdk by JetBrains.

the class TestBase64Golden method test0.

public static void test0(Base64Type type, Encoder encoder, Decoder decoder, String srcFile, String encodedFile) throws Exception {
    String[] srcLns = Files.readAllLines(Paths.get(SRCDIR, srcFile), DEF_CHARSET).toArray(new String[0]);
    String[] encodedLns = Files.readAllLines(Paths.get(SRCDIR, encodedFile), DEF_CHARSET).toArray(new String[0]);
    int lns = 0;
    for (String srcStr : srcLns) {
        String encodedStr = null;
        if (type != Base64Type.MIME) {
            encodedStr = encodedLns[lns++];
        } else {
            while (lns < encodedLns.length) {
                String s = encodedLns[lns++];
                if (s.length() == 0)
                    break;
                if (encodedStr != null) {
                    encodedStr += DEFAULT_CRLF + s;
                } else {
                    encodedStr = s;
                }
            }
            if (encodedStr == null && srcStr.length() == 0) {
                encodedStr = "";
            }
        }
        System.out.printf("%n    src[%d]: %s%n", srcStr.length(), srcStr);
        System.out.printf("encoded[%d]: %s%n", encodedStr.length(), encodedStr);
        byte[] srcArr = srcStr.getBytes(DEF_CHARSET);
        byte[] encodedArr = encodedStr.getBytes(DEF_CHARSET);
        ByteBuffer srcBuf = ByteBuffer.wrap(srcArr);
        ByteBuffer encodedBuf = ByteBuffer.wrap(encodedArr);
        byte[] resArr = new byte[encodedArr.length];
        // test int encode(byte[], byte[])
        int len = encoder.encode(srcArr, resArr);
        assertEqual(len, encodedArr.length);
        assertEqual(resArr, encodedArr);
        // test byte[] encode(byte[])
        resArr = encoder.encode(srcArr);
        assertEqual(resArr, encodedArr);
        // test ByteBuffer encode(ByteBuffer)
        int limit = srcBuf.limit();
        ByteBuffer resBuf = encoder.encode(srcBuf);
        assertEqual(srcBuf.position(), limit);
        assertEqual(srcBuf.limit(), limit);
        assertEqual(resBuf, encodedBuf);
        // reset for next test
        srcBuf.rewind();
        // test String encodeToString(byte[])
        String resEncodeStr = encoder.encodeToString(srcArr);
        assertEqual(resEncodeStr, encodedStr);
        // test int decode(byte[], byte[])
        resArr = new byte[srcArr.length];
        len = decoder.decode(encodedArr, resArr);
        assertEqual(len, srcArr.length);
        assertEqual(resArr, srcArr);
        // test byte[] decode(byte[])
        resArr = decoder.decode(encodedArr);
        assertEqual(resArr, srcArr);
        // test ByteBuffer decode(ByteBuffer)
        limit = encodedBuf.limit();
        resBuf = decoder.decode(encodedBuf);
        assertEqual(encodedBuf.position(), limit);
        assertEqual(encodedBuf.limit(), limit);
        assertEqual(resBuf, srcBuf);
        // reset for next test
        encodedBuf.rewind();
        // test byte[] decode(String)
        resArr = decoder.decode(encodedStr);
        assertEqual(resArr, srcArr);
        // test compatible with sun.misc.Base64Encoder
        if (type == Base64Type.MIME) {
            sun.misc.BASE64Encoder miscEncoder = new BASE64Encoder();
            sun.misc.BASE64Decoder miscDecoder = new BASE64Decoder();
            resArr = decoder.decode(miscEncoder.encode(srcArr));
            assertEqual(resArr, srcArr);
            resArr = encoder.encode(miscDecoder.decodeBuffer(encodedStr));
            assertEqual(new String(resArr, DEF_CHARSET), encodedStr);
        }
    }
}
Also used : BASE64Encoder(sun.misc.BASE64Encoder) BASE64Decoder(sun.misc.BASE64Decoder) BASE64Encoder(sun.misc.BASE64Encoder) ByteBuffer(java.nio.ByteBuffer) BASE64Decoder(sun.misc.BASE64Decoder)

Example 24 with BASE64Encoder

use of sun.misc.BASE64Encoder in project jdk8u_jdk by JetBrains.

the class Obj method encodeReference.

/**
     * Convert a Reference object into several LDAP attributes.
     *
     * A Reference is stored as into the following attributes:
     * javaClassName
     *   value: Reference.getClassName();
     * javaFactory
     *   value: Reference.getFactoryClassName();
     * javaCodeBase
     *   value: Reference.getFactoryClassLocation();
     * javaReferenceAddress
     *   value: #0#typeA#valA
     *   value: #1#typeB#valB
     *   value: #2#typeC##[serialized RefAddr C]
     *   value: #3#typeD#valD
     *
     * where
     * -  the first character denotes the separator
     * -  the number following the first separator denotes the position
     *    of the RefAddr within the Reference
     * -  "typeA" is RefAddr.getType()
     * -  ## denotes that the Base64-encoded form of the non-StringRefAddr
     *    is to follow; otherwise the value that follows is
     *    StringRefAddr.getContents()
     *
     * The default separator is the hash character (#).
     * May provide property for this in future.
     */
private static Attributes encodeReference(char separator, Reference ref, Attributes attrs, Object orig) throws NamingException {
    if (ref == null)
        return attrs;
    String s;
    if ((s = ref.getClassName()) != null) {
        attrs.put(new BasicAttribute(JAVA_ATTRIBUTES[CLASSNAME], s));
    }
    if ((s = ref.getFactoryClassName()) != null) {
        attrs.put(new BasicAttribute(JAVA_ATTRIBUTES[FACTORY], s));
    }
    if ((s = ref.getFactoryClassLocation()) != null) {
        attrs.put(new BasicAttribute(JAVA_ATTRIBUTES[CODEBASE], s));
    }
    // specified other type names
    if (orig != null && attrs.get(JAVA_ATTRIBUTES[TYPENAME]) != null) {
        Attribute tAttr = LdapCtxFactory.createTypeNameAttr(orig.getClass());
        if (tAttr != null) {
            attrs.put(tAttr);
        }
    }
    int count = ref.size();
    if (count > 0) {
        Attribute refAttr = new BasicAttribute(JAVA_ATTRIBUTES[REF_ADDR]);
        RefAddr refAddr;
        BASE64Encoder encoder = null;
        for (int i = 0; i < count; i++) {
            refAddr = ref.get(i);
            if (refAddr instanceof StringRefAddr) {
                refAttr.add("" + separator + i + separator + refAddr.getType() + separator + refAddr.getContent());
            } else {
                if (encoder == null)
                    encoder = new BASE64Encoder();
                refAttr.add("" + separator + i + separator + refAddr.getType() + separator + separator + encoder.encodeBuffer(serializeObject(refAddr)));
            }
        }
        attrs.put(refAttr);
    }
    return attrs;
}
Also used : BASE64Encoder(sun.misc.BASE64Encoder)

Example 25 with BASE64Encoder

use of sun.misc.BASE64Encoder in project portal by ixinportal.

the class MakeInvoiceService method execute.

/**
 * 开票推送
 */
@PostMapping(value = "/execute")
@ResponseBody
public Map<String, Object> execute(@RequestHeader("Content-Signature") String authHmac, @RequestParam("appId") String appId, @RequestParam("billId") String billNo, HttpServletRequest request) {
    Map<String, Object> result = new HashMap<String, Object>();
    result.put("status", -2);
    // 验证参数是否完整
    if (StringUtils.isEmpty(authHmac) || StringUtils.isEmpty(appId) || StringUtils.isEmpty(billNo)) {
        result.put("message", "提交的参数信息不完整");
        return result;
    }
    // 得到应用信息 改成service
    Map<String, ApplicationInfo> appInfoMap = CacheCustomer.getAPP_INFO_MAP();
    ApplicationInfo applicationInfo = appInfoMap.get(appId);
    if (applicationInfo == null) {
        ApplicationInfoExample applicationInfoExample = new ApplicationInfoExample();
        ApplicationInfoExample.Criteria appInfoExampleCriteria = applicationInfoExample.createCriteria();
        appInfoExampleCriteria.andAppIdEqualTo(appId);
        applicationInfo = sqlSession.selectOne("com.itrus.portal.db.ApplicationInfoMapper.selectByExample", applicationInfoExample);
    }
    // 获取配置信息
    ReceiptConfig rc = sqlSession.selectOne("com.itrus.portal.db.ReceiptConfigMapper.selectByExample");
    log.debug("任务开始");
    DefaultTransactionDefinition def = new DefaultTransactionDefinition();
    def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
    TransactionStatus ts = null;
    // 验证hmac有效性
    try {
        String macVal = Base64.encode(HMACSHA1.getHmacSHA1(appId + billNo, applicationInfo.getSecretKey()), false);
        if (!authHmac.equals("HMAC-SHA1 " + macVal)) {
            result.put("status", -4);
            result.put("message", "服务密钥错误");
            return result;
        }
    } catch (Exception e) {
        result.put("status", -3);
        result.put("message", "Hmac验证错误");
        e.printStackTrace();
        return result;
    }
    try {
        String ssl_store = getClass().getClassLoader().getResource("").getPath() + File.separator + // 执行命令后,会生成该testclient.truststore
        "fapiao.truststore";
        // 证书的存取密码,即执行命令时填写的密码
        String ssl_pwd = "ixin21060921";
        System.setProperty("javax.net.ssl.trustStore", ssl_store);
        System.setProperty("javax.net.ssl.keyStorePassword", ssl_pwd);
        // String url =
        // "https://218.17.158.39:8999/fpt_dsqz/services/DZFPService?wsdl";
        HostnameVerifier hv = new HostnameVerifier() {

            public boolean verify(String urlHostName, SSLSession session) {
                System.out.println("Warning: URL Host: " + urlHostName + " vs. " + session.getPeerHost());
                return true;
            }
        };
        HttpsURLConnection.setDefaultHostnameVerifier(hv);
        org.apache.axis.client.Service s = new org.apache.axis.client.Service();
        Call call = (Call) s.createCall();
        call.setTargetEndpointAddress(new URL(rc.getAddress()));
        call.setOperation("doService");
        Map param = new HashMap();
        param.put("billNo", billNo);
        Map<String, Object> data = sqlSession.selectOne("com.itrus.portal.db.BillMapper.selectByBillEreceipt", param);
        // Bill bill =sqlSession.selectOne("", billId);
        String xml;
        String val;
        Bill bill;
        Einvoice einvoice = null;
        Ereceipt ereceipt;
        Map<String, String> temp = null;
        String content;
        if (null != data && data.size() != 0) {
            ereceipt = sqlSession.selectOne("com.itrus.portal.db.EreceiptMapper.selectByPrimaryKey", data.get("eid"));
            content = getContent(data, ereceipt);
            log.error("[input0]{}", content);
            xml = getCommonXml("DFXJ1001", new BASE64Encoder().encodeBuffer(content.getBytes("UTF-8")), rc.getAppId());
            log.error("[input1]{}", xml);
            Object[] fn01 = { xml };
            val = (String) call.invoke(fn01);
            log.error("[output]{}", val);
            temp = parseXml(val);
            if (!temp.get("returnCode").equals("0000")) {
                // LogUtil.syslog(sqlSession, "开票推送", data.get("bill_id") + "开票推送失败,错误:" + temp.get("returnMessage"));
                log.error("ERRORLOG电子发票 {}", data.get("bill_id") + "开票推送失败,错误:" + temp.get("returnMessage"));
                result.put("status", -1);
                result.put("message", "开票推送失败");
                return result;
            }
            temp = parseXml(new String(new BASE64Decoder().decodeBuffer(temp.get("content")), "UTF-8"));
            einvoice = sqlSession.selectOne("com.itrus.portal.db.EinvoiceMapper.selectByPrimaryKey", data.get("e_invoice"));
            einvoice.setInvoiceId(temp.get("FPQQLSH"));
            einvoice.setInvoiceCode(temp.get("FP_DM"));
            einvoice.setInvoiceNo(temp.get("FP_HM"));
            einvoice.setCheckCode(temp.get("JYM"));
            einvoice.setConfirmTime(sdf.parse(temp.get("KPRQ")));
            einvoice.setDlAddress(temp.get("PDF_URL"));
            einvoice.setStatus(1);
            einvoice.setInvoiceSum(Double.valueOf(String.valueOf(data.get("bill_sum"))));
            ts = transactionManager.getTransaction(def);
            sqlSession.update("com.itrus.portal.db.EinvoiceMapper.updateByPrimaryKeySelective", einvoice);
            bill = sqlSession.selectOne("com.itrus.portal.db.BillMapper.selectByPrimaryKey", data.get("id"));
            bill.setIsInvoiced(1);
            bill.setBillTime(new Date());
            if (null == bill.getDelivery() && bill.getBillStatus() == 6) {
                bill.setBillStatus(ComNames.BILL_STATUS_8);
            }
            sqlSession.update("com.itrus.portal.db.BillMapper.updateByPrimaryKeySelective", bill);
            transactionManager.commit(ts);
            // count++;
            result.put("status", 1);
            result.put("address", temp.get("PDF_URL"));
        }
        // 返回地址
        // LogUtil.syslog(sqlSession, "开票推送", "开票推送成功,推送" +
        // billexall3.size() + "条,成功" + count + "条。");
        log.debug("任务结束");
    } catch (Exception e) {
        // LogUtil.syslog(sqlSession, "开票推送", "开票推送失败,错误:" + e.toString());
        log.error("ERRORLOG电子发票 {}", "开票推送失败,错误:" + e.toString());
        e.printStackTrace();
    } finally {
        if (ts != null && !ts.isCompleted()) {
            transactionManager.rollback(ts);
        }
    }
    return result;
}
Also used : DefaultTransactionDefinition(org.springframework.transaction.support.DefaultTransactionDefinition) HashMap(java.util.HashMap) ApplicationInfo(com.itrus.portal.db.ApplicationInfo) TransactionStatus(org.springframework.transaction.TransactionStatus) URL(java.net.URL) Einvoice(com.itrus.portal.db.Einvoice) BASE64Decoder(sun.misc.BASE64Decoder) Ereceipt(com.itrus.portal.db.Ereceipt) ApplicationInfoExample(com.itrus.portal.db.ApplicationInfoExample) Call(org.apache.axis.client.Call) BASE64Encoder(sun.misc.BASE64Encoder) SSLSession(javax.net.ssl.SSLSession) Date(java.util.Date) HostnameVerifier(javax.net.ssl.HostnameVerifier) Bill(com.itrus.portal.db.Bill) Map(java.util.Map) HashMap(java.util.HashMap) ReceiptConfig(com.itrus.portal.db.ReceiptConfig) PostMapping(org.springframework.web.bind.annotation.PostMapping) ResponseBody(org.springframework.web.bind.annotation.ResponseBody)

Aggregations

BASE64Encoder (sun.misc.BASE64Encoder)45 IOException (java.io.IOException)17 ByteArrayOutputStream (java.io.ByteArrayOutputStream)12 MessageDigest (java.security.MessageDigest)8 FileInputStream (java.io.FileInputStream)7 BufferedInputStream (java.io.BufferedInputStream)6 BufferedOutputStream (java.io.BufferedOutputStream)6 FileNotFoundException (java.io.FileNotFoundException)6 UnsupportedEncodingException (java.io.UnsupportedEncodingException)4 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)4 Map (java.util.Map)4 HostnameVerifier (javax.net.ssl.HostnameVerifier)4 SSLSession (javax.net.ssl.SSLSession)4 Call (org.apache.axis.client.Call)4 BASE64Decoder (sun.misc.BASE64Decoder)4 File (java.io.File)3 URL (java.net.URL)3 Signature (java.security.Signature)3 X509Certificate (java.security.cert.X509Certificate)3 Date (java.util.Date)3