Java method for creating certificates and signatures using OpenSSL

Source: Internet
Author: User
Tags pkcs12 password protection

Win32OpenSSL_Light-0_9_8k.exe

 

1. Generate a private key without password protection:
OpenSSL genrsa-out private-rsa.key 1024

2. Generate a certificate
OpenSSL req-New-X509-key private-rsa.key-days 750-out public-rsa.cer

3. Generate a keystore
3.1. Generate the PKCS12 format keystore
OpenSSL PKCS12-export-name test-alias-In public-rsa.cer-inkey private-rsa.key-out 99bill-rsa.pfx

 

 

Pfx certificate to PEM command
OpenSSL PKCS12-In 99bill-rsa.pfx-passin pass: generate the password set for the certificate-nodes-out 99bill-rsa.pem

 

Private-rsa.pfx

Public-rsa.cer

 

Appendix: Signature Method

Package com. Verify. Cert;

Public class certutil {

/**
* Sign a string
*
* @ Param tobesigned
* String to be signed
* @ Param Keyfile
* Pfx Certificate file path
* @ Param Password
* Private key password protection
* @ Return returns true if the signature is successful (the result is obtained from the lastresult attribute) and false if the signature fails (the cause of failure is obtained from the lasterrmsg attribute)
*/
Public static string signmsg (final string tobesigned, final string Keyfile, final string password) throws exception {
Cryptnorestrict = new cryptnorestrict ();
Cryptnorestrict. signmsg (tobesigned, Keyfile, password );
Return cryptnorestrict. lastsignmsg;
}

/**
* Verify the signature
*
* @ Param tobeverified
* Ciphertext of the signature to be verified
* @ Param plaintext
* Plaintext of the signature to be verified
* @ Param certfile
* Public Key Certificate of the signatory
* @ Return: True is returned for successful verification, and false is returned for failure (obtain the cause of failure from the lasterrmsg attribute)
*/
Public static Boolean verifymsg (string tobeverified, string plaintext, string certfile) throws exception {
Cryptnorestrict = new cryptnorestrict ();
Return cryptnorestrict. verifymsg (tobeverified, plaintext, certfile );
}

Public static void main (string [] ARGs ){
Try {
String A = "100 | 123123122222222222222 ";
String B = signmsg (a, "com/verify/CERT/private-rsa.pfx", "123456 ");
System. Err. println (B );
System. Err. println (verifymsg (B, A, "com/verify/CERT/public-rsa.cer "));

} Catch (exception e ){
// Todo auto-generated Catch Block
E. printstacktrace ();
}
}

}

 

Package com. Verify. Cert;

Public interface cryptinf {
Public Boolean verifymsg (string tobeverified, string plaintext, string certfile) throws exception;

Public Boolean signmsg (string tobesigned, string Keyfile, string password) throws exception;

Public String getlastsignmsg ();
}

 

/**
*
*/
Package com. Verify. Cert;

Import java. Io. inputstream;
Import java. Security. keystore;
Import java. Security. provider;
Import java. Security. signature;
Import java. Security. cert. certificatefactory;
Import java. Security. cert. x509certificate;
Import java. Security. Interfaces. rsw.vatecrtkey;
Import java. Security. Interfaces. rsapublickey;
Import java. util. enumeration;

Import org. bouncycastle. JCE. provider. bouncycastleprovider;

/**
* @ Author Administrator
*
*/
Public class cryptnorestrict implements cryptinf {
Public static provider = new bouncycastleprovider ();

/**
* Constructor
*/
Public cryptnorestrict (){
}

Public cryptnorestrict (string encoding ){
This. Encoding = encoding;
}

Private string encoding = "GBK ";

/**
* Obtain the output result after the encryption, decryption, and signature functions are successfully called.
*/
Protected string lastresult;

/**
* Returns the last signature result.
*/
Protected string lastsignmsg;

/**
* Sign a string
*
* @ Param tobesigned
* String to be signed
* @ Param Keyfile
* Pfx Certificate file path
* @ Param Password
* Private key password protection
* @ Return returns true if the signature is successful (the result is obtained from the lastresult attribute) and false if the signature fails (the cause of failure is obtained from the lasterrmsg attribute)
*/
Public Boolean signmsg (final string tobesigned, final string Keyfile, final string password) throws exception {

Classloader Cl = cryptnorestrict. Class. getclassloader ();
Inputstream fikeyfile = Cl. getresourceasstream (Keyfile );
// Input the absolute path
// Fileinputstream fikeyfile = NULL;
// Fikeyfile = new fileinputstream (Keyfile );

Boolean result = false;
This. lastsignmsg = "";
Keystore Ks = keystore. getinstance ("PKCS12 ");

Try {
KS. Load (fikeyfile, password. tochararray ());
} Catch (exception ex ){
If (fikeyfile! = NULL)
Fikeyfile. Close ();
Throw ex;
}
Enumeration myenum = ks. aliases ();
String keyalias = NULL;
Rsw.vatecrtkey prikey = NULL;
// Keyalias = (string) myenum. nextelement ();
/* The ibm jdk must use the while loop to obtain the last alias to obtain the private key alias */
While (myenum. hasmoreelements ()){
Keyalias = (string) myenum. nextelement ();
// System. Out. println ("keyalias =" + keyalias );
If (KS. iskeyentry (keyalias )){
Prikey = (rsaprivatecrtkey) ks. getkey (keyalias, password. tochararray ());
Break;
}
}
If (prikey = NULL ){
Result = false;
Throw new exception ("no matching Private Key found ");
} Else {
Signature sign = signature. getinstance ("sha1withrsa ");
Sign. initsign (prikey );
Sign. Update (tobesigned. getbytes (encoding ));
Byte Signed [] = sign. Sign ();
Byte sign_asc [] = new byte [signed. length * 2];
Hex2ascii (signed. length, signed, sign_asc );
This. lastresult = new string (sign_asc );
This. lastsignmsg = This. lastresult;
Result = true;
}
Return result;
}

/**
* Verify the signature
*
* @ Param tobeverified
* Ciphertext of the signature to be verified
* @ Param plaintext
* Plaintext of the signature to be verified
* @ Param certfile
* Public Key Certificate of the signatory
* @ Return: True is returned for successful verification, and false is returned for failure (obtain the cause of failure from the lasterrmsg attribute)
*/
Public Boolean verifymsg (string tobeverified, string plaintext, string certfile) throws exception {
Boolean result = false;
Classloader Cl = cryptnorestrict. Class. getclassloader ();
Inputstream certfile = Cl. getresourceasstream (certfile );
// Input the absolute path
// Fileinputstream certfile = NULL;
// Certfile = new fileinputstream (certfile );
Certificatefactory cf = certificatefactory. getinstance ("X.509 ");

X509certificate x509cert = NULL;
Try {
X509cert = (x509certificate) Cf. generatecertificate (certfile );
} Catch (exception ex ){
If (certfile! = NULL)
Certfile. Close ();
Throw ex;
}

Rsapublickey pubkey = (rsapublickey) x509cert. getpublickey ();
Signature verify = signature. getinstance ("sha1withrsa ");
Verify. initverify (pubkey );
Byte signeddata [] = new byte [tobeverified. Length ()/2];
Ascii2hex (tobeverified. Length (), tobeverified. getbytes (encoding), signeddata );
Verify. Update (plaintext. getbytes (encoding ));
If (verify. Verify (signeddata )){
Result = true;
} Else {
Result = false;
// Throw new exception ("Verification Failed ");
}
Return result;
}

/**
* Return the output result after the encryption, decryption, and signature functions are successfully called.
*
* @ Return the output result after the encryption, decryption, and signature function is successfully called.
*/
Public String getlastresult (){
Return this. lastresult;
}

/**
* Returns the last signature result.
*
* @ Return signature result
*/
Public String getlastsignmsg (){
Return this. lastsignmsg;
}

/**
* Convert hexadecimal data into ASCII strings
*
* @ Param Len
* Hexadecimal Data Length
* @ Param data_in
* Hexadecimal data to be converted
* @ Param data_out
* Converted ASCII string
*/
Private Static void hex2ascii (INT Len, byte data_in [], byte data_out []) {
Byte temp1 [] = new byte [1];
Byte temp2 [] = new byte [1];
For (INT I = 0, j = 0; I <Len; I ++ ){
Temp1 [0] = data_in [I];
Temp1 [0] = (byte) (temp1 [0] >>> 4 );
Temp1 [0] = (byte) (temp1 [0] & 0x0f );
Temp2 [0] = data_in [I];
Temp2 [0] = (byte) (temp2 [0] & 0x0f );
If (temp1 [0]> = 0x00 & temp1 [0] <= 0x09 ){
(Data_out [J]) = (byte) (temp1 [0] + '0 ');
} Else if (temp1 [0]> = 0x0a & temp1 [0] <= 0x0f ){
(Data_out [J]) = (byte) (temp1 [0] + 0x57 );
}

If (temp2 [0]> = 0x00 & temp2 [0] <= 0x09 ){
(Data_out [J + 1]) = (byte) (temp2 [0] + '0 ');
} Else if (temp2 [0]> = 0x0a & temp2 [0] <= 0x0f ){
(Data_out [J + 1]) = (byte) (temp2 [0] + 0x57 );
}
J + = 2;
}
}

/**
* Convert an ASCII string to hexadecimal data
*
* @ Param Len
* ASCII string length
* @ Param data_in
* ASCII string to be converted
* @ Param data_out
* Converted hexadecimal data
*/
Private Static void ascii2hex (INT Len, byte data_in [], byte data_out []) {
Byte temp1 [] = new byte [1];
Byte temp2 [] = new byte [1];
For (INT I = 0, j = 0; I <Len; j ++ ){
Temp1 [0] = data_in [I];
Temp2 [0] = data_in [I + 1];
If (temp1 [0]> = '0' & temp1 [0] <= '9 '){
Temp1 [0]-= '0 ';
Temp1 [0] = (byte) (temp1 [0] <4 );

Temp1 [0] = (byte) (temp1 [0] & 0xf0 );

} Else if (temp1 [0]> = 'A' & temp1 [0] <= 'F '){
Temp1 [0]-= 0x57;
Temp1 [0] = (byte) (temp1 [0] <4 );
Temp1 [0] = (byte) (temp1 [0] & 0xf0 );
}

If (temp2 [0]> = '0' & temp2 [0] <= '9 '){
Temp2 [0]-= '0 ';

Temp2 [0] = (byte) (temp2 [0] & 0x0f );

} Else if (temp2 [0]> = 'A' & temp2 [0] <= 'F '){
Temp2 [0]-= 0x57;

Temp2 [0] = (byte) (temp2 [0] & 0x0f );
}
Data_out [J] = (byte) (temp1 [0] | temp2 [0]);

I + = 2;
}

}

Protected string replaceall (string strurl, string straugs ){

// The string class in jdk1.3 does not have the replaceall Method
/*************************************** **********************/
Int start = 0;
Int end = 0;
String temp = new string ();
While (start <strurl. Length ()){
End = strurl. indexof ("", start );
If (end! =-1 ){
Temp = temp. Concat (strurl. substring (START, end). Concat ("% 20 "));
If (START = end + 1)> = strurl. Length ()){
Strurl = temp;
Break;
}

} Else if (END =-1 ){
If (START = 0)
Break;
If (start <strurl. Length ()){
Temp = temp. Concat (strurl. substring (START, strurl. Length ()));
Strurl = temp;
Break;
}
}

}

Temp = "";
Start = END = 0;

While (start <straugs. Length ()){
End = straugs. indexof ("", start );
If (end! =-1 ){
Temp = temp. Concat (straugs. substring (START, end). Concat ("% 20 "));
If (START = end + 1)> = straugs. Length ()){
Straugs = temp;
Break;
}

} Else if (END =-1 ){
If (START = 0)
Break;
If (start <straugs. Length ()){
Temp = temp. Concat (straugs. substring (START, straugs. Length ()));
Straugs = temp;
Break;
}
}

}

/*************************************** ****************************/
Return straugs;
}
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.