List of usage examples for java.security KeyFactory generatePublic
public final PublicKey generatePublic(KeySpec keySpec) throws InvalidKeySpecException
From source file:de.tum.frm2.nicos_android.nicos.NicosClient.java
private PublicKey extractPublicKey(String source) { // Java wants the key formatted without prefix and postfix. String prefix = "-----BEGIN RSA PUBLIC KEY-----"; String postfix = "\n-----END RSA PUBLIC KEY-----"; // Java's string formatting/slicing is... 'slightly' inferior to python's. String keyNoPrefix = source.substring(prefix.length()); String reversed = new StringBuilder(keyNoPrefix).reverse().toString(); String reversedNoPostfix = reversed.substring(postfix.length()); String keyString = new StringBuilder(reversedNoPostfix).reverse().toString(); keyString = keyString.replace("\n", ""); ASN1InputStream in = new ASN1InputStream(Base64.decode(keyString, Base64.NO_WRAP)); ASN1Primitive obj;/*from w w w . java2 s .com*/ try { obj = in.readObject(); } catch (IOException e) { return null; } RSAPublicKey key = RSAPublicKey.getInstance(obj); RSAPublicKeySpec keySpec = null; if (key != null) { keySpec = new RSAPublicKeySpec(key.getModulus(), key.getPublicExponent()); } KeyFactory keyFactory = null; try { keyFactory = KeyFactory.getInstance("RSA"); } catch (NoSuchAlgorithmException e) { // Cannot happen. } PublicKey pubkey = null; try { if (keyFactory != null) { pubkey = keyFactory.generatePublic(keySpec); } } catch (InvalidKeySpecException e) { // Cannot (SHOULD NOT) happen. } return pubkey; }
From source file:com.goodhustle.ouyaunitybridge.OuyaUnityActivity.java
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); OuyaController.init(this); // Initialize ouyaFacade ouyaFacade = OuyaFacade.getInstance(); ouyaFacade.init(this, DEVELOPER_ID); userManager = UserManager.getInstance(this); playerStates = new ControllerState[OuyaController.MAX_CONTROLLERS]; for (int i = 0; i < OuyaController.MAX_CONTROLLERS; i++) { playerStates[i] = new ControllerState(); }//www . j ava 2 s. c o m // Create the UnityPlayer mUnityPlayer = new UnityPlayer(this); int glesMode = mUnityPlayer.getSettings().getInt("gles_mode", 1); boolean trueColor8888 = false; mUnityPlayer.init(glesMode, trueColor8888); setContentView(R.layout.main); // Add the Unity view FrameLayout layout = (FrameLayout) findViewById(R.id.unityLayout); LayoutParams lp = new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT); layout.addView(mUnityPlayer.getView(), 0, lp); // Set the focus RelativeLayout mainLayout = (RelativeLayout) findViewById(R.id.mainLayout); mainLayout.setFocusableInTouchMode(true); // Attempt to restore the product and receipt list from the savedInstanceState Bundle if (savedInstanceState != null) { if (savedInstanceState.containsKey(PRODUCTS_INSTANCE_STATE_KEY)) { Parcelable[] products = savedInstanceState.getParcelableArray(PRODUCTS_INSTANCE_STATE_KEY); mProductList = new ArrayList<Product>(products.length); for (Parcelable product : products) { mProductList.add((Product) product); } addProducts(); } if (savedInstanceState.containsKey(RECEIPTS_INSTANCE_STATE_KEY)) { Parcelable[] receipts = savedInstanceState.getParcelableArray(RECEIPTS_INSTANCE_STATE_KEY); mReceiptList = new ArrayList<Receipt>(receipts.length); for (Parcelable receipt : receipts) { mReceiptList.add((Receipt) receipt); } addReceipts(); } } // Request the product list if it could not be restored from the savedInstanceState Bundle if (mProductList == null) { requestProducts(); } // Create a PublicKey object from the key data downloaded from the developer portal. try { X509EncodedKeySpec keySpec = new X509EncodedKeySpec(APPLICATION_KEY); KeyFactory keyFactory = KeyFactory.getInstance("RSA"); mPublicKey = keyFactory.generatePublic(keySpec); } catch (Exception e) { Log.e(LOG_TAG, "Unable to create encryption key", e); } }
From source file:org.mitre.jwt.JwtTest.java
/** * @throws Exception/*www . j a va2s . c om*/ */ @Test public void testGenerateRsaSignature() throws Exception { // Hard code the private/public key so as not to depend on it being in // the keystore... RSAPrivateKeySpec privateSpec = new RSAPrivateKeySpec(new BigInteger( "AD6E684550542947AD95EF9BACDC0AC2C9168C6EB3212D378C23E5539266111DB2E5B4D42B1E47EB4F7A65DB63D9782C72BC365492FD1E5C7B4CD2174C611668C29013FEDE22619B3F58DA3531BB6C02B3266768B7895CBDAFB3F9AC7A7B2F3DB17EF4DCF03BD2575604BDE0A01BB1FB7B0E733AD63E464DB4D7D89626297A214D7CECCD0C50421A322A01E9DCEA23443F6A9339576B31DFA504A133076394562CB57F3FDEDB26F9A82BED2F6D52D6F6BF8286E2497EF0B5C8456F32B4668F5A9F5FCD3781345DDDB749792C37238A53D18FD976C0C9D1F1E211F1A4A9AAE679C45B92D1741EF0D3C3F373232CE7FB93E9BC461E1C508A20B74E7E3361B3C527", 16), new BigInteger( "627CDD67E75B33EA0990A8F64DEED389942A62EB867C23B274B9F9C440D2078C47089D6D136369D21E5B52B688F8797F3C54D7C1A58B6A8F7851C2C90A4DE42CEFB864328B31191ED19582AD4CA5B38BC0F2E12C9D75BB1DD946AA55A1648D0A4ADEDEED0CDBDBF24EDDF87A345225FBBB0114BCE7E78B831B5CAC197068837AB0B3F07157952A05F67A72B9852972C704B6B32A70C3BB3DEB186936B0F7D6ABE012DEB89BC2DBE1F88AE7A28C06C53D1FB2459E58D8ED266E3BFC28266981D2A5F624D36555DD64F410461ADA5D53F448BA5EEBBD4BCEC3AF53285FB394650D7B3BFB06712E081AAD160EED6E83A3EA2D092712C07A6331209F62D27184BFC9", 16)); KeyFactory keyFactory = KeyFactory.getInstance("RSA"); PrivateKey privateKey = keyFactory.generatePrivate(privateSpec); RSAPublicKeySpec publicSpec = new RSAPublicKeySpec(new BigInteger( "AD6E684550542947AD95EF9BACDC0AC2C9168C6EB3212D378C23E5539266111DB2E5B4D42B1E47EB4F7A65DB63D9782C72BC365492FD1E5C7B4CD2174C611668C29013FEDE22619B3F58DA3531BB6C02B3266768B7895CBDAFB3F9AC7A7B2F3DB17EF4DCF03BD2575604BDE0A01BB1FB7B0E733AD63E464DB4D7D89626297A214D7CECCD0C50421A322A01E9DCEA23443F6A9339576B31DFA504A133076394562CB57F3FDEDB26F9A82BED2F6D52D6F6BF8286E2497EF0B5C8456F32B4668F5A9F5FCD3781345DDDB749792C37238A53D18FD976C0C9D1F1E211F1A4A9AAE679C45B92D1741EF0D3C3F373232CE7FB93E9BC461E1C508A20B74E7E3361B3C527", 16), new BigInteger("10001", 16)); PublicKey publicKey = keyFactory.generatePublic(publicSpec); Jwt jwt = new Jwt(); jwt.getHeader().setType("JWT"); jwt.getHeader().setAlgorithm("RS256"); jwt.getClaims().setExpiration(new Date(1300819380L * 1000L)); jwt.getClaims().setIssuer("joe"); jwt.getClaims().setClaim("http://example.com/is_root", Boolean.TRUE); JwtSigner signer = new RsaSigner(JwsAlgorithm.RS256.getJwaName(), publicKey, privateKey); ((RsaSigner) signer).afterPropertiesSet(); /* * Expected string based on the following structures, serialized exactly * as follows and base64 encoded: * * header: {"typ":"JWT","alg":"HS256"} claims: * {"exp":1300819380,"iss":"joe","http://example.com/is_root":true} * * Expected signature: dSRvtD-ExzGN- * fRXd1wRZOPo1JFPuqgwvaIKp8jgcyMXJegy6IUjssfUfUcICN5yvh0ggOMWMeWkwQ7 * -PlXMJWymdhXVI3BOpNt7ZOB2vMFYSOOHNBJUunQoe1lmNxuHQdhxqoHahn3u1cLDXz * -xx- * JELduuMmaDWqnTFPodVPl45WBKHaQhlOiFWj3ZClUV2k5p2yBT8TmxekL8gWwgVbQk5yPnYOs * -PcMjzODc9MZX4yI10ZSCSDciwf- * rgkQLT7wW4uZCoqTZ7187sCodHd6nw3nghqbtqN05fQ3Yq7ykwaR8pdQBFb2L9l7DhLLuXIREDKIFUHBSUs8OnvXFMg */ String signature = "dSRvtD-ExzGN-fRXd1wRZOPo1JFPuqgwvaIKp8jgcyMXJegy6IUjssfUfUcICN5yvh0ggOMWMeWkwQ7-PlXMJWymdhXVI3BOpNt7ZOB2vMFYSOOHNBJUunQoe1lmNxuHQdhxqoHahn3u1cLDXz-xx-JELduuMmaDWqnTFPodVPl45WBKHaQhlOiFWj3ZClUV2k5p2yBT8TmxekL8gWwgVbQk5yPnYOs-PcMjzODc9MZX4yI10ZSCSDciwf-rgkQLT7wW4uZCoqTZ7187sCodHd6nw3nghqbtqN05fQ3Yq7ykwaR8pdQBFb2L9l7DhLLuXIREDKIFUHBSUs8OnvXFMg"; String expected = "eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJleHAiOjEzMDA4MTkzODAsImlzcyI6ImpvZSIsImh0dHA6Ly9leGFtcGxlLmNvbS9pc19yb290Ijp0cnVlfQ" + "." + signature; signer.sign(jwt); String actual = jwt.toString(); assertThat(signer.verify(actual), equalTo(true)); assertThat(actual, equalTo(expected)); assertThat(jwt.getSignature(), equalTo(signature)); }
From source file:com.charabia.SmsViewActivity.java
@Override public void onActivityResult(int reqCode, int resultCode, Intent data) { super.onActivityResult(reqCode, resultCode, data); switch (reqCode) { case SMS_KEY_CONTACT: if (resultCode == RESULT_OK) { Uri uri = data.getData();// www . j av a 2 s.c o m ContentResolver cr = getContentResolver(); Cursor cursor = cr.query(uri, new String[] { Contacts.LOOKUP_KEY }, null, null, null); String lookup = null; if (cursor.moveToFirst()) { lookup = cursor.getString(0); } cursor.close(); if (lookup == null) { Toast.makeText(this, R.string.unexpected_error, Toast.LENGTH_LONG).show(); return; } cursor = cr.query(Data.CONTENT_URI, new String[] { Phone.NUMBER }, Data.MIMETYPE + "=? AND " + Data.LOOKUP_KEY + "=?", new String[] { Phone.CONTENT_ITEM_TYPE, lookup }, null); ArrayList<String> options = new ArrayList<String>(); while (cursor.moveToNext()) { options.add(cursor.getString(0)); } cursor.close(); final String[] phoneList = options.toArray(new String[0]); Builder builder = new AlertDialog.Builder(this); builder.setTitle(R.string.send_invit_on_phone); builder.setItems(phoneList, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialogInterface, int i) { keypair = tools.loadKeyPair(); RSAPublicKey pubKey = (RSAPublicKey) keypair.getPublic(); byte[] encoded = pubKey.getModulus().toByteArray(); byte[] data = new byte[3 + encoded.length]; data[0] = Tools.MAGIC[0]; data[1] = Tools.MAGIC[1]; data[2] = Tools.PUBLIC_KEY_TYPE; System.arraycopy(encoded, 0, data, 3, encoded.length); tools.sendData(phoneList[i], Tools.INVITATION, "", data); } }); builder.create().show(); } else { Toast.makeText(this, R.string.error_create_key, Toast.LENGTH_LONG).show(); } break; case IntentIntegrator.REQUEST_CODE: if (resultCode == RESULT_OK) { try { String contents = data.getStringExtra("SCAN_RESULT"); @SuppressWarnings("unused") String format = data.getStringExtra("SCAN_RESULT_FORMAT"); // Handle successful scan // TODO: add more tests control String[] infos = contents.split("\n"); Cipher rsaCipher = Cipher.getInstance(Tools.RSA_CIPHER_ALGO); if (mode == MODE_ESCLAVE) { // Save key and show crypted key on QRCode key = tools.generateKeyAES().getEncoded(); KeyFactory keyFact = KeyFactory.getInstance("RSA"); PublicKey pubkey = keyFact.generatePublic( new RSAPublicKeySpec(new BigInteger(infos[1]), new BigInteger(infos[2]))); rsaCipher.init(Cipher.ENCRYPT_MODE, pubkey); int blockSize = rsaCipher.getBlockSize(); int nbBlock = key.length / blockSize; int reste = key.length % blockSize; byte[] cryptedKey = new byte[(nbBlock + 1) * rsaCipher.getOutputSize(blockSize)]; int offset = 0; for (int i = 0; i < nbBlock; i++) { offset += rsaCipher.doFinal(key, i * blockSize, blockSize, cryptedKey, offset); } rsaCipher.doFinal(key, nbBlock * blockSize, reste, cryptedKey, offset); IntentIntegrator.shareText(SmsViewActivity.this, prefPhoneNumber + "\n" + Base64.encodeToString(cryptedKey, Base64.NO_WRAP)); } else { // We have read crypted key, so decode it rsaCipher.init(Cipher.DECRYPT_MODE, keypair.getPrivate()); byte[] cryptedData = Base64.decode(infos[1], Base64.NO_WRAP); int blockSize = rsaCipher.getBlockSize(); int nbBlock = cryptedData.length / blockSize; int offset = 0; byte[] tempKey = new byte[(nbBlock + 1) * blockSize]; for (int i = 0; i < nbBlock; i++) { offset += rsaCipher.doFinal(cryptedData, i * blockSize, blockSize, tempKey, offset); } key = new byte[offset]; System.arraycopy(tempKey, 0, key, 0, offset); } phoneNumber = infos[0]; // store the key // TODO dialog to confirm add contact in mode SLAVE try { new Tools(this).updateOrCreateContactKey(phoneNumber, key); } catch (NoContactException e) { e.printStackTrace(); // propose to add contact Intent newIntent = new Intent(Intents.SHOW_OR_CREATE_CONTACT); newIntent.setData(Uri.fromParts("tel", phoneNumber, null)); startActivityForResult(newIntent, ADD_CONTACT); return; } Toast.makeText(this, getString(R.string.contact_added) + "\n" + phoneNumber, Toast.LENGTH_LONG) .show(); } catch (Exception e) { e.printStackTrace(); Toast.makeText(this, R.string.error_create_key, Toast.LENGTH_LONG).show(); } } else { // TODO: string Toast.makeText(this, R.string.fail_reading_tag, Toast.LENGTH_LONG).show(); } break; case ADD_CONTACT: try { tools.updateOrCreateContactKey(phoneNumber, key); Toast.makeText(this, getString(R.string.contact_added) + "\n" + phoneNumber, Toast.LENGTH_LONG) .show(); } catch (NoContactException e) { e.printStackTrace(); Toast.makeText(this, R.string.error_create_key, Toast.LENGTH_LONG).show(); } break; } }
From source file:com.magestore.app.pos.api.m1.config.POSConfigDataAccessM1.java
private String decryptRSAToString(String encryptedBase64, String privateKey) { String decryptedString = ""; try {//from ww w. j a v a 2 s . c o m String rStart = privateKey.replace("-----BEGIN PUBLIC KEY-----", ""); String rEnd = rStart.replace("-----END PUBLIC KEY-----", ""); rEnd = rEnd.replaceAll("\r", ""); rEnd = rEnd.replaceAll("\n", ""); rEnd = rEnd.replaceAll("\t", ""); rEnd = rEnd.replaceAll(" ", ""); KeyFactory keyFac = KeyFactory.getInstance("RSA"); PublicKey publicKey = keyFac .generatePublic(new X509EncodedKeySpec(Base64.decode(rEnd.toString(), Base64.DEFAULT))); // get an RSA cipher object and print the provider final Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding", "BC"); // encrypt the plain text using the public key cipher.init(Cipher.DECRYPT_MODE, publicKey); byte[] encryptedBytes = Base64.decode(encryptedBase64, Base64.DEFAULT); byte[] decryptedBytes = cipher.doFinal(encryptedBytes); decryptedString = new String(decryptedBytes); } catch (Exception e) { e.printStackTrace(); } return decryptedString; }
From source file:org.apache.geode.internal.cache.tier.sockets.HandShake.java
public Properties readCredential(DataInputStream dis, DataOutputStream dos, DistributedSystem system) throws GemFireSecurityException, IOException { Properties credentials = null; boolean requireAuthentication = securityService.isClientSecurityRequired(); try {//from w w w . jav a 2 s.c o m byte secureMode = dis.readByte(); throwIfMissingRequiredCredentials(requireAuthentication, secureMode != CREDENTIALS_NONE); if (secureMode == CREDENTIALS_NORMAL) { this.appSecureMode = CREDENTIALS_NORMAL; /* * if (requireAuthentication) { credentials = DataSerializer.readProperties(dis); } else { * DataSerializer.readProperties(dis); // ignore the credentials } */ } else if (secureMode == CREDENTIALS_DHENCRYPT) { this.appSecureMode = CREDENTIALS_DHENCRYPT; boolean sendAuthentication = dis.readBoolean(); InternalLogWriter securityLogWriter = (InternalLogWriter) system.getSecurityLogWriter(); // Get the symmetric encryption algorithm to be used // String skAlgo = DataSerializer.readString(dis); this.clientSKAlgo = DataSerializer.readString(dis); // Get the public key of the other side byte[] keyBytes = DataSerializer.readByteArray(dis); byte[] challenge = null; // PublicKey pubKey = null; if (requireAuthentication) { // Generate PublicKey from encoded form X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes); KeyFactory keyFact = KeyFactory.getInstance("DH"); this.clientPublicKey = keyFact.generatePublic(x509KeySpec); // Send the public key to other side keyBytes = dhPublicKey.getEncoded(); challenge = new byte[64]; random.nextBytes(challenge); // If the server has to also authenticate itself then // sign the challenge from client. if (sendAuthentication) { // Get the challenge string from client byte[] clientChallenge = DataSerializer.readByteArray(dis); if (privateKeyEncrypt == null) { throw new AuthenticationFailedException( LocalizedStrings.HandShake_SERVER_PRIVATE_KEY_NOT_AVAILABLE_FOR_CREATING_SIGNATURE .toLocalizedString()); } // Sign the challenge from client and send it to the client Signature sig = Signature.getInstance(privateKeySignAlgo); sig.initSign(privateKeyEncrypt); sig.update(clientChallenge); byte[] signedBytes = sig.sign(); dos.writeByte(REPLY_OK); DataSerializer.writeByteArray(keyBytes, dos); // DataSerializer.writeString(privateKeyAlias, dos); DataSerializer.writeString(privateKeySubject, dos); DataSerializer.writeByteArray(signedBytes, dos); securityLogWriter.fine("HandShake: sent the signed client challenge"); } else { // These two lines should not be moved before the if{} statement in // a common block for both if...then...else parts. This is to handle // the case when an AuthenticationFailedException is thrown by the // if...then part when sending the signature. dos.writeByte(REPLY_OK); DataSerializer.writeByteArray(keyBytes, dos); } // Now send the server challenge DataSerializer.writeByteArray(challenge, dos); securityLogWriter.fine("HandShake: sent the public key and challenge"); dos.flush(); // Read and decrypt the credentials byte[] encBytes = DataSerializer.readByteArray(dis); Cipher c = getDecryptCipher(this.clientSKAlgo, this.clientPublicKey); byte[] credentialBytes = decryptBytes(encBytes, c); ByteArrayInputStream bis = new ByteArrayInputStream(credentialBytes); DataInputStream dinp = new DataInputStream(bis); // credentials = DataSerializer.readProperties(dinp);//Hitesh: we don't send in handshake // now byte[] challengeRes = DataSerializer.readByteArray(dinp); // Check the challenge string if (!Arrays.equals(challenge, challengeRes)) { throw new AuthenticationFailedException( LocalizedStrings.HandShake_MISMATCH_IN_CHALLENGE_BYTES_MALICIOUS_CLIENT .toLocalizedString()); } dinp.close(); } else { if (sendAuthentication) { // Read and ignore the client challenge DataSerializer.readByteArray(dis); } dos.writeByte(REPLY_AUTH_NOT_REQUIRED); dos.flush(); } } } catch (IOException ex) { throw ex; } catch (GemFireSecurityException ex) { throw ex; } catch (Exception ex) { throw new AuthenticationFailedException( LocalizedStrings.HandShake_FAILURE_IN_READING_CREDENTIALS.toLocalizedString(), ex); } return credentials; }
From source file:org.apache.geode.internal.cache.tier.sockets.HandShake.java
/** * This assumes that authentication is the last piece of info in handshake *//*from w w w. ja v a 2s. c om*/ public void writeCredentials(DataOutputStream dos, DataInputStream dis, Properties p_credentials, boolean isNotification, DistributedMember member, HeapDataOutputStream heapdos) throws IOException, GemFireSecurityException { if (p_credentials == null) { // No credentials indicator heapdos.writeByte(CREDENTIALS_NONE); heapdos.flush(); dos.write(heapdos.toByteArray()); dos.flush(); return; } if (dhSKAlgo == null || dhSKAlgo.length() == 0) { // Normal credentials without encryption indicator heapdos.writeByte(CREDENTIALS_NORMAL); DataSerializer.writeProperties(p_credentials, heapdos); heapdos.flush(); dos.write(heapdos.toByteArray()); dos.flush(); return; } try { InternalLogWriter securityLogWriter = (InternalLogWriter) this.system.getSecurityLogWriter(); securityLogWriter.fine("HandShake: using Diffie-Hellman key exchange with algo " + dhSKAlgo); boolean requireAuthentication = (certificateFilePath != null && certificateFilePath.length() > 0); if (requireAuthentication) { securityLogWriter.fine("HandShake: server authentication using digital " + "signature required"); } // Credentials with encryption indicator heapdos.writeByte(CREDENTIALS_DHENCRYPT); heapdos.writeBoolean(requireAuthentication); // Send the symmetric encryption algorithm name DataSerializer.writeString(dhSKAlgo, heapdos); // Send the DH public key byte[] keyBytes = dhPublicKey.getEncoded(); DataSerializer.writeByteArray(keyBytes, heapdos); byte[] clientChallenge = null; if (requireAuthentication) { // Authentication of server should be with the client supplied // challenge clientChallenge = new byte[64]; random.nextBytes(clientChallenge); DataSerializer.writeByteArray(clientChallenge, heapdos); } heapdos.flush(); dos.write(heapdos.toByteArray()); dos.flush(); // Expect the alias and signature in the reply byte acceptanceCode = dis.readByte(); if (acceptanceCode != REPLY_OK && acceptanceCode != REPLY_AUTH_NOT_REQUIRED) { // Ignore the useless data dis.readByte(); dis.readInt(); if (!isNotification) { DataSerializer.readByteArray(dis); } readMessage(dis, dos, acceptanceCode, member); } else if (acceptanceCode == REPLY_OK) { // Get the public key of the other side keyBytes = DataSerializer.readByteArray(dis); if (requireAuthentication) { String subject = DataSerializer.readString(dis); byte[] signatureBytes = DataSerializer.readByteArray(dis); if (!certificateMap.containsKey(subject)) { throw new AuthenticationFailedException( LocalizedStrings.HandShake_HANDSHAKE_FAILED_TO_FIND_PUBLIC_KEY_FOR_SERVER_WITH_SUBJECT_0 .toLocalizedString(subject)); } // Check the signature with the public key X509Certificate cert = (X509Certificate) certificateMap.get(subject); Signature sig = Signature.getInstance(cert.getSigAlgName()); sig.initVerify(cert); sig.update(clientChallenge); // Check the challenge string if (!sig.verify(signatureBytes)) { throw new AuthenticationFailedException( "Mismatch in client " + "challenge bytes. Malicious server?"); } securityLogWriter .fine("HandShake: Successfully verified the " + "digital signature from server"); } byte[] challenge = DataSerializer.readByteArray(dis); X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes); KeyFactory keyFact = KeyFactory.getInstance("DH"); // PublicKey pubKey = keyFact.generatePublic(x509KeySpec); this.clientPublicKey = keyFact.generatePublic(x509KeySpec); HeapDataOutputStream hdos = new HeapDataOutputStream(Version.CURRENT); try { DataSerializer.writeProperties(p_credentials, hdos); // Also add the challenge string DataSerializer.writeByteArray(challenge, hdos); // byte[] encBytes = encrypt.doFinal(hdos.toByteArray()); byte[] encBytes = encryptBytes(hdos.toByteArray(), getEncryptCipher(dhSKAlgo, this.clientPublicKey)); DataSerializer.writeByteArray(encBytes, dos); } finally { hdos.close(); } } } catch (IOException ex) { throw ex; } catch (GemFireSecurityException ex) { throw ex; } catch (Exception ex) { throw new AuthenticationFailedException("HandShake failed in Diffie-Hellman key exchange", ex); } dos.flush(); }
From source file:org.apache.geode.internal.cache.tier.sockets.HandShake.java
/** * This method writes what readCredential() method expects to read. (Note the use of singular * credential). It is similar to writeCredentials(), except that it doesn't write * credential-properties.//from w w w . j a va 2s . c o m */ public byte writeCredential(DataOutputStream dos, DataInputStream dis, String authInit, boolean isNotification, DistributedMember member, HeapDataOutputStream heapdos) throws IOException, GemFireSecurityException { if (!this.multiuserSecureMode && (authInit == null || authInit.length() == 0)) { // No credentials indicator heapdos.writeByte(CREDENTIALS_NONE); heapdos.flush(); dos.write(heapdos.toByteArray()); dos.flush(); return -1; } if (dhSKAlgo == null || dhSKAlgo.length() == 0) { // Normal credentials without encryption indicator heapdos.writeByte(CREDENTIALS_NORMAL); this.appSecureMode = CREDENTIALS_NORMAL; // DataSerializer.writeProperties(p_credentials, heapdos); heapdos.flush(); dos.write(heapdos.toByteArray()); dos.flush(); return -1; } byte acceptanceCode = -1; try { InternalLogWriter securityLogWriter = (InternalLogWriter) this.system.getSecurityLogWriter(); securityLogWriter.fine("HandShake: using Diffie-Hellman key exchange with algo " + dhSKAlgo); boolean requireAuthentication = (certificateFilePath != null && certificateFilePath.length() > 0); if (requireAuthentication) { securityLogWriter.fine("HandShake: server authentication using digital " + "signature required"); } // Credentials with encryption indicator heapdos.writeByte(CREDENTIALS_DHENCRYPT); this.appSecureMode = CREDENTIALS_DHENCRYPT; heapdos.writeBoolean(requireAuthentication); // Send the symmetric encryption algorithm name DataSerializer.writeString(dhSKAlgo, heapdos); // Send the DH public key byte[] keyBytes = dhPublicKey.getEncoded(); DataSerializer.writeByteArray(keyBytes, heapdos); byte[] clientChallenge = null; if (requireAuthentication) { // Authentication of server should be with the client supplied // challenge clientChallenge = new byte[64]; random.nextBytes(clientChallenge); DataSerializer.writeByteArray(clientChallenge, heapdos); } heapdos.flush(); dos.write(heapdos.toByteArray()); dos.flush(); // Expect the alias and signature in the reply acceptanceCode = dis.readByte(); if (acceptanceCode != REPLY_OK && acceptanceCode != REPLY_AUTH_NOT_REQUIRED) { // Ignore the useless data dis.readByte(); dis.readInt(); if (!isNotification) { DataSerializer.readByteArray(dis); } readMessage(dis, dos, acceptanceCode, member); } else if (acceptanceCode == REPLY_OK) { // Get the public key of the other side keyBytes = DataSerializer.readByteArray(dis); if (requireAuthentication) { String subject = DataSerializer.readString(dis); byte[] signatureBytes = DataSerializer.readByteArray(dis); if (!certificateMap.containsKey(subject)) { throw new AuthenticationFailedException( LocalizedStrings.HandShake_HANDSHAKE_FAILED_TO_FIND_PUBLIC_KEY_FOR_SERVER_WITH_SUBJECT_0 .toLocalizedString(subject)); } // Check the signature with the public key X509Certificate cert = (X509Certificate) certificateMap.get(subject); Signature sig = Signature.getInstance(cert.getSigAlgName()); sig.initVerify(cert); sig.update(clientChallenge); // Check the challenge string if (!sig.verify(signatureBytes)) { throw new AuthenticationFailedException( "Mismatch in client " + "challenge bytes. Malicious server?"); } securityLogWriter .fine("HandShake: Successfully verified the " + "digital signature from server"); } // Read server challenge bytes byte[] serverChallenge = DataSerializer.readByteArray(dis); X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes); KeyFactory keyFact = KeyFactory.getInstance("DH"); // PublicKey pubKey = keyFact.generatePublic(x509KeySpec); this.clientPublicKey = keyFact.generatePublic(x509KeySpec); HeapDataOutputStream hdos = new HeapDataOutputStream(Version.CURRENT); try { // Add the challenge string DataSerializer.writeByteArray(serverChallenge, hdos); // byte[] encBytes = encrypt.doFinal(hdos.toByteArray()); byte[] encBytes = encryptBytes(hdos.toByteArray(), getEncryptCipher(dhSKAlgo, this.clientPublicKey)); DataSerializer.writeByteArray(encBytes, dos); } finally { hdos.close(); } } } catch (IOException ex) { throw ex; } catch (GemFireSecurityException ex) { throw ex; } catch (Exception ex) { throw new AuthenticationFailedException("HandShake failed in Diffie-Hellman key exchange", ex); } dos.flush(); return acceptanceCode; }
From source file:org.openbravo.erpCommon.obps.ActivationKey.java
private PublicKey getPublicKey(String strPublickey) { try {//from ww w . ja v a 2s. c om KeyFactory keyFactory = KeyFactory.getInstance("RSA"); byte[] rawPublicKey = org.apache.commons.codec.binary.Base64.decodeBase64(strPublickey.getBytes()); X509EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(rawPublicKey); return keyFactory.generatePublic(publicKeySpec); } catch (Exception e) { log.error(e.getMessage(), e); return null; } }
From source file:android.content.pm.PackageParser.java
public static final PublicKey parsePublicKey(final String encodedPublicKey) { if (encodedPublicKey == null) { Slog.w(TAG, "Could not parse null public key"); return null; }/*from www . j a v a 2s. c o m*/ EncodedKeySpec keySpec; try { final byte[] encoded = Base64.decode(encodedPublicKey, Base64.DEFAULT); keySpec = new X509EncodedKeySpec(encoded); } catch (IllegalArgumentException e) { Slog.w(TAG, "Could not parse verifier public key; invalid Base64"); return null; } /* First try the key as an RSA key. */ try { final KeyFactory keyFactory = KeyFactory.getInstance("RSA"); return keyFactory.generatePublic(keySpec); } catch (NoSuchAlgorithmException e) { Slog.wtf(TAG, "Could not parse public key: RSA KeyFactory not included in build"); } catch (InvalidKeySpecException e) { // Not a RSA public key. } /* Now try it as a ECDSA key. */ try { final KeyFactory keyFactory = KeyFactory.getInstance("EC"); return keyFactory.generatePublic(keySpec); } catch (NoSuchAlgorithmException e) { Slog.wtf(TAG, "Could not parse public key: EC KeyFactory not included in build"); } catch (InvalidKeySpecException e) { // Not a ECDSA public key. } /* Now try it as a DSA key. */ try { final KeyFactory keyFactory = KeyFactory.getInstance("DSA"); return keyFactory.generatePublic(keySpec); } catch (NoSuchAlgorithmException e) { Slog.wtf(TAG, "Could not parse public key: DSA KeyFactory not included in build"); } catch (InvalidKeySpecException e) { // Not a DSA public key. } /* Not a supported key type */ return null; }