자바 암호 화 복호화 와 인증서 의 demo

8798 단어

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.security.InvalidKeyException;
import java.security.Key;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.Signature;
import java.security.UnrecoverableKeyException;
import java.security.cert.Certificate;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;

public class UtilDemo{
public static void main(String[] args) throws Exception {
    String keystorePath = "C:/Users/CeoiHong/x.keystore";
    String keystorePass = "123456";
    String certPath = "C:/Users/CeoiHong/x003.cer";
    String certPass = "abc002";
    String alias = "x002";


    KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("DSA");
    KeyPair keyPair = keyPairGenerator.genKeyPair();


    System.out.println("==========|  |==========");
    String source = "   www.xuhang.us";
    String source2 = "[email protected]";

    System.out.println("     :" + source);
    KeyStore keyStore = loadKeyStore(keystorePath, keystorePass);
    //    
    PrivateKey privateKey = getPrivateKey(keyStore, alias, certPass);
    //PrivateKey privateKey = keyPair.getPrivate();
    //      
    byte[] encrypted = asymmetricEncrypt("RSA/ECB/PKCS1Padding", source.getBytes("UTF-8"), privateKey);
    //      
    System.out.println("    (  ):" + privateKey.getAlgorithm());
    System.out.println("  :" + privateKey.getEncoded());
    System.out.println("      (    ):" + byte2Hex(encrypted));

    System.out.println("==========|  |==========");
    //    
    PublicKey publicKey = getPublicKey(keyStore.getCertificate(alias));
    //PublicKey publicKey = keyPair.getPublic();
    //      
    byte[] decrypted = asymmetricDecrypt("RSA/ECB/PKCS1Padding", encrypted, publicKey);
    //      
    System.out.println("    (  ):" + publicKey.getAlgorithm());
    System.out.println("  :" + publicKey.getEncoded());
    System.out.println("     (  ):" + byte2Hex(decrypted));
    System.out.println("      (  ):" + new String(decrypted, "UTF-8"));


    System.out.println("==========|  |==========");
    //       rsa  ,         rsa  
    //      Signature            ,DSA    md5  

    String alg = ((X509Certificate)getCertFromKStore(alias, keyStore)).getSigAlgName();
    Signature signature = Signature.getInstance("SHA1WithDSA");
    signature.initSign(keyPair.getPrivate());
    signature.update(source.getBytes("UTF-8"));
    signature.update(source2.getBytes("UTF-8"),0,source2.getBytes("UTF-8").length);
    byte[] sign = signature.sign();
    System.out.println("  plain:" + source);
    System.out.println("     :" + byte2Hex(sign));
    System.out.println("    /    :" + signature.getAlgorithm() + "/" + keyPair.getPrivate().getAlgorithm());

    System.out.println("==========|  |==========");
    Signature vSignature = Signature.getInstance("SHA1WithDSA");
    vSignature.initVerify(keyPair.getPublic());
    vSignature.update(source.getBytes("UTF-8"));
    vSignature.update(source2.getBytes("UTF-8"));
    boolean b = vSignature.verify(hex2Byte(byte2Hex(sign)));
    System.out.println("    /    :" + vSignature.getAlgorithm() + "/" + keyPair.getPublic().getAlgorithm());
    System.out.println("    :" + b);

    System.out.println("==========|    |==========");
    System.out.println("  plain:" + source);
    byte[] digestText = digest(source);
    System.out.println("    :" + byte2Hex(digestText));
    byte[] sign1 = asymmetricEncrypt("RSA", digestText, privateKey);
    System.out.println("    :" + byte2Hex(sign1));


    System.out.println("==========|    |==========");
    byte[] digest1 = asymmetricDecrypt("RSA", sign1, publicKey);
    System.out.println("         :" + byte2Hex(digest1));
    System.out.println("      " + byte2Hex(digest1).equals(byte2Hex(digestText)));




}

//     keystore
public static KeyStore loadKeyStore(String keystorePath, String keystorePass) throws KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException{
    //       
    KeyStore keyStore = KeyStore.getInstance("JKS");
    //  keystore      
    InputStream in = new FileInputStream(keystorePath);
    keyStore.load(in, keystorePass.toCharArray());

    return keyStore;

}

//         certificate
public static Certificate loadCertificate(String certPath, String certPass) throws CertificateException, FileNotFoundException{
    //     X509
    CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
    //          
    InputStream in = new FileInputStream(certPath);
    Certificate certificate = certificateFactory.generateCertificate(in);
    return certificate;
}

//        alias    certificate
public static Certificate getCertFromKStore(String alias, KeyStore keyStore) throws KeyStoreException{
    return keyStore.getCertificate(alias);
}

//    
public static byte[] symmetricEncrypt(String transformation, byte[] plainText, Key key) throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException{
    Cipher cipher = Cipher.getInstance(transformation);

    cipher.init(Cipher.ENCRYPT_MODE, key);

    cipher.update(plainText);

    return cipher.doFinal();
}

//    
public static byte[] symmetricDecrypt(String transformation, byte[] cipherText, Key key) throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException{
    Cipher cipher = Cipher.getInstance(transformation);

    cipher.init(Cipher.DECRYPT_MODE, key);

    cipher.update(cipherText);

    return cipher.doFinal();
}

//     
public static byte[] asymmetricEncrypt(String transformation, byte[] plainText, PrivateKey key) throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException{
    Cipher cipher = Cipher.getInstance(transformation);

    cipher.init(Cipher.ENCRYPT_MODE, key);

    cipher.update(plainText);

    return cipher.doFinal();
}

//     
public static byte[] asymmetricDecrypt(String transformation, byte[] cipherText, PublicKey key) throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException{
    Cipher cipher = Cipher.getInstance(transformation);

    cipher.init(Cipher.DECRYPT_MODE, key);

    cipher.update(cipherText);

    return cipher.doFinal();
}



//    PublicKey
public static PublicKey getPublicKey(Certificate certificate){
    return certificate.getPublicKey();
}

//    PrivateKey
public static PrivateKey getPrivateKey(KeyStore keyStore, String alias, String certpass) throws UnrecoverableKeyException, KeyStoreException, NoSuchAlgorithmException{
    return (PrivateKey)keyStore.getKey(alias, certpass.toCharArray());
}

//  
//TODO

//         
public static String byte2Hex(byte[] b){
    StringBuilder sb = new StringBuilder();
    for(int i=0;i<b.length;i++){
        String hex = Integer.toHexString(0x00ff & b[i]);
        if(hex.length()<2){
            sb.append('0');
        }
        sb.append(hex);
    }
    return sb.toString();
}

//         
public static byte[] hex2Byte(String hex){
    byte[] bytes = new byte[hex.length()/2];
    for(int i=0;i*2<hex.length();i++){
        bytes[i] = (byte) Integer.parseInt(hex.substring(2*i, 2*i+2), 16);
    }
    return bytes;
}

public static void printByte(byte[] bytes){
    for(int i=0;i<bytes.length;i++){
        if(i>0){
            System.out.print(",");
        }
        System.out.print(bytes[i]);
    }
    System.out.println();
}

//    
public static byte[] digest(String source) throws NoSuchAlgorithmException{
    MessageDigest md = MessageDigest.getInstance("SHA1");

    md.update(source.getBytes());

    return md.digest();
}
}

keytool 사용
키 라 이브 러 리 키 키 도구 목록 - keystore x. keystore - v (상세)

좋은 웹페이지 즐겨찾기