當前位置:首頁 » 編程語言 » javajar加密

javajar加密

發布時間: 2023-06-16 01:28:17

java加密解密要用到的JAR包

一般java加密解密都需要jar包的,不同的加解密方式對應
不同的加解密包,一般加解密方式有這么幾種。
資料鏈接:http://www.doc88.com/p-19252566394.html

Ⅱ java密碼加密與解密

以下兩個類可以很方便的完成字元串的加密和解密

加密 CryptHelper encrypt(password)

解密 CrypHelper decrypt(password)

代碼如下

CryptUtils java

[java]

package gdie lab crypt;

import java io IOException;

import javax crypto Cipher;

import javax crypto KeyGenerator;

import javax crypto SecretKey;

import apache xerces internal impl dv util Base ;

public class CryptUtils {

private static String Algorithm = DES ;

private static byte[] DEFAULT_KEY=new byte[] { };

private static String VALUE_ENCODING= UTF ;

/**

* 生成密鑰

*

* @return byte[] 返回生成的密鑰

* @throws exception

* 扔出異常

*/

public static byte[] getSecretKey() throws Exception {

KeyGenerator keygen = KeyGenerator getInstance(Algorithm)

SecretKey deskey = keygen generateKey()

// if (debug ) System out println ( 生成密鑰 +byte hex (deskey getEncoded

// ()))

return deskey getEncoded()

}

/**

* 將指定的數據根據提供的密鑰進行加密

*

* @param input

* 需要加密的數據

* @param key

* 密鑰

* @return byte[] 加密後的數據

* @throws Exception

*/

public static byte[] encryptData(byte[] input byte[] key) throws Exception {

SecretKey deskey = new javax crypto spec SecretKeySpec(key Algorithm)

// if (debug )

// {

// System out println ( 加密前的二進串 +byte hex (input ))

// System out println ( 加密前的字元串 +new String (input ))

//

// }

Cipher c = Cipher getInstance(Algorithm)

c init(Cipher ENCRYPT_MODE deskey)

byte[] cipherByte = c doFinal(input)

// if (debug ) System out println ( 加密後的二進串 +byte hex (cipherByte ))

return cipherByte;

}

public static byte[] encryptData(byte[] input) throws Exception {

return encryptData(input DEFAULT_KEY)

}

/**

* 將給定的已加密的數據通過指定的密鑰進行解密

*

* @param input

* 待解密的數據

* @param key

* 密鑰

* @return byte[] 解密後的數據

* @throws Exception

*/

public static byte[] decryptData(byte[] input byte[] key) throws Exception {

SecretKey deskey = new javax crypto spec SecretKeySpec(key Algorithm)

// if (debug ) System out println ( 解密前的信息 +byte hex (input ))

Cipher c = Cipher getInstance(Algorithm)

c init(Cipher DECRYPT_MODE deskey)

byte[] clearByte = c doFinal(input)

// if (debug )

// {

// System out println ( 解密後的二進串 +byte hex (clearByte ))

// System out println ( 解密後的字元串 +(new String (clearByte )))

//

// }

return clearByte;

}

public static byte[] decryptData(byte[] input) throws Exception {

return decryptData(input DEFAULT_KEY)

}

/**

* 位元組碼轉換成 進制字元串

*

* @param byte[] b 輸入要轉換的位元組碼

* @return String 返回轉換後的 進制字元串

*/

public static String byte hex(byte[] bytes) {

StringBuilder hs = new StringBuilder()

for(byte b : bytes)

hs append(String format( % $ X b))

return hs toString()

}

public static byte[] hex byte(String content) {

int l=content length()》 ;

byte[] result=new byte[l];

for(int i= ;i<l;i++) {

int j=i《 ;

String s=content substring(j j+ )

result[i]=Integer valueOf(s ) byteValue()

}

return result;

}

/**

* 將位元組數組轉換為base 編碼字元串

* @param buffer

* @return

*/

public static String bytesToBase (byte[] buffer) {

//BASE Encoder en=new BASE Encoder()

return Base encode(buffer)

// return encoder encode(buffer)

}

/**

* 將base 編碼的字元串解碼為位元組數組

* @param value

* @return

* @throws IOException

*/

public static byte[] base ToBytes(String value) throws IOException {

//return Base decodeToByteArray(value)

// System out println(decoder decodeBuffer(value))

// return decoder decodeBuffer(value)

return Base decode(value)

}

/**

* 加密給定的字元串

* @param value

* @return 加密後的base 字元串

*/

public static String encryptString(String value) {

return encryptString(value DEFAULT_KEY)

}

/**

* 根據給定的密鑰加密字元串

* @param value 待加密的字元串

* @param key 以BASE 形式存在的密鑰

* @return 加密後的base 字元串

* @throws IOException

*/

public static String encryptString(String value String key) throws IOException {

return encryptString(value base ToBytes(key))

}

/**

* 根據給定的密鑰加密字元串

* @param value 待加密的字元串

* @param key 位元組數組形式的密鑰

* @return 加密後的base 字元串

*/

public static String encryptString(String value byte[] key) {

try {

byte[] data=value getBytes(VALUE_ENCODING)

data=CryptUtils encryptData(data key)

return bytesToBase (data)

} catch (Exception e) {

// TODO Auto generated catch block

e printStackTrace()

return null;

}

}

/**

* 解密字元串

* @param value base 形式存在的密文

* @return 明文

*/

public static String decryptString(String value) {

return decryptString(value DEFAULT_KEY)

}

/**

* 解密字元串

* @param value base 形式存在的密文

* @param key base 形式存在的密鑰

* @return 明文

* @throws IOException

*/

public static String decryptString(String value String key) throws IOException {

String s=decryptString(value base ToBytes(key))

return s;

}

/**

* 解密字元串

* @param value base 形式存在的密文

* @param key 位元組數據形式存在的密鑰

* @return 明文

*/

public static String decryptString(String value byte[] key) {

try {

byte[] data=base ToBytes(value)

data=CryptUtils decryptData(data key)

return new String(data VALUE_ENCODING)

}catch(Exception e) {

e printStackTrace()

return null;

}

}

}

package gdie lab crypt;

import java io IOException;

import javax crypto Cipher;

import javax crypto KeyGenerator;

import javax crypto SecretKey;

import apache xerces internal impl dv util Base ;

public class CryptUtils {

private static String Algorithm = DES ;

private static byte[] DEFAULT_KEY=new byte[] { };

private static String VALUE_ENCODING= UTF ;

/**

* 生成密鑰

*

* @return byte[] 返回生成的密鑰

* @throws exception

* 扔出異常

*/

public static byte[] getSecretKey() throws Exception {

KeyGenerator keygen = KeyGenerator getInstance(Algorithm)

SecretKey deskey = keygen generateKey()

// if (debug ) System out println ( 生成密鑰 +byte hex (deskey getEncoded

// ()))

return deskey getEncoded()

}

/**

* 將指定的數據根據提供的密鑰進行加密

*

* @param input

* 需要加密的數據

* @param key

* 密鑰

* @return byte[] 加密後的數據

* @throws Exception

*/

public static byte[] encryptData(byte[] input byte[] key) throws Exception {

SecretKey deskey = new javax crypto spec SecretKeySpec(key Algorithm)

// if (debug )

// {

// System out println ( 加密前的二進串 +byte hex (input ))

// System out println ( 加密前的字元串 +new String (input ))

//

// }

Cipher c = Cipher getInstance(Algorithm)

c init(Cipher ENCRYPT_MODE deskey)

byte[] cipherByte = c doFinal(input)

// if (debug ) System out println ( 加密後的二進串 +byte hex (cipherByte ))

return cipherByte;

}

public static byte[] encryptData(byte[] input) throws Exception {

return encryptData(input DEFAULT_KEY)

}

/**

* 將給定的已加密的數據通過指定的密鑰進行解密

*

* @param input

* 待解密的數據

* @param key

* 密鑰

* @return byte[] 解密後的數據

* @throws Exception

*/

public static byte[] decryptData(byte[] input byte[] key) throws Exception {

SecretKey deskey = new javax crypto spec SecretKeySpec(key Algorithm)

// if (debug ) System out println ( 解密前的信息 +byte hex (input ))

Cipher c = Cipher getInstance(Algorithm)

c init(Cipher DECRYPT_MODE deskey)

byte[] clearByte = c doFinal(input)

// if (debug )

// {

// System out println ( 解密後的二進串 +byte hex (clearByte ))

// System out println ( 解密後的字元串 +(new String (clearByte )))

//

// }

return clearByte;

}

public static byte[] decryptData(byte[] input) throws Exception {

return decryptData(input DEFAULT_KEY)

}

/**

* 位元組碼轉換成 進制字元串

*

* @param byte[] b 輸入要轉換的位元組碼

* @return String 返回轉換後的 進制字元串

*/

public static String byte hex(byte[] bytes) {

StringBuilder hs = new StringBuilder()

for(byte b : bytes)

hs append(String format( % $ X b))

return hs toString()

}

public static byte[] hex byte(String content) {

int l=content length()》 ;

byte[] result=new byte[l];

for(int i= ;i<l;i++) {

int j=i《 ;

String s=content substring(j j+ )

result[i]=Integer valueOf(s ) byteValue()

}

return result;

}

/**

* 將位元組數組轉換為base 編碼字元串

* @param buffer

* @return

*/

public static String bytesToBase (byte[] buffer) {

//BASE Encoder en=new BASE Encoder()

return Base encode(buffer)

// return encoder encode(buffer)

}

/**

* 將base 編碼的字元串解碼為位元組數組

* @param value

* @return

* @throws IOException

*/

public static byte[] base ToBytes(String value) throws IOException {

//return Base decodeToByteArray(value)

// System out println(decoder decodeBuffer(value))

// return decoder decodeBuffer(value)

return Base decode(value)

}

/**

* 加密給定的字元串

* @param value

* @return 加密後的base 字元串

*/

public static String encryptString(String value) {

return encryptString(value DEFAULT_KEY)

}

/**

* 根據給定的密鑰加密字元串

* @param value 待加密的字元串

* @param key 以BASE 形式存在的密鑰

* @return 加密後的base 字元串

* @throws IOException

*/

public static String encryptString(String value String key) throws IOException {

return encryptString(value base ToBytes(key))

}

/**

* 根據給定的密鑰加密字元串

* @param value 待加密的字元串

* @param key 位元組數組形式的密鑰

* @return 加密後的base 字元串

*/

public static String encryptString(String value byte[] key) {

try {

byte[] data=value getBytes(VALUE_ENCODING)

data=CryptUtils encryptData(data key)

return bytesToBase (data)

} catch (Exception e) {

// TODO Auto generated catch block

e printStackTrace()

return null;

}

}

/**

* 解密字元串

* @param value base 形式存在的密文

* @return 明文

*/

public static String decryptString(String value) {

return decryptString(value DEFAULT_KEY)

}

/**

* 解密字元串

* @param value base 形式存在的密文

* @param key base 形式存在的密鑰

* @return 明文

* @throws IOException

*/

public static String decryptString(String value String key) throws IOException {

String s=decryptString(value base ToBytes(key))

return s;

}

/**

* 解密字元串

* @param value base 形式存在的密文

* @param key 位元組數據形式存在的密鑰

* @return 明文

*/

public static String decryptString(String value byte[] key) {

try {

byte[] data=base ToBytes(value)

data=CryptUtils decryptData(data key)

return new String(data VALUE_ENCODING)

}catch(Exception e) {

e printStackTrace()

return null;

}

}

}

CryptHelper java

[java]

package gdie lab crypt;

import javax crypto Cipher;

import javax crypto SecretKey;

import javax crypto SecretKeyFactory;

import javax crypto spec DESKeySpec;

import javax crypto spec IvParameterSpec;

import springframework util DigestUtils;

public class CryptHelper{

private static String CRYPT_KEY = zhongqian ;

//加密

private static Cipher ecip;

//解密

private static Cipher dcip;

static {

try {

String KEY = DigestUtils md DigestAsHex(CRYPT_KEY getBytes()) toUpperCase()

KEY = KEY substring( )

byte[] bytes = KEY getBytes()

DESKeySpec ks = new DESKeySpec(bytes)

SecretKeyFactory skf = SecretKeyFactory getInstance( DES )

SecretKey sk = skf generateSecret(ks)

IvParameterSpec iv = new IvParameterSpec(bytes)

ecip = Cipher getInstance( DES/CBC/PKCS Padding )

ecip init(Cipher ENCRYPT_MODE sk iv )

dcip = Cipher getInstance( DES/CBC/PKCS Padding )

dcip init(Cipher DECRYPT_MODE sk iv )

}catch(Exception ex) {

ex printStackTrace()

}

}

public static String encrypt(String content) throws Exception {

byte[] bytes = ecip doFinal(content getBytes( ascii ))

return CryptUtils byte hex(bytes)

}

public static String decrypt(String content) throws Exception {

byte[] bytes = CryptUtils hex byte(content)

bytes = dcip doFinal(bytes)

return new String(bytes ascii )

}

//test

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

String password = gly ;

String en = encrypt(password)

System out println(en)

System out println(decrypt(en))

}

}

package gdie lab crypt;

import javax crypto Cipher;

import javax crypto SecretKey;

import javax crypto SecretKeyFactory;

import javax crypto spec DESKeySpec;

import javax crypto spec IvParameterSpec;

import springframework util DigestUtils;

public class CryptHelper{

private static String CRYPT_KEY = zhongqian ;

//加密

private static Cipher ecip;

//解密

private static Cipher dcip;

static {

try {

String KEY = DigestUtils md DigestAsHex(CRYPT_KEY getBytes()) toUpperCase()

KEY = KEY substring( )

byte[] bytes = KEY getBytes()

DESKeySpec ks = new DESKeySpec(bytes)

SecretKeyFactory skf = SecretKeyFactory getInstance( DES )

SecretKey sk = skf generateSecret(ks)

IvParameterSpec iv = new IvParameterSpec(bytes)

ecip = Cipher getInstance( DES/CBC/PKCS Padding )

ecip init(Cipher ENCRYPT_MODE sk iv )

dcip = Cipher getInstance( DES/CBC/PKCS Padding )

dcip init(Cipher DECRYPT_MODE sk iv )

}catch(Exception ex) {

ex printStackTrace()

}

}

public static String encrypt(String content) throws Exception {

byte[] bytes = ecip doFinal(content getBytes( ascii ))

return CryptUtils byte hex(bytes)

}

public static String decrypt(String content) throws Exception {

byte[] bytes = CryptUtils hex byte(content)

bytes = dcip doFinal(bytes)

return new String(bytes ascii )

}

//test

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

String password = gly ;

String en = encrypt(password)

System out println(en)

System out println(decrypt(en))

}

lishixin/Article/program/Java/hx/201311/26449

Ⅲ 如何把 jar 文件加密

1,打開一個要加密的文本文檔。
2,確保一下裡面的內容都保存好了後,關閉退出。
3,返回存放這個文本文檔的地方,然後選中它,右鍵一下,在彈出來的列表中我們選擇「重命名」選項。
4,接著就可以對這個jar檔轉換一下格式,比如可以把它轉換成表格或者word文檔,即把後綴改成「.doc」等格式,然後轉換成文檔後,這時就知道文檔裡面是加密功能的。

Ⅳ 請問下如何把 jar 文件加密

可以使用Virbox Protector Standalone 加殼工具對java的jar、war包及class文件進行保護。可防止代碼反編譯,更安全,更方便

產品簡介

Virbox Protector Standalone提供了強大的代碼虛擬化、高級混淆與智能壓縮技術,保護您的程序免受逆向工程和非法修改。

Virbox Protector Standalone 將被保護的程序代碼轉換為虛擬機代碼,程序運行時,虛擬機將模擬程序執行,進入和離開虛擬機都有高級代碼混淆。虛擬機配合代碼混淆可以達到很好的保護效果,尤其是開發者的私有邏輯。高級混淆利用花指令和代碼非等價變形等技術,將程序的代碼,轉換成一種功能上等價,但是難於閱讀和理解的代碼,可充分干擾靜態分析。應用程序的解壓縮含有動態密碼,讓一切自動脫殼工具失效,有效的阻止.Net、PE 程序的直接反編譯。

特點

多種加密策略:代碼虛擬化、高級混淆、智能壓縮

性能分析:智能分析引擎,一鍵分析各個函數模塊調用的次數

支持多種開發語言:多種開發語言加殼支持

源碼級保護:保護到匯編級別,c#保護IL級別

免費更新:免費版本升級

Ⅳ java項目如何加密

Java基本的單向加密演算法

1.BASE64 嚴格地說,屬於編碼格式,而非加密演算法
2.MD5(Message Digest algorithm 5,信息摘要演算法)
3.SHA(Secure Hash Algorithm,安全散列演算法)
4.HMAC(Hash Message Authentication Code,散列消息鑒別碼)
按 照RFC2045的定義,Base64被定義為:Base64內容傳送編碼被設計用來把任意序列的8位位元組描述為一種不易被人直接識別的形式。(The Base64 Content-Transfer-Encoding is designed to represent arbitrary sequences of octets in a form that need not be humanly readable.)
常見於郵件、http加密,截取http信息,你就會發現登錄操作的用戶名、密碼欄位通過BASE64加密的。
主要就是BASE64Encoder、BASE64Decoder兩個類,我們只需要知道使用對應的方法即可。另,BASE加密後產生的位元組位數是8的倍數,如果不夠位數以=符號填充。
MD5
MD5 -- message-digest algorithm 5 (信息-摘要演算法)縮寫,廣泛用於加密和解密技術,常用於文件校驗。校驗?不管文件多大,經過MD5後都能生成唯一的MD5值。好比現在的ISO校驗,都 是MD5校驗。怎麼用?當然是把ISO經過MD5後產生MD5的值。一般下載linux-ISO的朋友都見過下載鏈接旁邊放著MD5的串。就是用來驗證文 件是否一致的。

HMAC
HMAC(Hash Message Authentication Code,散列消息鑒別碼,基於密鑰的Hash演算法的認證協議。消息鑒別碼實現鑒別的原理是,用公開函數和密鑰產生一個固定長度的值作為認證標識,用這個 標識鑒別消息的完整性。使用一個密鑰生成一個固定大小的小數據塊,即MAC,並將其加入到消息中,然後傳輸。接收方利用與發送方共享的密鑰進行鑒別認證 等。

Ⅵ java加密的幾種方式

朋友你好,很高興為你作答。

首先,Java加密能夠應對的風險包括以下幾個:

1、核心技術竊取

2、核心業務破解

3、通信模塊破解

4、API介面暴露

本人正在使用幾維安全Java加密方式,很不錯,向你推薦,希望能夠幫助到你。

幾維安全Java2C針對DEX文件進行加密保護,將DEX文件中標記的Java代碼翻譯為C代碼,編譯成加固後的SO文件。默認情況只加密activity中的onCreate函數,如果開發者想加密其它類和方法,只需對相關類或函數添加標記代碼,在APK加密時會自動對標記的代碼進行加密處理。

與傳統的APP加固方案相比,不涉及到自定義修改DEX文件的載入方式,所以其兼容性非常好;其次Java函數被完全轉化為C函數,直接在Native層執行,不存在Java層解密執行的步驟,其性能和執行效率更優。

如果操作上有不明白的地方,可以聯系技術支持人員幫你完成Java加密。

希望以上解答能夠幫助到你。

Ⅶ java非對稱加密的源代碼(RSA)

鑒於rsa加密的重要性和相關源代碼的匱乏 經過整理特此貼出 需要下載bcprov jdk jar import javax crypto Cipher;import java security *;import java security spec RSAPublicKeySpec;清納import java security spec RSAPrivateKeySpec;import java security spec InvalidKeySpecException;import java security interfaces RSAPrivateKey;import java security interfaces RSAPublicKey;import java io *;import java math BigInteger;/*** RSA 工具類 提供加密 解密 生成密鑰對等方法 * 需要到下載bcprov jdk jar **/public class RSAUtil {/*** 生成密鑰對* @return KeyPair* @throws EncryptException*/public static KeyPair generateKeyPair() throws EncryptException {try {槐碼KeyPairGenerator keyPairGen = KeyPairGenerator getInstance( RSA new bouncycastle jce provider BouncyCastleProvider());final int KEY_SIZE = ;//沒什麼好說的了 這個值關繫到塊加密的大小 可以更改 但是不要太大 否則效率會低keyPairGen initialize(KEY_SIZE new SecureRandom());KeyPair keyPair = keyPairGen genKeyPair();return keyPair;} catch (Exception e) {throw new EncryptException(e getMessage());}}/*** 生成公鑰* @param molus* @param publicExponent* @return RSAPublicKey* @throws EncryptException*/public static RSAPublicKey generateRSAPublicKey(byte[] molus byte[] publicExponent) throws EncryptException {KeyFactory keyFac = null;try {keyFac = KeyFactory getInstance( RSA new bouncycastle jce provider BouncyCastleProvider());} catch (NoSuchAlgorithmException ex) {throw new EncryptException(ex getMessage());}RSAPublicKeySpec pubKeySpec = new RSAPublicKeySpec(new BigInteger(molus) new BigInteger(publicExponent));try {return (RSAPublicKey) keyFac generatePublic(pubKeySpec);} catch (InvalidKeySpecException ex) {throw new EncryptException(ex getMessage());}}/*** 生成私鑰* @param molus鉛正哪* @param privateExponent* @return RSAPrivateKey* @throws EncryptException*/public static RSAPrivateKey generateRSAPrivateKey(byte[] molus byte[] privateExponent) throws EncryptException {KeyFactory keyFac = null;try {keyFac = KeyFactory getInstance( RSA new bouncycastle jce provider BouncyCastleProvider());} catch (NoSuchAlgorithmException ex) {throw new EncryptException(ex getMessage());}RSAPrivateKeySpec priKeySpec = new RSAPrivateKeySpec(new BigInteger(molus) new BigInteger(privateExponent));try {return (RSAPrivateKey) keyFac generatePrivate(priKeySpec);} catch (InvalidKeySpecException ex) {throw new EncryptException(ex getMessage());}}/*** 加密* @param key 加密的密鑰* @param data 待加密的明文數據* @return 加密後的數據* @throws EncryptException*/public static byte[] encrypt(Key key byte[] data) throws EncryptException {try {Cipher cipher = Cipher getInstance( RSA new bouncycastle jce provider BouncyCastleProvider());cipher init(Cipher ENCRYPT_MODE key);int blockSize = cipher getBlockSize();//獲得加密塊大小 如 加密前數據為 個byte 而key_size= 加密塊大小為 byte 加密後為 個byte;因此共有 個加密塊 第一個 byte第二個為 個byteint outputSize = cipher getOutputSize(data length);//獲得加密塊加密後塊大小int leavedSize = data length % blockSize;int blocksSize = leavedSize != ? data length / blockSize + : data length / blockSize;byte[] raw = new byte[outputSize * blocksSize];int i = ;while (data length i * blockSize > ) {if (data length i * blockSize > blockSize)cipher doFinal(data i * blockSize blockSize raw i * outputSize);elsecipher doFinal(data i * blockSize data length i * blockSize raw i * outputSize);//這裡面doUpdate方法不可用 查看源代碼後發現每次doUpdate後並沒有什麼實際動作除了把byte[]放到ByteArrayOutputStream中 而最後doFinal的時候才將所有的byte[]進行加密 可是到了此時加密塊大小很可能已經超出了OutputSize所以只好用dofinal方法 i++;}return raw;} catch (Exception e) {throw new EncryptException(e getMessage());}}/*** 解密* @param key 解密的密鑰* @param raw 已經加密的數據* @return 解密後的明文* @throws EncryptException*/public static byte[] decrypt(Key key byte[] raw) throws EncryptException {try {Cipher cipher = Cipher getInstance( RSA new bouncycastle jce provider BouncyCastleProvider());cipher init(cipher DECRYPT_MODE key);int blockSize = cipher getBlockSize();ByteArrayOutputStream bout = new ByteArrayOutputStream( );int j = ;while (raw length j * blockSize > ) {bout write(cipher doFinal(raw j * blockSize blockSize));j++;}return bout toByteArray();} catch (Exception e) {throw new EncryptException(e getMessage());}}/**** @param args* @throws Exception*/public static void main(String[] args) throws Exception {File file = new File( l );FileInputStream in = new FileInputStream(file);ByteArrayOutputStream bout = new ByteArrayOutputStream();byte[] tmpbuf = new byte[ ];int count = ;while ((count = in read(tmpbuf)) != ) {bout write(tmpbuf count);tmpbuf = new byte[ ];}in close();byte[] Data = bout toByteArray();KeyPair keyPair = RSAUtil generateKeyPair();RSAPublicKey pubKey = (RSAPublicKey) keyPair getPublic();RSAPrivateKey priKey = (RSAPrivateKey) keyPair getPrivate();byte[] pubModBytes = pubKey getMolus() toByteArray();byte[] pubPubExpBytes = pubKey getPublicExponent() toByteArray();byte[] priModBytes = priKey getMolus() toByteArray();byte[] priPriExpBytes = priKey getPrivateExponent() toByteArray();RSAPublicKey recoveryPubKey = RSAUtil generateRSAPublicKey(pubModBytes pubPubExpBytes);RSAPrivateKey recoveryPriKey = RSAUtil generateRSAPrivateKey(priModBytes priPriExpBytes);byte[] raw = RSAUtil encrypt(priKey Data);file = new File( encrypt_result dat );OutputStream out = new FileOutputStream(file);out write(raw);out close();byte[] data = RSAUtil decrypt(recoveryPubKey raw);file = new File( l );out = new FileOutputStream(file);out write(data);out flush();out close();}}加密可以用公鑰 解密用私鑰 或者加密用私鑰 通常非對稱加密是非常消耗資源的 因此可以對大數據用對稱加密如 des(具體代碼可以看我以前發的貼子) 而對其對稱密鑰進行非對稱加密 這樣既保證了數據的安全 還能保證效率 lishixin/Article/program/Java/gj/201311/27391

Ⅷ 漫談Java加密技術(二)

接下來我們介紹對稱加密演算法 最常用的莫過於DES數據加密演算法

DES

DES Data Encryption Standard 即數據加密演算法 是IBM公司於 年研究成功並公開發表的 DES演算法的入口參數有三個 Key Data Mode 其中Key為 個位元組共 位 是DES演算法的工作密鑰 Data也為 個位元組 位 是要被加密或被解密的數據 Mode為DES的工作方式 有兩種 加密或解密

DES演算法把 位的明文輸入塊變為 位的密文輸出塊 它所使用的密鑰也是 位

通過java代碼實現如下

importjava security Key;importjava security SecureRandom;importjavax crypto Cipher;importjavax crypto KeyGenerator;importjavax crypto SecretKey;importjavax crypto SecretKeyFactory;importjavax crypto spec DESKeySpec;/***//***DES安全編碼組件authorby;**<pre>*支持DES DESede(TripleDES 就是 DES) AES Blowfish RC RC (ARCFOUR)*DESkeysizemustbeequalto *DESede(TripleDES)keysizemustbeequalto or *AESkeysizemustbeequalto or but and bitsmaynotbeavailable* andcanonlyrangefrom to (inclusive)*RC keysizemustbebeeen and bits*RC (ARCFOUR)keysizemustbebeeen and bits*具體內容需要關注JDKDocument&///docs/technotes/guides/security/l*</pre>**@author梁棟*@version *@since */{/***//***ALGORITHM演算法<br>*可替換為以下任意一種演算法 同時key值的size相應改變 **<pre>*DESkeysizemustbeequalto *DESede(TripleDES)keysizemustbeequalto or *AESkeysizemustbeequalto or but and bitsmaynotbeavailable* andcanonlyrangefrom to (inclusive)*RC keysizemustbebeeen and bits*RC (ARCFOUR)keysizemustbebeeen and bits*</pre>**在KeytoKey(byte[]key)方法中使用下述代碼*<code>SecretKeysecretKey=newSecretKeySpec(key ALGORITHM);</code>替換*<code>*DESKeySpecdks=newDESKeySpec(key);*SecretKeyFactorykeyFactory=SecretKeyFactory getInstance(ALGORITHM);*SecretKeysecretKey=keyFactory generateSecret(dks);*</code>*/= DES ;/***//***轉換密鑰<br>**@paramkey*@return*@throwsException*/privatestaticKeytoKey(byte[]key)throwsException{DESKeySpecdks=newDESKeySpec(key);SecretKeyFactorykeyFactory=SecretKeyFactory getInstance(ALGORITHM);SecretKeysecretKey=keyFactory generateSecret(dks);//當使用其他對稱加密演算法時 如AES Blowfish等演算法時 用下述代碼替換上述三行代碼//SecretKeysecretKey=newSecretKeySpec(key ALGORITHM);returnsecretKey;}/***//***解密**@paramdata*@paramkey*@return*@throwsException*/publicstaticbyte[]decrypt(byte[]data Stringkey)throwsException{Keyk=toKey(decryptBASE (key));Ciphercipher=Cipher getInstance(ALGORITHM);cipher init(Cipher DECRYPT_MODE k);returncipher doFinal(data);}/***//***加密**@paramdata*@paramkey*@return*@throwsException*/publicstaticbyte[]encrypt(byte[]data Stringkey)throwsException{Keyk=toKey(decryptBASE (key));Ciphercipher=Cipher getInstance(ALGORITHM);cipher init(Cipher ENCRYPT_MODE k);returncipher doFinal(data);}/***//***生成密鑰**@return*@throwsException*/publicstaticStringinitKey()throwsException{returninitKey(null);}/***//***生成密鑰**@paramseed*@return*@throwsException*/publicstaticStringinitKey(Stringseed)throwsException{SecureRandomsecureRandom=null;if(seed!=null){secureRandom=newSecureRandom(decryptBASE (seed));}else{secureRandom=newSecureRandom();}KeyGeneratorkg=KeyGenerator getInstance(ALGORITHM);kg init(secureRandom);SecretKeysecretKey=kg generateKey();returnencryptBASE (secretKey getEncoded());}}

延續上一個類的實現 我們通過MD 以及SHA對字元串加密生成密鑰 這是比較常見的密鑰生成方式

再給出一個測試類

importstatic junit Assert *;import junit Test;/***//****@authorby;;*@version *@since */publicclassDESCoderTest{@Testpublicvoidtest()throwsException{StringinputStr= DES ;Stringkey=DESCoder initKey();System err println( 原文: +inputStr);System err println( 密鑰: +key);byte[]inputData=inputStr getBytes();inputData=DESCoder encrypt(inputData key);System err println( 加密後: +DESCoder encryptBASE (inputData));byte[]outputData=DESCoder decrypt(inputData key);StringoutputStr=newString(outputData);System err println( 解密後: +outputStr);assertEquals(inputStr outputStr);}}

得到的輸出內容如下

原文 DES

密鑰 f wEtRrV q =

加密後 C qe oNIzRY=

解密後 DES

由控制台得到的輸出 我們能夠比對加密 解密後結果一致 這是一種簡單的加密解密方式 只有一個密鑰

其實DES有很多同胞兄弟 如DESede(TripleDES) AES Blowfish RC RC (ARCFOUR) 這里就不過多闡述了 大同小異 只要換掉ALGORITHM換成對應的值 同時做一個代碼替換SecretKey secretKey = new SecretKeySpec(key ALGORITHM) 就可以了 此外就是密鑰長度不同了

/**

lishixin/Article/program/Java/gj/201311/27624

Ⅸ JAVA程序加密,怎麼做才安全

程序加密?你說的是代碼加密還是數據加密。我都說一下吧。

Java代碼加密:

這點因為Java是開源的,想達到完全加密,基本是不可能的,因為在反編譯的時候,雖然反編譯回來的時候可能不是您原來的代碼,但是意思是接近的,所以是不行的。

那麼怎麼增加反編譯的難度(閱讀難度),那麼可以採用多層繼承(實現)方式來解決,這樣即使反編譯出來的代碼,可讀性太差,復用性太差了。

Java數據加密:

我們一般用校驗性加密,常用的是MD5,優點是速度快,數據佔用空間小。缺點是不可逆,所以我們一般用來校驗數據有沒有被改動等。

需要可逆,可以選用base64,Unicode,缺點是沒有密鑰,安全性不高。

而我們需要可逆而且採用安全的方式是:對稱加密和非堆成加密,我們常用的有AES、DES等單密鑰和雙密鑰的方式。而且是各種語言通用的。

全部手動敲字,望採納,下面是我用Javascript方式做的一系列在線加密/解密工具:

http://www.sojson.com/encrypt.html

Ⅹ 我想把java文件先加密然後打包,請高手指教怎麼加密,有那種好的加密演算法嗎

RSA演算法非常簡單,概述如下:
找兩素數p和q
取n=p*q
取t=(p-1)*(q-1)
取任何一個數e,要求滿足e<t並且e與t互素(就是最大公因數為1)
取d*e%t==1

這樣最終得到三個數: n d e

設消息為數M (M <n)
設c=(M**d)%n就得到了加密後的消息c
設m=(c**e)%n則 m == M,從而完成對c的解密。
註:**表示次方,上面兩式中的d和e可以互換。

在對稱加密中:
n d兩個數構成公鑰,可以告訴別人;
n e兩個數構成私鑰,e自己保留,不讓任何人知道。
給別人發送的信息使用e加密,只要別人能用d解開就證明信息是由你發送的,構成了簽名機制。
別人給你發送信息時使用d加密,這樣只有擁有e的你能夠對其解密。

rsa的安全性在於對於一個大數n,沒有有效的方法能夠將其分解
從而在已知n d的情況下無法獲得e;同樣在已知n e的情況下無法
求得d。

<二>實踐

接下來我們來一個實踐,看看實際的操作:
找兩個素數:
p=47
q=59
這樣
n=p*q=2773
t=(p-1)*(q-1)=2668
取e=63,滿足e<t並且e和t互素
用perl簡單窮舉可以獲得滿主 e*d%t ==1的數d:
C:\Temp>perl -e "foreach $i (1..9999){ print($i),last if $i*63%2668==1 }"
847
即d=847

最終我們獲得關鍵的
n=2773
d=847
e=63

取消息M=244我們看看

加密:

c=M**d%n = 244**847%2773
用perl的大數計算來算一下:
C:\Temp>perl -Mbigint -e "print 244**847%2773"
465
即用d對M加密後獲得加密信息c=465

解密:

我們可以用e來對加密後的c進行解密,還原M:
m=c**e%n=465**63%2773 :
C:\Temp>perl -Mbigint -e "print 465**63%2773"
244
即用e對c解密後獲得m=244 , 該值和原始信息M相等。

<三>字元串加密

把上面的過程集成一下我們就能實現一個對字元串加密解密的示例了。
每次取字元串中的一個字元的ascii值作為M進行計算,其輸出為加密後16進制
的數的字元串形式,按3位元組表示,如01F

代碼如下:

#!/usr/bin/perl -w
#RSA 計算過程學習程序編寫的測試程序
#watercloud 2003-8-12
#
use strict;
use Math::BigInt;

my %RSA_CORE = (n=>2773,e=>63,d=>847); #p=47,q=59

my $N=new Math::BigInt($RSA_CORE{n});
my $E=new Math::BigInt($RSA_CORE{e});
my $D=new Math::BigInt($RSA_CORE{d});

print "N=$N D=$D E=$E\n";

sub RSA_ENCRYPT
{
my $r_mess = shift @_;
my ($c,$i,$M,$C,$cmess);

for($i=0;$i < length($$r_mess);$i++)
{
$c=ord(substr($$r_mess,$i,1));
$M=Math::BigInt->new($c);
$C=$M->(); $C->bmodpow($D,$N);
$c=sprintf "%03X",$C;
$cmess.=$c;
}
return \$cmess;
}

sub RSA_DECRYPT
{
my $r_mess = shift @_;
my ($c,$i,$M,$C,$dmess);

for($i=0;$i < length($$r_mess);$i+=3)
{
$c=substr($$r_mess,$i,3);
$c=hex($c);
$M=Math::BigInt->new($c);
$C=$M->(); $C->bmodpow($E,$N);
$c=chr($C);
$dmess.=$c;
}
return \$dmess;
}

my $mess="RSA 娃哈哈哈~~~";
$mess=$ARGV[0] if @ARGV >= 1;
print "原始串:",$mess,"\n";

my $r_cmess = RSA_ENCRYPT(\$mess);
print "加密串:",$$r_cmess,"\n";

my $r_dmess = RSA_DECRYPT($r_cmess);
print "解密串:",$$r_dmess,"\n";

#EOF

測試一下:
C:\Temp>perl rsa-test.pl
N=2773 D=847 E=63
原始串:RSA 娃哈哈哈~~~
加密串:
解密串:RSA 娃哈哈哈~~~

C:\Temp>perl rsa-test.pl 安全焦點(xfocus)
N=2773 D=847 E=63
原始串:安全焦點(xfocus)
加密串:
解密串:安全焦點(xfocus)

<四>提高

前面已經提到,rsa的安全來源於n足夠大,我們測試中使用的n是非常小的,根本不能保障安全性,
我們可以通過RSAKit、RSATool之類的工具獲得足夠大的N 及D E。
通過工具,我們獲得1024位的N及D E來測試一下:

n=EC3A85F5005D
4C2013433B383B
A50E114705D7E2
BC511951

d=0x10001

e=DD28C523C2995
47B77324E66AFF2
789BD782A592D2B
1965

設原始信息
M=

完成這么大數字的計算依賴於大數運算庫,用perl來運算非常簡單:

A) 用d對M進行加密如下:
c=M**d%n :
C:\Temp>perl -Mbigint -e " $x=Math::BigInt->bmodpow(0x11111111111122222222222233
333333333, 0x10001,
D55EDBC4F0
6E37108DD6
);print $x->as_hex"
b73d2576bd
47715caa6b
d59ea89b91
f1834580c3f6d90898

即用d對M加密後信息為:
c=b73d2576bd
47715caa6b
d59ea89b91
f1834580c3f6d90898

B) 用e對c進行解密如下:

m=c**e%n :
C:\Temp>perl -Mbigint -e " $x=Math::BigInt->bmodpow(0x17b287be418c69ecd7c39227ab
5aa1d99ef3
0cb4764414
, 0xE760A
3C29954C5D
7324E66AFF
2789BD782A
592D2B1965, CD15F90
4F017F9CCF
DD60438941
);print $x->as_hex"

(我的P4 1.6G的機器上計算了約5秒鍾)

得到用e解密後的m= == M

C) RSA通常的實現
RSA簡潔幽雅,但計算速度比較慢,通常加密中並不是直接使用RSA 來對所有的信息進行加密,
最常見的情況是隨機產生一個對稱加密的密鑰,然後使用對稱加密演算法對信息加密,之後用
RSA對剛才的加密密鑰進行加密。

最後需要說明的是,當前小於1024位的N已經被證明是不安全的
自己使用中不要使用小於1024位的RSA,最好使用2048位的。

----------------------------------------------------------

一個簡單的RSA演算法實現JAVA源代碼:

filename:RSA.java

/*
* Created on Mar 3, 2005
*
* TODO To change the template for this generated file go to
* Window - Preferences - Java - Code Style - Code Templates
*/

import java.math.BigInteger;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.FileWriter;
import java.io.FileReader;
import java.io.BufferedReader;
import java.util.StringTokenizer;

/**
* @author Steve
*
* TODO To change the template for this generated type comment go to
* Window - Preferences - Java - Code Style - Code Templates
*/
public class RSA {

/**
* BigInteger.ZERO
*/
private static final BigInteger ZERO = BigInteger.ZERO;

/**
* BigInteger.ONE
*/
private static final BigInteger ONE = BigInteger.ONE;

/**
* Pseudo BigInteger.TWO
*/
private static final BigInteger TWO = new BigInteger("2");

private BigInteger myKey;

private BigInteger myMod;

private int blockSize;

public RSA (BigInteger key, BigInteger n, int b) {
myKey = key;
myMod = n;
blockSize = b;
}

public void encodeFile (String filename) {
byte[] bytes = new byte[blockSize / 8 + 1];
byte[] temp;
int tempLen;
InputStream is = null;
FileWriter writer = null;
try {
is = new FileInputStream(filename);
writer = new FileWriter(filename + ".enc");
}
catch (FileNotFoundException e1){
System.out.println("File not found: " + filename);
}
catch (IOException e1){
System.out.println("File not found: " + filename + ".enc");
}

/**
* Write encoded message to 'filename'.enc
*/
try {
while ((tempLen = is.read(bytes, 1, blockSize / 8)) > 0) {
for (int i = tempLen + 1; i < bytes.length; ++i) {
bytes[i] = 0;
}
writer.write(encodeDecode(new BigInteger(bytes)) + " ");
}
}
catch (IOException e1) {
System.out.println("error writing to file");
}

/**
* Close input stream and file writer
*/
try {
is.close();
writer.close();
}
catch (IOException e1) {
System.out.println("Error closing file.");
}
}

public void decodeFile (String filename) {

FileReader reader = null;
OutputStream os = null;
try {
reader = new FileReader(filename);
os = new FileOutputStream(filename.replaceAll(".enc", ".dec"));
}
catch (FileNotFoundException e1) {
if (reader == null)
System.out.println("File not found: " + filename);
else
System.out.println("File not found: " + filename.replaceAll(".enc", "dec"));
}

BufferedReader br = new BufferedReader(reader);
int offset;
byte[] temp, toFile;
StringTokenizer st = null;
try {
while (br.ready()) {
st = new StringTokenizer(br.readLine());
while (st.hasMoreTokens()){
toFile = encodeDecode(new BigInteger(st.nextToken())).toByteArray();
System.out.println(toFile.length + " x " + (blockSize / 8));

if (toFile[0] == 0 && toFile.length != (blockSize / 8)) {
temp = new byte[blockSize / 8];
offset = temp.length - toFile.length;
for (int i = toFile.length - 1; (i <= 0) && ((i + offset) <= 0); --i) {
temp[i + offset] = toFile[i];
}
toFile = temp;
}

/*if (toFile.length != ((blockSize / 8) + 1)){
temp = new byte[(blockSize / 8) + 1];
System.out.println(toFile.length + " x " + temp.length);
for (int i = 1; i < temp.length; i++) {
temp[i] = toFile[i - 1];
}
toFile = temp;
}
else
System.out.println(toFile.length + " " + ((blockSize / 8) + 1));*/
os.write(toFile);
}
}
}
catch (IOException e1) {
System.out.println("Something went wrong");
}

/**
* close data streams
*/
try {
os.close();
reader.close();
}
catch (IOException e1) {
System.out.println("Error closing file.");
}
}

/**
* Performs <tt>base</tt>^<sup><tt>pow</tt></sup> within the molar
* domain of <tt>mod</tt>.
*
* @param base the base to be raised
* @param pow the power to which the base will be raisded
* @param mod the molar domain over which to perform this operation
* @return <tt>base</tt>^<sup><tt>pow</tt></sup> within the molar
* domain of <tt>mod</tt>.
*/
public BigInteger encodeDecode(BigInteger base) {
BigInteger a = ONE;
BigInteger s = base;
BigInteger n = myKey;

while (!n.equals(ZERO)) {
if(!n.mod(TWO).equals(ZERO))
a = a.multiply(s).mod(myMod);

s = s.pow(2).mod(myMod);
n = n.divide(TWO);
}

return a;
}

}

在這里提供兩個版本的RSA演算法JAVA實現的代碼下載:

1. 來自於 http://www.javafr.com/code.aspx?ID=27020 的RSA演算法實現源代碼包:
http://zeal.newmenbase.net/attachment/JavaFR_RSA_Source.rar

2. 來自於 http://www.ferrara.linux.it/Members/lucabariani/RSA/implementazioneRsa/ 的實現:
http://zeal.newmenbase.net/attachment/sorgentiJava.tar.gz - 源代碼包
http://zeal.newmenbase.net/attachment/algoritmoRSA.jar - 編譯好的jar包

另外關於RSA演算法的php實現請參見文章:
php下的RSA演算法實現

關於使用VB實現RSA演算法的源代碼下載(此程序採用了psc1演算法來實現快速的RSA加密):
http://zeal.newmenbase.net/attachment/vb_PSC1_RSA.rar

RSA加密的JavaScript實現: http://www.ohdave.com/rsa/
參考資料:http://www.lenovonet.com/proct/showarticle.asp?id=118

熱點內容
銳志哪個配置性價比最高 發布:2025-02-12 17:38:43 瀏覽:917
智能推送演算法 發布:2025-02-12 17:38:41 瀏覽:834
拍照上傳器 發布:2025-02-12 17:34:29 瀏覽:651
androidweb框架 發布:2025-02-12 17:32:45 瀏覽:75
安卓編程賀卡 發布:2025-02-12 17:32:44 瀏覽:837
php獲取資料庫的欄位 發布:2025-02-12 17:29:02 瀏覽:765
伺服器地址消失 發布:2025-02-12 17:23:36 瀏覽:950
後台執行php腳本 發布:2025-02-12 17:21:45 瀏覽:470
spring編程式事務 發布:2025-02-12 17:16:55 瀏覽:397
nginx禁止ip訪問 發布:2025-02-12 17:15:14 瀏覽:273