集册 Java实例教程 将字节数组签名为Base64

将字节数组签名为Base64

欢马劈雪     最近更新时间:2020-01-02 10:19:05

506
将字节数组签名为Base64


import java.io.ByteArrayInputStream;

import java.io.ByteArrayOutputStream;/** 来 自 nowjava.com - 时  代  Java**/

import java.io.File;

import java.io.FileInputStream;

import java.io.FileOutputStream;

import java.io.InputStream;

import java.io.OutputStream;

import java.nio.MappedByteBuffer;

import java.nio.channels.FileChannel;

import java.security.KeyStore;

import java.security.PrivateKey;

import java.security.PublicKey;

import java.security.Signature;

import java.security.cert.Certificate;

import java.security.cert.CertificateFactory;

import java.security.cert.X509Certificate;

import java.util.Date;

import javax.crypto.Cipher;


public class Main{/* 来 自 N o w J a v a . c o m - 时  代  Java*/

    public static void main(String[] argv) throws Exception{

        byte[] data = new byte[]{34,35,36,37,37,37,67,68,69};

        String keyStorePath = "nowjava.com";

        String alias = "nowjava.com";

        String password = "nowjava.com";

        System.out.println(signToBase64(data,keyStorePath,alias,password));

    }

    

    public static final String KEY_STORE = "JKS";

    public static final String X509 = "X.509";

    

    public static String signToBase64(byte[] data, String keyStorePath,

            String alias, String password) throws Exception {

        return Base64.encode2String(sign(data, keyStorePath, alias,

                password));

    }

    

    public static byte[] sign(byte[] data, String keyStorePath,

            String alias, String password) throws Exception {

        // ?

        X509Certificate x509Certificate = (X509Certificate) getCertificate(

                keyStorePath, alias, password);

        // ?

        KeyStore keyStore = getKeyStore(keyStorePath, password);

        // ?

        PrivateKey privateKey = (PrivateKey) keyStore.getKey(alias,

                password.toCharArray());

        // 

        Signature signature = Signature.getInstance(x509Certificate

                .getSigAlgName());

        signature.initSign(privateKey);

        signature.update(data);

        return signature.sign();

    }

    

    private static Certificate getCertificate(String certificatePath)

            throws Exception {

        CertificateFactory certificateFactory = CertificateFactory

                .getInstance(X509);

        FileInputStream in = new FileInputStream(certificatePath);

        Certificate certificate = certificateFactory

                .generateCertificate(in);

        in.close();

        return certificate;

    }

    

    private static Certificate getCertificate(String keyStorePath,

            String alias, 
展开阅读全文