List of usage examples for java.security.interfaces RSAPublicKey getModulus
public BigInteger getModulus();
From source file:test.integ.be.fedict.commons.eid.client.JCATest.java
@Test public void testPSSPrefix() throws Exception { Security.addProvider(new BeIDProvider()); Security.addProvider(new BouncyCastleProvider()); KeyStore keyStore = KeyStore.getInstance("BeID"); keyStore.load(null);//w ww.jav a 2 s. c o m PrivateKey authnPrivateKey = (PrivateKey) keyStore.getKey("Authentication", null); X509Certificate authnCertificate = (X509Certificate) keyStore.getCertificate("Authentication"); PublicKey authnPublicKey = authnCertificate.getPublicKey(); Signature signature = Signature.getInstance("SHA1withRSAandMGF1"); signature.initSign(authnPrivateKey); byte[] toBeSigned = "hello world".getBytes(); signature.update(toBeSigned); byte[] signatureValue = signature.sign(); signature.initVerify(authnPublicKey); signature.update(toBeSigned); boolean result = signature.verify(signatureValue); assertTrue(result); RSAPublicKey rsaPublicKey = (RSAPublicKey) authnPublicKey; BigInteger signatureValueBigInteger = new BigInteger(signatureValue); BigInteger messageBigInteger = signatureValueBigInteger.modPow(rsaPublicKey.getPublicExponent(), rsaPublicKey.getModulus()); String paddedMessage = new String(Hex.encodeHex(messageBigInteger.toByteArray())); LOG.debug("padded message: " + paddedMessage); assertTrue(paddedMessage.endsWith("bc")); }
From source file:qauth.djd.qauthclient.main.ContentFragment.java
@Override public void onMessageReceived(MessageEvent messageEvent) { Log.i("qAuthWear", "on message received23123123!!!!!"); if (messageEvent.getPath().equals("REGISTER")) { //Log.i("test", "device id:" + messageEvent.getData().toString()); watch = null;//w ww . j a v a2 s. c om ByteArrayInputStream bis = new ByteArrayInputStream(messageEvent.getData()); ObjectInput in = null; try { in = new ObjectInputStream(bis); } catch (Exception e) { Log.i("exception1", "e: " + e); } try { watch = (Watch) in.readObject(); } catch (Exception e) { Log.i("exception2", "e: " + e); } if (watch != null) { Log.i("WATCH SERIALIZABLE", "deviceId:" + watch.deviceId + " model:" + watch.model); getActivity().runOnUiThread(new Runnable() { @Override public void run() { if (!wDataset.contains(watch)) { wDataset.add(watch); wAdapter.notifyDataSetChanged(); } } }); RSAPrivateKey rsaPrivKey = null; RSAPublicKey rsaPubKey = null; try { rsaPrivKey = (RSAPrivateKey) Authenticate.getPrivKeyFromString(watch.privKey); rsaPubKey = (RSAPublicKey) Authenticate.getPubKeyFromString(watch.pubKey); } catch (Exception e) { } String N = rsaPubKey.getModulus().toString(10); //N int E = rsaPubKey.getPublicExponent().intValue(); //E for (String nodeId : getNodes()) { SharedPreferences prefs = getActivity().getSharedPreferences("qauth.djd.qauthclient", Context.MODE_PRIVATE); String email = prefs.getString("email", "email"); String password = prefs.getString("password", "password"); new RegisterBluetooth(email, password, watch.deviceId, N, E, nodeId).execute(); } } else { Log.i("WATCH SERIALIZABLE", "watch = null"); } } }
From source file:org.dasein.cloud.test.identity.IdentityResources.java
/** * @link http://stackoverflow.com/a/14582408/211197 * @return Encoded generated public key//from w w w . j av a2s .com */ private @Nullable String generateKey() { KeyPairGenerator generator; try { generator = KeyPairGenerator.getInstance("RSA"); generator.initialize(2048); KeyPair keyPair = generator.genKeyPair(); RSAPublicKey rsaPublicKey = (RSAPublicKey) keyPair.getPublic(); ByteArrayOutputStream byteOs = new ByteArrayOutputStream(); DataOutputStream dos = new DataOutputStream(byteOs); dos.writeInt("ssh-rsa".getBytes().length); dos.write("ssh-rsa".getBytes()); dos.writeInt(rsaPublicKey.getPublicExponent().toByteArray().length); dos.write(rsaPublicKey.getPublicExponent().toByteArray()); dos.writeInt(rsaPublicKey.getModulus().toByteArray().length); dos.write(rsaPublicKey.getModulus().toByteArray()); String publicKeyEncoded = new String(Base64.encodeBase64(byteOs.toByteArray())); return "ssh-rsa " + publicKeyEncoded + " dasein"; } catch (Throwable e) { return null; } }
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();//from w ww .j a va 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.qut.middleware.crypto.impl.CryptoProcessorImpl.java
public KeyDescriptor createSigningKeyDescriptor(RSAPublicKey pubKey, String keyPairName, String issuerDN, String serialNumber) {/*from ww w . ja v a2s .c o m*/ KeyDescriptor keyDescriptor = new KeyDescriptor(); keyDescriptor.setUse(KeyTypes.SIGNING); KeyInfo keyInfo = new KeyInfo(); KeyName keyName = new KeyName(keyPairName); keyInfo.getContent().add(keyName); KeyValue keyValue = new KeyValue(); RSAKeyValue rsaKeyValue = new RSAKeyValue(); rsaKeyValue.setExponent(pubKey.getPublicExponent().toByteArray()); rsaKeyValue.setModulus(pubKey.getModulus().toByteArray()); keyValue.getContent().add(rsaKeyValue); keyInfo.getContent().add(keyValue); keyDescriptor.setKeyInfo(keyInfo); if (issuerDN != null && serialNumber != null) { BigInteger serialNumberValue = new BigInteger(serialNumber); X509Data x509Data = new X509Data(); X509IssuerSerialType x509IssuerSerialType = new X509IssuerSerialType(); x509IssuerSerialType.setX509IssuerName(issuerDN); x509IssuerSerialType.setX509SerialNumber(serialNumberValue); x509Data.getX509DataContent() .add(new ObjectFactory().createX509DataX509IssuerSerial(x509IssuerSerialType)); keyInfo.getContent().add(x509Data); } logger.debug("Generated KeyDescriptor for document signing with keyname " + keyPairName); return keyDescriptor; }
From source file:acp.sdk.SecureUtil.java
/** * /*w w w .j ava 2 s . c om*/ * @param tPIN * @param iPan * @param publicKey * @return */ public String assymEncrypt(String tPIN, String iPan, RSAPublicKey publicKey) { System.out.println("SampleHashMap::assymEncrypt([" + tPIN + "])"); System.out.println("SampleHashMap::assymEncrypt(PIN =[" + tPIN + "])"); try { int tKeyLength = 1024; int tBlockSize = tKeyLength / 8; byte[] tTemp = null; tTemp = SecureUtil.pin2PinBlockWithCardNO(tPIN, iPan); tTemp = addPKCS1Padding(tTemp, tBlockSize); BigInteger tPlainText = new BigInteger(tTemp); BigInteger tCipherText = tPlainText.modPow(publicKey.getPublicExponent(), publicKey.getModulus()); byte[] tCipherBytes = tCipherText.toByteArray(); int tCipherLength = tCipherBytes.length; if (tCipherLength > tBlockSize) { byte[] tTempBytes = new byte[tBlockSize]; System.arraycopy(tCipherBytes, tCipherLength - tBlockSize, tTempBytes, 0, tBlockSize); tCipherBytes = tTempBytes; } else if (tCipherLength < tBlockSize) { byte[] tTempBytes = new byte[tBlockSize]; for (int i = 0; i < tBlockSize - tCipherLength; i++) { tTempBytes[i] = 0x00; } System.arraycopy(tCipherBytes, 0, tTempBytes, tBlockSize - tCipherLength, tCipherLength); tCipherBytes = tTempBytes; } String tEncryptPIN = new String(SecureUtil.base64Encode(tCipherBytes)); System.out.println("SampleHashMap::assymEncrypt(EncryptCardNo =[" + tEncryptPIN + "])"); return tEncryptPIN; } catch (Exception e) { e.printStackTrace(System.out); return tPIN; } catch (Error e) { e.printStackTrace(System.out); return tPIN; } }
From source file:org.globus.myproxy.MyProxy.java
/** * Retrieves delegated credentials from the MyProxy server. * * @param credential/*from w w w . j a v a 2 s. co m*/ * The local GSI credentials to use for authentication. * Can be set to null if no local credentials. * @param params * The parameters for the get operation. * @return GSSCredential * The retrieved delegated credentials. * @exception MyProxyException * If an error occurred during the operation. */ public GSSCredential get(GSSCredential credential, GetParams params) throws MyProxyException { if (params == null) { throw new IllegalArgumentException("params == null"); } if (credential == null) { try { credential = getAnonymousCredential(); } catch (GSSException e) { throw new MyProxyException("Failed to create anonymous credentials", e); } } String msg = params.makeRequest(); Socket gsiSocket = null; OutputStream out = null; InputStream in = null; try { gsiSocket = getSocket(credential); if (credential.getName().isAnonymous()) { this.context.requestAnonymity(true); } out = gsiSocket.getOutputStream(); in = gsiSocket.getInputStream(); if (!((GssSocket) gsiSocket).getContext().getConfState()) throw new Exception("Confidentiality requested but not available"); // send message out.write(msg.getBytes()); out.flush(); if (logger.isDebugEnabled()) { logger.debug("Req sent:" + params); } // may require authz handshake handleReply(in, out, params.getAuthzCreds(), params.getWantTrustroots()); // start delegation - generate key pair KeyPair keyPair = CertificateUtil.generateKeyPair("RSA", DEFAULT_KEYBITS); // According to the MyProxy protocol, the MyProxy server // will ignore the subject in the client's certificate // signing request (CSR). However, in some cases it is // helpful to control the CSR subject (for example, when // the MyProxy server is using a CA back-end that can only // issue certificates with subjects matching the request). // So we construct the CSR subject using the given MyProxy // username (if possible). String CSRsubjectString = params.getUserName(); CSRsubjectString = CSRsubjectString.trim(); if (CSRsubjectString.contains("CN=") || CSRsubjectString.contains("cn=")) { // If the MyProxy username is a DN, use it. if (CSRsubjectString.charAt(0) == '/') { // "good enough" conversion of OpenSSL DN strings CSRsubjectString = CSRsubjectString.substring(1); CSRsubjectString = CSRsubjectString.replace('/', ','); } } else { CSRsubjectString = "CN=" + CSRsubjectString; } X509Name CSRsubjectName; try { CSRsubjectName = new X509Name(CSRsubjectString); } catch (Exception e) { // If our X509Name construction fails for any reason, // just use a default value (as in the past). CSRsubjectName = new X509Name("CN=ignore"); } if (logger.isDebugEnabled()) { logger.debug("CSR subject: " + CSRsubjectName.toString()); } BouncyCastleCertProcessingFactory certFactory = BouncyCastleCertProcessingFactory.getDefault(); byte[] req = null; req = certFactory.createCertificateRequest(CSRsubjectName, "SHA1WithRSAEncryption", keyPair); // send the request to server out.write(req); out.flush(); // read the number of certificates int size = in.read(); if (logger.isDebugEnabled()) { logger.debug("Reading " + size + " certs"); } X509Certificate[] chain = new X509Certificate[size]; for (int i = 0; i < size; i++) { chain[i] = certFactory.loadCertificate(in); // DEBUG: display the cert names if (logger.isDebugEnabled()) { logger.debug("Received cert: " + chain[i].getSubjectDN()); } } // get the response handleReply(in); // make sure the private key belongs to the right public key // currently only works with RSA keys RSAPublicKey pkey = (RSAPublicKey) chain[0].getPublicKey(); RSAPrivateKey prkey = (RSAPrivateKey) keyPair.getPrivate(); if (!pkey.getModulus().equals(prkey.getModulus())) { throw new MyProxyException("Private/Public key mismatch!"); } X509Credential newCredential = null; newCredential = new X509Credential(keyPair.getPrivate(), chain); return new GlobusGSSCredentialImpl(newCredential, GSSCredential.INITIATE_AND_ACCEPT); } catch (Exception e) { throw new MyProxyException("MyProxy get failed.", e); } finally { // close socket close(out, in, gsiSocket); } }
From source file:com.netscape.cmsutil.crypto.CryptoUtil.java
public static byte[] getModulus(PublicKey pubk) { RSAPublicKey rsaKey = (RSAPublicKey) pubk; return rsaKey.getModulus().toByteArray(); }
From source file:com.netscape.cmsutil.crypto.CryptoUtil.java
public static X509Key convertPublicKeyToX509Key(PublicKey pubk) throws InvalidKeyException { X509Key xKey;/*w w w .j a v a 2s .c om*/ if (pubk instanceof RSAPublicKey) { RSAPublicKey rsaKey = (RSAPublicKey) pubk; xKey = new netscape.security.provider.RSAPublicKey(new BigInt(rsaKey.getModulus()), new BigInt(rsaKey.getPublicExponent())); } else if (pubk instanceof PK11ECPublicKey) { byte encoded[] = pubk.getEncoded(); xKey = CryptoUtil.getPublicX509ECCKey(encoded); } else { // Assert.assert(pubk instanceof DSAPublicKey); DSAPublicKey dsaKey = (DSAPublicKey) pubk; DSAParams params = dsaKey.getParams(); xKey = new netscape.security.provider.DSAPublicKey(dsaKey.getY(), params.getP(), params.getQ(), params.getG()); } return xKey; }