Java加密算法 DSA 和 數字簽名

cp5m 9年前發布 | 3K 次閱讀 Java

import java.security.Key;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.SecureRandom;
import java.security.Signature;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.HashMap;
import java.util.Map;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

/**

  • DSA-Digital Signature Algorithm 是Schnorr和ElGamal簽名算法的變種,被美國NIST作為DSS(DigitalSignature Standard)。
  • 簡單的說,這是一種更高級的驗證方式,用作數字簽名。不單單只有公鑰、私鑰,還有數字簽名。私鑰加密生成數字簽名,公鑰驗證數據及簽名。
  • 如果數據和簽名不匹配則認為驗證失敗!即 傳輸中的數據 可以不再加密,接收方獲得數據后,拿到公鑰與簽名 驗證數據是否有效
  • @author stone
  • @date 2014-03-11 09:50:51 /
    public class DSA {
    //不僅可以使用DSA算法,同樣也可以使用RSA算法做數字簽名
    /
    public static final String KEY_ALGORITHM = "RSA"; public static final String SIGNATURE_ALGORITHM = "MD5withRSA";*/

    public static final String KEY_ALGORITHM = "DSA";
    public static final String SIGNATURE_ALGORITHM = "DSA";

    public static final String DEFAULT_SEED = "$%^*%^()(HJG8awfjas7"; //默認種子
    public static final String PUBLIC_KEY = "DSAPublicKey";
    public static final String PRIVATE_KEY = "DSAPrivateKey";

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

     String str = "!@#$!#^$#&ZXVDF呆軍工路愛著你*()_+";  
     byte[] data = str.getBytes();  
    
     Map<String, Object> keyMap = initKey();// 構建密鑰  
     PublicKey publicKey = (PublicKey) keyMap.get(PUBLIC_KEY);  
     PrivateKey privateKey = (PrivateKey) keyMap.get(PRIVATE_KEY);  
     System.out.println("私鑰format:" + privateKey.getFormat());  
     System.out.println("公鑰format:" + publicKey.getFormat());  
    // 產生簽名  
    String sign = sign(data, getPrivateKey(keyMap));  

    // 驗證簽名   
    boolean verify1 = verify("aaa".getBytes(), getPublicKey(keyMap), sign);  
    System.err.println("經驗證 數據和簽名匹配:" + verify1);     

    boolean verify = verify(data, getPublicKey(keyMap), sign);  
    System.err.println("經驗證 數據和簽名匹配:" + verify);     
}  

/**   
 * 生成密鑰   
 *    
 * @param seed 種子   
 * @return 密鑰對象   
 * @throws Exception   
 */  
public static Map<String, Object> initKey(String seed) throws Exception {  
    System.out.println("生成密鑰");  

    KeyPairGenerator keygen = KeyPairGenerator.getInstance(KEY_ALGORITHM);  
    SecureRandom secureRandom = new SecureRandom();     
    secureRandom.setSeed(seed.getBytes());   
    //Modulus size must range from 512 to 1024 and be a multiple of 64  
    keygen.initialize(640, secureRandom);    

    KeyPair keys = keygen.genKeyPair();  
    PrivateKey privateKey = keys.getPrivate();  
    PublicKey publicKey = keys.getPublic();  

    Map<String, Object> map = new HashMap<String, Object>(2);  
    map.put(PUBLIC_KEY, publicKey);     
    map.put(PRIVATE_KEY, privateKey);  
    return map;  
}  

/**   
 * 生成默認密鑰   
 *    
 * @return 密鑰對象   
 * @throws Exception   
 */    
public static Map<String, Object> initKey() throws Exception {     
    return initKey(DEFAULT_SEED);     
}  

/**   
 * 取得私鑰   
 *    
 * @param keyMap   
 * @return   
 * @throws Exception   
 */    
public static String getPrivateKey(Map<String, Object> keyMap) throws Exception {     
    Key key = (Key) keyMap.get(PRIVATE_KEY);     
    return encryptBASE64(key.getEncoded()); //base64加密私鑰  
}     

/**   
 * 取得公鑰   
 *    
 * @param keyMap   
 * @return   
 * @throws Exception   
 */    
public static String getPublicKey(Map<String, Object> keyMap) throws Exception {     
    Key key = (Key) keyMap.get(PUBLIC_KEY);     
    return encryptBASE64(key.getEncoded()); //base64加密公鑰  
}     

/** 
 *  用私鑰對信息進行數字簽名 
 * @param data  加密數據 
 * @param privateKey 私鑰-base64加密的 
 * @return  
 * @throws Exception 
 */  
public static String sign(byte[] data, String privateKey) throws Exception {  
    System.out.println("用私鑰對信息進行數字簽名");  

    byte[] keyBytes = decryptBASE64(privateKey);  
    PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyBytes);  
    KeyFactory factory = KeyFactory.getInstance(KEY_ALGORITHM);  
    PrivateKey priKey = factory.generatePrivate(keySpec);//生成 私鑰  

    //用私鑰對信息進行數字簽名  
    Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);  
    signature.initSign(priKey);  
    signature.update(data);  
    return encryptBASE64(signature.sign());  
}  

/** 
 * BASE64Encoder 加密 
 * @param data 要加密的數據 
 * @return 加密后的字符串 
 */  
private static String encryptBASE64(byte[] data) {  
    BASE64Encoder encoder = new BASE64Encoder();  
    String encode = encoder.encode(data);  
    return encode;  
}  

/** 
 * BASE64Decoder 解密 
 * @param data 要解密的字符串 
 * @return 解密后的byte[] 
 * @throws Exception  
 */  
private static byte[] decryptBASE64(String data) throws Exception {  
    BASE64Decoder decoder = new BASE64Decoder();  
    byte[] buffer = decoder.decodeBuffer(data);  
    return buffer;  
}  

/** 
 * 校驗數字簽名 
 * @param data 加密數據 
 * @param publicKey 
 * @param sign 數字簽名 
 * @return 
 * @throws Exception 
 */  
public static boolean verify(byte[] data, String publicKey, String sign) throws Exception {  
    byte[] keyBytes = decryptBASE64(publicKey);   
    X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);  
    KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);    
    PublicKey pubKey = keyFactory.generatePublic(keySpec);  

    Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);     
    signature.initVerify(pubKey);   
    signature.update(data);  

    return signature.verify(decryptBASE64(sign)); //驗證簽名  
}  

} </pre>

 本文由用戶 cp5m 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!