• 热门专题

Java RSA加解密

作者:timliao0308  发布日期:2013-10-30 10:32:39
Tag标签:Java  RSA  加解密  
  • RSA加解密通常双方皆需有PublicKey及PrivateKey

    将加密资料用PrivateKey加密后丢出,PublicKey解密以验签证(PublicKey事前即需抛给对方)


     

    import java.io.IOException;
    import java.security.InvalidKeyException;
    import java.security.NoSuchAlgorithmException;
    import java.security.PrivateKey;
    import java.security.PublicKey;
    
    import javax.crypto.BadPaddingException;
    import javax.crypto.Cipher;
    import javax.crypto.IllegalBlockSizeException;
    import javax.crypto.NoSuchPaddingException;
    
    public class RSAUtils {
    	private static PublicKey pubKey = null;
    	private static PrivateKey priKey = null;
    
    	public static void loadRSAPubKey(String filename) throws IOException {
    		pubKey = (PublicKey) RSAKey.readPublicKeyFile(filename);
    	}
    
    	public static void loadRSAPriKey(String filename) {
    		priKey = (PrivateKey) RSAKey.readPrivateKeyFile(filename);
    	}
    
    	public static PublicKey getPublicKey() {
    		return pubKey;
    	}
    
    	public static PrivateKey getPrivateKey() {
    		return priKey;
    	}
    	
    	public static String pubEncrypt(byte[] sessKey) {
    		try {
    			Cipher desCipher = Cipher.getInstance("RSA/ECB/OAEPWITHSHA-256ANDMGF1PADDING");
    			desCipher.init(Cipher.ENCRYPT_MODE, getPublicKey());
    			return RSAKey.bytesToBase64Str(desCipher.doFinal(sessKey));
    		} catch (NoSuchAlgorithmException e) {
    			// TODO Auto-generated catch block
    			e.printStackTrace();
    		} catch (NoSuchPaddingException 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 (InvalidKeyException e) {
    			// TODO Auto-generated catch block
    			e.printStackTrace();
    		}
    		return null;
    	}
    	
    	public static String priEncrypt(byte[] hash) {
    		try {
    			Cipher desCipher = Cipher.getInstance("RSA/ECB/PKCS1PADDING");
    			desCipher.init(Cipher.ENCRYPT_MODE, getPrivateKey());
    			return RSAKey.bytesToBase64Str(desCipher.doFinal(hash));
    		} 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();
    		}
    		return null;
    	}
    	
    	
    	
    	
    	public static byte[] priDecrypt(String encryptStr) {
    		try {
    			Cipher desCipher = Cipher.getInstance("RSA/ECB/OAEPWITHSHA-256ANDMGF1PADDING");
    			desCipher.init(Cipher.DECRYPT_MODE, getPrivateKey());
    			return desCipher.doFinal(RSAKey.base64StrToBytes(encryptStr));
    		} 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();
    		}
    		return null;
    	}
    
    	public static byte[] pubDecrypt(String encryptStr) {
    		try {
    			Cipher desCipher = Cipher.getInstance("RSA/ECB/PKCS1PADDING");
    			desCipher.init(Cipher.DECRYPT_MODE, getPublicKey());
    			return desCipher.doFinal(RSAKey.base64StrToBytes(encryptStr));
    		} catch (NoSuchAlgorithmException e) {
    			// TODO Auto-generated catch block
    			e.printStackTrace();
    		} catch (NoSuchPaddingException 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 (InvalidKeyException e) {
    			// TODO Auto-generated catch block
    			e.printStackTrace();
    		}
    		return null;
    	}
    
    	
    	public static void main(String[] arg) {
    		
    	}
    	
    }

    其中需有KEY之产生,在这以J2EE之架构

     

    import java.io.ByteArrayOutputStream;
     import java.io.File;
     import java.io.FileInputStream;
     import java.io.IOException;
     import java.io.InputStream;
     import java.security.KeyFactory;
     import java.security.PrivateKey;
     import java.security.PublicKey;
     import java.security.spec.PKCS8EncodedKeySpec;
     import java.security.spec.X509EncodedKeySpec;
    
    import sun.misc.BASE64Decoder;
     import sun.misc.BASE64Encoder;
    
    public class RSAKey {
      public static PublicKey readPublicKeyFile(String filename) throws IOException {
       try {
        String sysRootKey = "VPlatform.install.root";
        String root = System.getProperty(sysRootKey);
        File f = new File(root + "\\WEB-INF\\" + filename);
        byte[] b = read(f);
        PublicKey key = KeyFactory.getInstance("RSA").generatePublic(new X509EncodedKeySpec(b));
        
        return key;
       } catch (Exception e){
        e.printStackTrace();
       }
       return null;
      }
    
     public static PrivateKey readPrivateKeyFile(String filename) {
       try {
        String sysRootKey = "VPlatform.install.root";
        String root = System.getProperty(sysRootKey);
        File f = new File(root + "\\WEB-INF\\" + filename);
        byte[] b = read(f);
        PrivateKey key = KeyFactory.getInstance("RSA").generatePrivate(new PKCS8EncodedKeySpec(b));
        
        return key;
       } catch (Exception e){
        e.printStackTrace();
       }
       return null;
      }
    
     public static String bytesToBase64Str(byte[] bytes) {
       return new BASE64Encoder().encode(bytes);
      }
    
     public static byte[] base64StrToBytes(String base64Str) {
       try {
        return new BASE64Decoder().decodeBuffer(base64Str);
       } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
       }
       return null;
      }
      
      public static byte[] read(File file) throws IOException {
    
         ByteArrayOutputStream ous = null;
          InputStream ios = null;
          try {
              byte[] buffer = new byte[4096];
              ous = new ByteArrayOutputStream();
              ios = new FileInputStream(file);
              int read = 0;
              while ( (read = ios.read(buffer)) != -1 ) {
                  ous.write(buffer, 0, read);
              }
          } finally {
              try {
                   if ( ous != null )
                       ous.close();
              } catch ( IOException e) {
              }
    
             try {
                   if ( ios != null )
                        ios.close();
              } catch ( IOException e) {
              }
          }
          return ous.toByteArray();
      }
     }
    

     

About IT165 - 广告服务 - 隐私声明 - 版权申明 - 免责条款 - 网站地图 - 网友投稿 - 联系方式
本站内容来自于互联网,仅供用于网络技术学习,学习中请遵循相关法律法规