android - Key from String in Java RSA -
i using in app rsa cryptography. store generated public key convert string , save in database.
key publickey=null; key privatekey=null; keypair keypair=rsacrypto.getkeypairrsa(1024); publickey=keypair.getpublic(); privatekey=keypair.getprivate(); string publick=base64.encodetostring(publickey.getencoded(), base64.default); string privatek=base64.encodetostring(privatekey.getencoded(), base64.default);
i save strings publick
, privatek
. problem is, when want encrypt/decrypt text rsa , use saved key in string format don't know how convert key
.
public static string encrypt(key publickey, string inputtext){ byte[]encodedbytes=null; string encryptedtext=""; try { cipher cipher=cipher.getinstance("rsa"); cipher.init(cipher.encrypt_mode, publickey); encodedbytes=cipher.dofinal(inputtext.getbytes()); } catch (exception e) {log.e("error", "rsa encryption error"); } encryptedtext=base64.encodetostring(encodedbytes, base64.default); return encryptedtext; }
do have idea? lot
to convert publick(string) public key below :
byte[] keybytes = base64.decode(publick.getbytes("utf-8")); x509encodedkeyspec spec = new x509encodedkeyspec(keybytes); keyfactory keyfactory = keyfactory.getinstance("rsa"); publickey key = keyfactory.generatepublic(spec);
to convert privatek(string) private key below :
byte[] keybytes = base64.decode(privatek.getbytes("utf-8")); pkcs8encodedkeyspec keyspec = new pkcs8encodedkeyspec(keybytes); keyfactory fact = keyfactory.getinstance("rsa"); privatekey priv = fact.generateprivate(keyspec);
Comments
Post a Comment