Current location - Quotes Website - Personality signature - An example of how RSA realizes asymmetric encryption in Java
An example of how RSA realizes asymmetric encryption in Java
The code is as follows. Base64 transformation needs to rely on a jar package commons-codec-1.9.jar. Please download it yourself.

Import? org . Apache . commons . codec . binary . base64;

Import? javax . crypto . badpaddingexception;

Import? javax . crypto . cipher;

Import? javax . crypto . illegalblocksizeexception;

Import? Java . io . bytearrayoutputstream;

Import? Java . io . unsupportedencodingexception;

Import? Java . security . *;

Import? Java . security . interfaces . rsaprivatekey;

Import? Java . security . interfaces . RSA public key;

Import? Java . security . spec . pkcs 8 encodedkeyspec;

Import? Java . security . spec . x 509 encodedkeyspec;

Public? Class? RSAUtils? {

//? Encryption mode

Public? Static electricity Final? String? Algorithm? =? ”RSA”;

//? Signature algorithm

Private? Static electricity Final? String? Signature _ algorithm? =? ”sha 1 with RSA”;

//? Create the initial length of the key pair

Private? Static electricity Final? int? KEY_SIZE? =? 5 12;

//? Character encoding format

Private? Static electricity Final? String? Character set? =? “UTF-8”;

//? RSA maximum encrypted plaintext size

Private? Static electricity Final? int? MAX_ENCRYPT_BLOCK? =? 1 17;

//? Maximum decryption ciphertext length of RSA

Private? Static electricity Final? int? MAX_DECRYPT_BLOCK? =? 128;

Private? KeyFactory? keyFactory

Public? RSAUtils()? Throwing? NoSuchAlgorithmException? {

keyFactory? =? KeyFactory.getInstance (algorithm);

}

/**

*? Private key encryption

*

*? @param? The content string to encrypt.

*? @param? privateKey? Private key

*? @ Return? Encrypted string (BASE64 encoding)

*/

Public? String? EncryptByPrivateKey (string? Content? String? privateKey)? Throwing? Exceptions? {

String? Results;

Try it? (ByteArrayOutputStream? Out? =? New? ByteArrayOutputStream())? {

byte[]? keyBytes? =? New? Base64()。 decode(private key);

PKCS8EncodedKeySpec? pkcs8KeySpec? =? New? pkcs 8 encodedkeyspec(key bytes);

PrivateKey? pKey? =? key factory . generate private(pkcs 8 key spec);

Password? Password? =? Cipher.getInstance (algorithm);

Cipher.init (password. Encryption mode? pKey);

byte[]? Data? =? content . getbytes(CHARSET);

Write2Stream (password,? Data? out);

byte[]? Result bytes? =? out . tobytearray();

The result? =? base64 . encode base 64 string(result bytes);

}? Catch? (exception? e)? {

Throw? New? Exception (e);

}

Return? Results;

}

/**

*? Public key decryption

*

*? @param? Content encrypted string (BASE64 encrypted)

*? @param? Public key? Public key

*? @ Return

*/

Public? String? DecryptByPublicKey (string? Content? String? publicKey)? Throwing? Exceptions? {

String? The result? =? "";

Try it? (ByteArrayOutputStream? Out? =? New? ByteArrayOutputStream())? {

byte[]? keyBytes? =? New? Base64()。 decode(public key);

X509EncodedKeySpec? x509KeySpec? =? New? x 509 encodedkeyspec(key bytes);

Public key? pKey? =? key factory . generate public(x509 key spec);

Password? Password? =? Cipher.getInstance (algorithm);

Cipher.init (password. Decryption mode? pKey);

byte[]? Data? =? Base64.decodeBase64 (content);

Write2Stream (password,? Data? out);

byte[]? Result bytes? =? out . tobytearray();

The result? =? New? String (result bytes);

}? Catch? (exception? e)? {

Throw? New? Exception (e);

}

Return? Results;

}

/**

*? Public key encryption

*

*? @param? The content string to encrypt.

*? @param? Public key? Public key

*? @ Return? Encrypted string (BASE64 encoding)

*/

Public? String? EncryptByPublicKey (string? Content? String? publicKey)? Throwing? Exceptions? {

String? The result? =? "";

Try it? (ByteArrayOutputStream? Out? =? New? ByteArrayOutputStream())? {

byte[]? keyBytes? =? New? Base64()。 decode(public key);

X509EncodedKeySpec? x509KeySpec? =? New? x 509 encodedkeyspec(key bytes);

Public key? pKey? =? key factory . generate public(x509 key spec);

Password? Password? =? Cipher.getInstance (algorithm);

Cipher.init (password. Encryption mode? pKey);

byte[]? Data? =? content . getbytes(CHARSET);

Write2Stream (password,

Data? out);

byte[]? Result bytes? =? out . tobytearray();

The result? =? base64 . encode base 64 string(result bytes);

}? Catch? (exception? e)? {

Throw? New? Exception (e);

}

Return? Results;

}

/**

*? Private key decryption

*

*? @param? Content encrypted string

*? @param? privateKey? Private key

*? @ Return? Decrypted string

*/

Public? String? DecryptByPrivateKey (string? Content? String? privateKey)? Throwing? Exceptions? {

String? The result? =? "";

Try it? (ByteArrayOutputStream? Out? =? New? ByteArrayOutputStream())? {

byte[]? keyBytes? =? New? Base64()。 decode(private key);

PKCS8EncodedKeySpec? pkcs8KeySpec? =? New? pkcs 8 encodedkeyspec(key bytes);

PrivateKey? pKey? =? key factory . generate private(pkcs 8 key spec);

Password? Password? =? Cipher.getInstance (algorithm);

Cipher.init (password. Decryption mode? pKey);

byte[]? Data? =? Base64.decodeBase64 (content);

Write2Stream (password,? Data? out);

byte[]? Result bytes? =? out . tobytearray();

The result? =? New? String (result bytes);

}? Catch? (exception? e)? {

Throw? New? Exception (e);

}

Return? Results;

}

Private? Static electricity Invalid? Write2Stream (password? Password? byte[]? Data? ByteArrayOutputStream? Out)? throw

BadPaddingException,? IllegalBlockSizeException? {

int? D 'Artalen? =? Data length;

int? Offset? =? 0;

byte[]? Caching;

int? Me? =? 0;

//? Decrypt data segment

What time? (dataLen? -? Offset? & gt? 0)? {

What if? (dataLen? -? Offset? & gt? MAX_DECRYPT_BLOCK)? {

Caching? =? cipher.doFinal(data,? Offset? Maximum decryption block);

}? Or what? {

Caching? =? cipher.doFinal(data,? Offset? D 'Artalen? -? Offset);

}

Out.write (cache,? 0,? cache . length);

i++;

Offset? =? Me? *? Maximum decryption block;

}

}

/**

*? Generate a digital signature on information with a private key.

*

*? @param? Data encryption data

*? @param? privateKey? Private key (BASE64 encoding)

*? @ Return? symbol

*/

Public? String? Symbol (string? Data? String? privateKey)? Throwing? Exceptions? {

String? The result? =? "";

Try it? {

byte[]? keyBytes? =? New? Base64()。 decode(private key);

PKCS8EncodedKeySpec? pkcs8KeySpec? =? New? pkcs 8 encodedkeyspec(key bytes);

PrivateKey? privateK? =? key factory . generate private(pkcs 8 key spec);

Signature? Signature? =? SIGNATURE . getinstance(SIGNATURE _ ALGORITHM);

signature . init sign(privateK);

signature . update(parse 2 hex str(data))。 getBytes(CHARSET));

The result? =? New? Base64()。 encodeToString(signature . sign());

}? Catch? (exception? e)? {

Throw? New? Exception (e);

}

Return? Results;

}

/**

*? Check digital signature

*

*? @param? Data? enciphered data

*? @param? Public key? Public key (BASE64 encoding)

*? @param? Sign? digital signature

*? @ Return

*? @throws? exception

*/

Public? Bull? Verification (string? Data? String? Public key? String? Sign)? Throwing? Exceptions? {

Bull? Results;

Try it? {

byte[]? keyBytes? =? New? Base64()。 decode(public key);

X509EncodedKeySpec? keySpec? =? New? x 509 encodedkeyspec(key bytes);

Public key? publicK? =? key factory . generate public(key spec);

Signature? Signature? =? SIGNATURE . getinstance(SIGNATURE _ ALGORITHM);

signature . init verify(publicK);

signature . update(parse 2 hex str(data))。 getBytes(CHARSET));

The result? =? Signature.verify (new? Base64()。 Decode (symbol));

}? Catch? (exception? e)? {

Throw? New? Exception (e);

}

Return? Results;

}

/**

*? Convert binary to 16.

*

*? @param? data

*? @ Return

*/

Public? Static electricity String? Parse2HexStr (string? Data)? Throwing? Exceptions? {

String? The result? =? "";

Try it? {

byte[]? buf? =? data . getbytes(CHARSET);

StringBuffer? sb? =? New? string buffer();

For what? (int? Me? =? 0; ? Me? & lt? Buf. length; ? i++)? {

String? Black magic? =? Integer.toHexString(buf[i]? & amp? 0x ff);

What if? (hex.length()? ==? 1)? {

Black magic? =? '0'? +? Hexadecimal;

}

sb . append(hex . toupper case());

}

The result? =? sb . tostring();

}? Catch? (UnsupportedEncodingException? e)? {

Throw? New? Exception (e);

}

Return? Results;

}

/**

*? Generate public and private keys

*/

Public? Static electricity Invalid? createKey()? Throwing? Exceptions? {

Try it? {

KeyPairGenerator? keyPairGenerator? =? KeyPairGenerator.getInstance (algorithm);

keypairgenerator . initialize(KEY _ SIZE);

KeyPair? keyPair? =? keypairgenerator . generatekeypair();

RSAPublicKey? rsaPublicKey? =? (RSAPublicKey)? key pair . get public();

RSAPrivateKey? rsaPrivateKey? =? (RSAPrivateKey)? key pair . get private();

String? Public key? =? base64 . encode base 64 string(RSA public key . get encoded());

String? privateKey? =? base64 . encode base 64 string(rsaprivatekey . get encoded());

System.out.println("publicKey= "? +? Public key? +? " \nprivateKey= "? +? private key);

}? Catch? (NoSuchAlgorithmException? e)? {

Throw? New? Exception (e);

}

}

Public? Static electricity Invalid? main(String[]? args)? Throwing? Exceptions? {

String? PRIVATE_KEY? =? " miiceaibadangbgkqhkig 9 w 0 baqefaascamiwggjeageaogbakeygxh 6 vz+m+kul 1 1 rdrandhb 4 yqezgqpjgprswbelgveohu 2/fns 1 bmgfjhi 8 lhr/o/hy 8 efb/I/ddylcccu 4 bcltxpki 8 EDC+kjr 2 wvyyfnnvmwee/3q 2 jsvkrf 8 1

String? Public key? =? " MIG fma 0 gcsqgsib 3d qebaquaa 4 gnadcbiqkbgqcnmblx+LC/pviri 9 du Q0 wjxrweghmyqsrj 0 usaxpyl xkb 7 TV 3 zbn w5 hyyspjya/ 6px 8 vbbqfypw8 i3 anfogwi 7 cazivhnqviudlr 8 MH 5 1 zlhhv 96 to 0 lskx/nfovkvqndzdh 60 zlgomde 0 NBR TN/5 zejgwjbvdlvcfoi

RSAUtils? rsaUtil? =? New? RSAUtils();

String? encryptByPublicKey? =? RSA util . encryptbypublickey(" Hello!" ,? PUBLIC _ KEY);

system . out . println(encryptByPublicKey);

String? decryptByPrivateKey? =? RSA util . decryptbyprivatekey(encryptByPublicKey,? PRIVATE _ KEY);

system . out . println(decryptByPrivateKey);

String? encryptByPrivateKey? =? RSA util . encryptbyprivatekey(" Hello!" ,? PRIVATE _ KEY);

system . out . println(encryptByPrivateKey);

String? decryptByPublicKey? =? RSA util . decryptbypublickey(encryptByPrivateKey,? PUBLIC _ KEY);

system . out . println(decryptByPublicKey);

String? Sign? =? rsaUtil.sign(" 1234 ",PRIVATE _ KEY);

System.out.println("sign:"? +? Signature);

System. out.println (rsautil.verify ("1234"), public key? Signature));

}

}