Java Code Examples for java.security.PublicKey

The following code examples are extracted from open source projects. You can click to vote up the examples that are useful to you.

Example 1

From project candlepin, under directory /src/main/java/org/candlepin/pki/.

Source file: PKIUtility.java

  25 
vote

public KeyPair decodeKeys(byte[] privKeyBits,byte[] pubKeyBits) throws InvalidKeySpecException, NoSuchAlgorithmException {
  KeyFactory keyFactory=KeyFactory.getInstance("RSA");
  PrivateKey privKey=keyFactory.generatePrivate(new PKCS8EncodedKeySpec(privKeyBits));
  PublicKey pubKey=keyFactory.generatePublic(new X509EncodedKeySpec(pubKeyBits));
  return new KeyPair(pubKey,privKey);
}
 

Example 2

From project AndroidBillingLibrary, under directory /AndroidBillingLibrary/src/net/robotmedia/billing/security/.

Source file: DefaultSignatureValidator.java

  23 
vote

public boolean validate(String signedData,String signature){
  final String publicKey;
  if (configuration == null || TextUtils.isEmpty(publicKey=configuration.getPublicKey())) {
    Log.w(BillingController.LOG_TAG,"Please set the public key or turn on debug mode");
    return false;
  }
  if (signedData == null) {
    Log.e(BillingController.LOG_TAG,"Data is null");
    return false;
  }
  PublicKey key=generatePublicKey(publicKey);
  return validate(key,signedData,signature);
}
 

Example 3

From project connectbot, under directory /src/sk/vx/connectbot/util/.

Source file: PubkeyUtils.java

  23 
vote

public static String getPubkeyString(PubkeyBean pubkey){
  try {
    PublicKey pk=pubkey.getPublicKey();
    return convertToOpenSSHFormat(pk,pubkey.getNickname());
  }
 catch (  Exception e) {
    e.printStackTrace();
  }
  return null;
}
 

Example 4

From project Cours-3eme-ann-e, under directory /Java/FerryInpres/src/identity_server/.

Source file: IdentityApplic.java

  23 
vote

public static SecretKey keyExchange(ObjectInputStream in,ObjectOutputStream out) throws IllegalBlockSizeException, BadPaddingException, InvalidKeyException, NoSuchAlgorithmException, IOException, ClassNotFoundException, NoSuchPaddingException {
  KeyPairGenerator gen=KeyPairGenerator.getInstance("RSA");
  gen.initialize(1024,new SecureRandom());
  KeyPair keys=gen.generateKeyPair();
  PublicKey publicKey=keys.getPublic();
  PrivateKey privateKey=keys.getPrivate();
  out.writeObject(new KeyExchangeClient(publicKey));
  out.flush();
  KeyExchangeServer response=(KeyExchangeServer)in.readObject();
  Cipher decryptor=Cipher.getInstance("RSA/ECB/PKCS1Padding");
  decryptor.init(Cipher.DECRYPT_MODE,privateKey);
  byte[] sessionKeyEncoded=decryptor.doFinal(response.getCryptedSessionKey());
  return new SecretKeySpec(sessionKeyEncoded,"DES");
}
 

Example 5

From project DTE, under directory /src/cl/nic/dte/extension/.

Source file: DTEDefTypeExtensionHandler.java

  23 
vote

public static void timbrar(DTEDefType dte,CAFType caf,PrivateKey pKey) throws TimbreException, NoSuchAlgorithmException, SignatureException, InvalidKeyException {
  PublicKey pubKey=null;
  try {
    pubKey=caf.getPublicKey();
  }
 catch (  InvalidKeySpecException e1) {
    throw new InvalidKeyException(Utilities.exceptions.getString("TIMBRE_ERROR_BAD_KEY") + ": " + e1.getMessage());
  }
  if (dte.isSetDocumento())   timbrar(dte.getDocumento(),caf.getCAFforDocument(),pubKey,pKey);
 else   if (dte.isSetLiquidacion())   timbrar(dte.getLiquidacion(),caf.getCAFforLiquidacion(),pubKey,pKey);
 else   if (dte.isSetExportaciones())   timbrar(dte.getExportaciones(),caf.getCAFforExportacion(),pubKey,pKey);
}
 

Example 6

From project Gibberbot, under directory /src/info/guardianproject/otr/.

Source file: OtrAndroidKeyManagerImpl.java

  22 
vote

public String getLocalFingerprint(String userId){
  KeyPair keyPair=loadLocalKeyPair(userId);
  if (keyPair == null)   return null;
  PublicKey pubKey=keyPair.getPublic();
  try {
    String fingerprint=cryptoEngine.getFingerprint(pubKey);
    OtrDebugLogger.log("got fingerprint for: " + userId + "="+ fingerprint);
    return fingerprint;
  }
 catch (  OtrCryptoException e) {
    e.printStackTrace();
    return null;
  }
}
 

Example 7

From project karaf, under directory /shell/ssh/src/test/java/org/apache/karaf/shell/ssh/.

Source file: KnownHostsManagerTest.java

  22 
vote

@Test public void testStoreAndRetrieve() throws IOException, NoSuchAlgorithmException, InvalidKeySpecException {
  SocketAddress address=new InetSocketAddress("localhost",1001);
  File hostsFile=File.createTempFile("hosts","");
  KnownHostsManager manager=new KnownHostsManager(hostsFile);
  PublicKey foundKey1=manager.getKnownKey(address,ALGORITHM);
  Assert.assertNull(foundKey1);
  PublicKey serverKey=createPubKey();
  manager.storeKeyForHost(address,serverKey);
  PublicKey foundKey2=manager.getKnownKey(address,ALGORITHM);
  Assert.assertEquals(serverKey,foundKey2);
}
 

Example 8

From project magrit, under directory /server/sshd/src/main/java/org/kercoin/magrit/sshd/auth/.

Source file: GitPublickeyAuthenticator.java

  22 
vote

@Override public boolean authenticate(String username,PublicKey authKey,ServerSession session){
  try {
    open();
    PublicKey targetKey=readKeyFromRepository(username);
    return targetKey != null && areEqual(targetKey,authKey);
  }
 catch (  Exception e) {
    e.printStackTrace();
    return false;
  }
}
 

Example 9

From project maven-wagon, under directory /wagon-providers/wagon-ssh-common-test/src/main/java/org/apache/maven/wagon/providers/ssh/.

Source file: TestPublickeyAuthenticator.java

  22 
vote

public boolean authenticate(String username,PublicKey key,ServerSession session){
  if (!keyAuthz) {
    return false;
  }
  try {
    InputStream is=Thread.currentThread().getContextClassLoader().getResourceAsStream("ssh-keys/id_rsa.pub");
    PublicKey publicKey=decodePublicKey(IOUtil.toString(is));
    publickeyAuthenticatorRequests.add(new PublickeyAuthenticatorRequest(username,key));
    return ((RSAPublicKey)publicKey).getModulus().equals(((RSAPublicKey)publicKey).getModulus());
  }
 catch (  Exception e) {
    throw new RuntimeException(e.getMessage(),e);
  }
}
 

Example 10

From project mina-sshd, under directory /sshd-core/src/main/java/org/apache/sshd/common/kex/.

Source file: DH.java

  22 
vote

public byte[] getK() throws Exception {
  if (K == null) {
    KeyFactory myKeyFac=SecurityUtils.getKeyFactory("DH");
    DHPublicKeySpec keySpec=new DHPublicKeySpec(f,p,g);
    PublicKey yourPubKey=myKeyFac.generatePublic(keySpec);
    myKeyAgree.doPhase(yourPubKey,true);
    byte[] mySharedSecret=myKeyAgree.generateSecret();
    K=new BigInteger(mySharedSecret);
    K_array=mySharedSecret;
  }
  return K_array;
}
 

Example 11

From project openengsb-framework, under directory /examples/remoteclient/src/main/java/test/.

Source file: SecureSampleApp.java

  22 
vote

private static EncryptedMessage encryptMessage(SecretKey sessionKey,byte[] requestString) throws IOException, EncryptionException {
  PublicKey publicKey=readPublicKey();
  byte[] encryptedContent=CipherUtils.encrypt(requestString,sessionKey);
  byte[] encryptedKey=CipherUtils.encrypt(sessionKey.getEncoded(),publicKey);
  EncryptedMessage encryptedMessage=new EncryptedMessage(encryptedContent,encryptedKey);
  return encryptedMessage;
}
 

Example 12

From project OpenID-Connect-Java-Spring-Server, under directory /openid-connect-common/src/main/java/org/mitre/jwk/model/.

Source file: Rsa.java

  22 
vote

@Override public PublicKey getKey() throws NoSuchAlgorithmException, InvalidKeySpecException {
  byte[] modulusByte=Base64.decodeBase64(mod);
  BigInteger modulus=new BigInteger(modulusByte);
  byte[] exponentByte=Base64.decodeBase64(exp);
  BigInteger exponent=new BigInteger(exponentByte);
  RSAPublicKeySpec spec=new RSAPublicKeySpec(modulus,exponent);
  KeyFactory factory=KeyFactory.getInstance("RSA");
  PublicKey pub=factory.generatePublic(spec);
  return pub;
}
 

Example 13

From project OWASP-WebScarab, under directory /src/org/owasp/webscarab/plugin/proxy/.

Source file: SSLSocketFactoryFactory.java

  22 
vote

private void generateCA(X500Principal caName) throws GeneralSecurityException, IOException {
  KeyPairGenerator keyGen=KeyPairGenerator.getInstance("RSA");
  keyGen.initialize(1024);
  KeyPair caPair=keyGen.generateKeyPair();
  caKey=caPair.getPrivate();
  PublicKey caPubKey=caPair.getPublic();
  Date begin=new Date();
  Date ends=new Date(begin.getTime() + DEFAULT_VALIDITY);
  X509Certificate cert=SunCertificateUtils.sign(caName,caPubKey,caName,caPubKey,caKey,begin,ends,BigInteger.ONE);
  caCerts=new X509Certificate[]{cert};
  keystore.setKeyEntry(CA,caKey,password,caCerts);
  saveKeystore();
}
 

Example 14

From project security, under directory /external/src/test/java/org/jboss/seam/security/externaltest/module/.

Source file: SamlSignatureUtilForPostBindingTest.java

  22 
vote

@Before public void setup() throws KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException, UnrecoverableKeyException {
  samlSignatureUtilForPostBinding=new SamlSignatureUtilForPostBinding();
  InputStream keyStoreStream=getClass().getClassLoader().getResourceAsStream("test_keystore.jks");
  KeyStore keyStore=KeyStore.getInstance(KeyStore.getDefaultType());
  keyStore.load(keyStoreStream,"store456".toCharArray());
  X509Certificate certificate=(X509Certificate)keyStore.getCertificate("servercert");
  PublicKey publicKey=certificate.getPublicKey();
  PrivateKey privateKey=(PrivateKey)keyStore.getKey("servercert","pass456".toCharArray());
  keyPair=new KeyPair(publicKey,privateKey);
}
 

Example 15

From project dungbeetle, under directory /src/edu/stanford/mobisocial/dungbeetle/.

Source file: DBHelper.java

  21 
vote

private void generateAndStorePersonalInfo(SQLiteDatabase db){
  String email=getUserEmail();
  String name=email;
  KeyPair keypair=DBIdentityProvider.generateKeyPair();
  PrivateKey privateKey=keypair.getPrivate();
  PublicKey publicKey=keypair.getPublic();
  String pubKeyStr=FastBase64.encodeToString(publicKey.getEncoded());
  String privKeyStr=FastBase64.encodeToString(privateKey.getEncoded());
  ContentValues cv=new ContentValues();
  cv.put(MyInfo.PUBLIC_KEY,pubKeyStr);
  cv.put(MyInfo.PRIVATE_KEY,privKeyStr);
  cv.put(MyInfo.NAME,name);
  cv.put(MyInfo.EMAIL,email);
  db.insertOrThrow(MyInfo.TABLE,null,cv);
  Log.d(TAG,"Generated public key: " + pubKeyStr);
  Log.d(TAG,"Generated priv key: **************");
}
 

Example 16

From project eucalyptus, under directory /clc/modules/axis2-transport/src/edu/ucsb/eucalyptus/transport/query/.

Source file: StorageQuerySecurityHandler.java

  21 
vote

public UserInfo handle(String addr,String verb,Map<String,String> parameters,Map<String,String> headers) throws QuerySecurityException {
  CaseInsensitiveMap hdrs=new CaseInsensitiveMap(headers);
  this.checkParameters(hdrs);
  String date=(String)hdrs.remove(SecurityParameter.Date);
  String eucaCert=(String)hdrs.remove(StorageSecurityParameters.EucaCert);
  String signature=(String)hdrs.remove(StorageSecurityParameters.EucaSignature);
  String data=verb + "\n" + date+ "\n"+ addr+ "\n";
  Signature sig;
  boolean valid=false;
  try {
    X509Certificate cert=(X509Certificate)new PEMReader(new StringReader(eucaCert)).readObject();
    AbstractKeyStore keyStore=ServiceKeyStore.getInstance();
    if (keyStore.getCertificateAlias(cert) != null) {
      PublicKey publicKey=cert.getPublicKey();
      sig=Signature.getInstance("SHA1withRSA");
      sig.initVerify(publicKey);
      sig.update(data.getBytes());
      valid=sig.verify(Base64.decode(signature));
    }
  }
 catch (  Exception ex) {
    ex.printStackTrace();
  }
  if (!valid) {
    throw new QuerySecurityException("User authentication failed.");
  }
  UserInfo admin=new UserInfo("admin");
  admin.setIsAdministrator(Boolean.TRUE);
  return admin;
}
 

Example 17

From project flazr, under directory /src/main/java/com/flazr/rtmp/.

Source file: RtmpHandshake.java

  21 
vote

private void initCiphers(){
  BigInteger otherPublicKeyInt=new BigInteger(1,peerPublicKey);
  try {
    KeyFactory keyFactory=KeyFactory.getInstance("DH");
    KeySpec otherPublicKeySpec=new DHPublicKeySpec(otherPublicKeyInt,DH_MODULUS,DH_BASE);
    PublicKey otherPublicKey=keyFactory.generatePublic(otherPublicKeySpec);
    keyAgreement.doPhase(otherPublicKey,true);
  }
 catch (  Exception e) {
    throw new RuntimeException(e);
  }
  byte[] sharedSecret=keyAgreement.generateSecret();
  byte[] digestOut=Utils.sha256(peerPublicKey,sharedSecret);
  byte[] digestIn=Utils.sha256(ownPublicKey,sharedSecret);
  try {
    cipherOut=Cipher.getInstance("RC4");
    cipherOut.init(Cipher.ENCRYPT_MODE,new SecretKeySpec(digestOut,0,16,"RC4"));
    cipherIn=Cipher.getInstance("RC4");
    cipherIn.init(Cipher.DECRYPT_MODE,new SecretKeySpec(digestIn,0,16,"RC4"));
    logger.info("initialized encryption / decryption ciphers");
  }
 catch (  Exception e) {
    throw new RuntimeException(e);
  }
  byte[] dummyBytes=new byte[HANDSHAKE_SIZE];
  cipherIn.update(dummyBytes);
  cipherOut.update(dummyBytes);
}
 

Example 18

From project gengweibo, under directory /src/net/oauth/signature/.

Source file: RSA_SHA1.java

  21 
vote

private PublicKey getPublicKeyFromPem(String pem) throws GeneralSecurityException, IOException {
  InputStream stream=new ByteArrayInputStream(pem.getBytes("UTF-8"));
  PEMReader reader=new PEMReader(stream);
  byte[] bytes=reader.getDerBytes();
  PublicKey pubKey;
  if (PEMReader.PUBLIC_X509_MARKER.equals(reader.getBeginMarker())) {
    KeySpec keySpec=new X509EncodedKeySpec(bytes);
    KeyFactory fac=KeyFactory.getInstance("RSA");
    pubKey=fac.generatePublic(keySpec);
  }
 else   if (PEMReader.CERTIFICATE_X509_MARKER.equals(reader.getBeginMarker())) {
    pubKey=getPublicKeyFromDerCert(bytes);
  }
 else {
    throw new IOException("Invalid PEM fileL: Unknown marker for " + " public key or cert " + reader.getBeginMarker());
  }
  return pubKey;
}
 

Example 19

From project GradeCalculator-Android, under directory /GradeCalculator/src/com/jetheis/android/grades/billing/.

Source file: Security.java

  21 
vote

public static boolean isCorrectSignature(String signedData,String signature){
  PublicKey publicKey;
  try {
    byte[] decodedKey=Base64.decode(PUBLIC_KEY_64,0);
    KeyFactory keyFactory=KeyFactory.getInstance("RSA");
    publicKey=keyFactory.generatePublic(new X509EncodedKeySpec(decodedKey));
  }
 catch (  NoSuchAlgorithmException e) {
    Log.e(Constants.TAG,"NoSuchAlgoritmException: " + e.getLocalizedMessage());
    return false;
  }
catch (  InvalidKeySpecException e) {
    Log.e(Constants.TAG,"InvalidKeySpecException: " + e.getLocalizedMessage());
    return false;
  }
  Signature sig;
  try {
    sig=Signature.getInstance("SHA1withRSA");
    sig.initVerify(publicKey);
    sig.update(signedData.getBytes());
    if (!sig.verify(Base64.decode(signature,0))) {
      Log.e(Constants.TAG,"Bad Google Play signature! Possible security breach!");
      return false;
    }
    return true;
  }
 catch (  NoSuchAlgorithmException e) {
    Log.e(Constants.TAG,"NoSuchAlgorithmException: " + e.getLocalizedMessage());
    return false;
  }
catch (  InvalidKeyException e) {
    Log.e(Constants.TAG,"InvalidKeyException: " + e.getLocalizedMessage());
    return false;
  }
catch (  SignatureException e) {
    Log.e(Constants.TAG,"SignatureException: " + e.getLocalizedMessage());
    return false;
  }
}
 

Example 20

From project isohealth, under directory /Oauth/java/core/commons/src/main/java/net/oauth/signature/.

Source file: RSA_SHA1.java

  21 
vote

private PublicKey getPublicKeyFromPem(String pem) throws GeneralSecurityException, IOException {
  InputStream stream=new ByteArrayInputStream(pem.getBytes("UTF-8"));
  PEMReader reader=new PEMReader(stream);
  byte[] bytes=reader.getDerBytes();
  PublicKey pubKey;
  if (PEMReader.PUBLIC_X509_MARKER.equals(reader.getBeginMarker())) {
    KeySpec keySpec=new X509EncodedKeySpec(bytes);
    KeyFactory fac=KeyFactory.getInstance("RSA");
    pubKey=fac.generatePublic(keySpec);
  }
 else   if (PEMReader.CERTIFICATE_X509_MARKER.equals(reader.getBeginMarker())) {
    pubKey=getPublicKeyFromDerCert(bytes);
  }
 else {
    throw new IOException("Invalid PEM fileL: Unknown marker for " + " public key or cert " + reader.getBeginMarker());
  }
  return pubKey;
}
 

Example 21

From project JGlobus, under directory /ssl-proxies/src/main/java/org/globus/gsi/trustmanager/.

Source file: TrustedCertPathFinder.java

  21 
vote

private static X509Certificate checkCertificate(List<X509Certificate> trustedCertPath,X509Certificate x509Certificate,Certificate issuerCertificate) throws CertPathValidatorException {
  X509Certificate x509IssuerCertificate=(X509Certificate)issuerCertificate;
  String issuerDN=CertificateUtil.toGlobusID(x509Certificate.getIssuerX500Principal());
  String issuerCertDN=CertificateUtil.toGlobusID(x509IssuerCertificate.getSubjectX500Principal());
  if (!(issuerDN.equals(issuerCertDN))) {
    throw new IllegalArgumentException("Incorrect certificate path, certificate in chain can only " + "be issuer of previous certificate");
  }
  PublicKey publicKey=x509IssuerCertificate.getPublicKey();
  try {
    x509Certificate.verify(publicKey);
  }
 catch (  CertificateException e) {
    throw new CertPathValidatorException("Signature validation on the certificate " + x509Certificate.getSubjectDN(),e);
  }
catch (  NoSuchAlgorithmException e) {
    throw new CertPathValidatorException("Signature validation on the certificate " + x509Certificate.getSubjectDN(),e);
  }
catch (  InvalidKeyException e) {
    throw new CertPathValidatorException("Signature validation on the certificate " + x509Certificate.getSubjectDN(),e);
  }
catch (  NoSuchProviderException e) {
    throw new CertPathValidatorException("Signature validation on the certificate " + x509Certificate.getSubjectDN(),e);
  }
catch (  SignatureException e) {
    throw new CertPathValidatorException("Signature validation on the certificate " + x509Certificate.getSubjectDN(),e);
  }
  trustedCertPath.add(x509Certificate);
  return x509IssuerCertificate;
}
 

Example 22

From project jPOS-EE, under directory /modules/sshd/src/main/java/org/jpos/ee/cli/.

Source file: AuthorizedKeysFileBasedPKA.java

  21 
vote

protected List<PublicKey> parseAuthorizedKeys() throws Exception {
  List<PublicKey> authorizedKeys=new ArrayList<PublicKey>();
  AuthorizedKeysDecoder decoder=new AuthorizedKeysDecoder();
  File file=new File(filename);
  Scanner scanner=null;
  try {
    scanner=new Scanner(file).useDelimiter("\n");
    while (scanner.hasNext()) {
      final PublicKey publicKey=decoder.decodePublicKey(scanner.next());
      authorizedKeys.add(publicKey);
    }
  }
  finally {
    if (scanner != null) {
      scanner.close();
    }
  }
  return authorizedKeys;
}
 

Example 23

From project narya, under directory /core/src/main/java/com/threerings/presents/client/.

Source file: BlockingCommunicator.java

  21 
vote

@Override protected void willStart(){
  try {
    connect();
    PublicKey key=_client.getPublicKey();
    AuthResponse response=null;
    if (key != null) {
      PublicKeyCredentials pkcreds=new PublicKeyCredentials(key);
      sendMessage(new SecureRequest(pkcreds,_client.getVersion()));
      log.debug("Waiting for secure response.");
      response=(AuthResponse)receiveMessage();
      if (response instanceof SecureResponse) {
        AuthRequest areq=AESAuthRequest.createAuthRequest(_client.getCredentials(),_client.getVersion(),_client.getBootGroups(),_client.requireSecureAuth(),pkcreds,(SecureResponse)response);
        sendMessage(areq);
        _client.setSecret(areq.getSecret());
        log.debug("Waiting for auth response.");
        response=(AuthResponse)receiveMessage();
      }
    }
 else {
      sendMessage(AESAuthRequest.createAuthRequest(_client.getCredentials(),_client.getVersion(),_client.getBootGroups(),_client.requireSecureAuth()));
      log.debug("Waiting for auth response.");
      response=(AuthResponse)receiveMessage();
    }
    gotAuthResponse(response);
  }
 catch (  Exception e) {
    log.debug("Logon failed: " + e);
    _logonError=e;
    shutdown();
  }
}
 

Example 24

From project ODE-X, under directory /runtime/src/main/java/org/apache/ode/runtime/exec/platform/.

Source file: NodeImpl.java

  21 
vote

@PostConstruct public void init(){
  try {
    encKey=clusterConfig.getSecurity().getEncKey();
    KeyStore ks=KeyStore.getInstance("PKCS12");
    ks.load(new ByteArrayInputStream(clusterConfig.getSecurity().getEncKeyStore()),clusterConfig.getSecurity().getEncKeyStorePass().toCharArray());
    PrivateKey privateKey=(PrivateKey)ks.getKey(clusterConfig.getSecurity().getKeyAlias(),clusterConfig.getSecurity().getEncKeyPass().toCharArray());
    if (privateKey == null) {
      throw new Exception(String.format("Can't find private key alias %s in cluster config keystore",clusterConfig.getSecurity().getKeyAlias()));
    }
    java.security.cert.Certificate cert=ks.getCertificate(clusterConfig.getSecurity().getKeyAlias());
    if (cert == null) {
      throw new Exception(String.format("Can't find public key alias %s in cluster config keystore",clusterConfig.getSecurity().getKeyAlias()));
    }
    PublicKey publicKey=cert.getPublicKey();
    clusterKey=new KeyPair(publicKey,privateKey);
  }
 catch (  Exception e) {
    log.log(Level.SEVERE,"",e);
  }
}
 

Example 25

From project Ohmage_Phone, under directory /src/org/ohmage/util/.

Source file: NDNUtils.java

  21 
vote

public static byte[] encryptConfigData(KeyLocator locator,String username,String password){
  PublicKey public_key=null;
  final BSONEncoder encoder=new BSONEncoder();
  final GlobalConfig config=GlobalConfig.getInstance();
  final PDCKeyManager keymgr=config.getKeyManager();
  final PublisherPublicKeyDigest digest=OhmagePDVManager.getConfigurationDigest();
  DBObject bsonData=new BasicDBObject();
  bsonData.put("username",username);
  bsonData.put("password",password);
  try {
    public_key=keymgr.getPublicKey(digest,locator);
    if (public_key == null) {
      Log.info("Public Key returned is null");
      return null;
    }
    return EncryptionHelper.encryptAsymData(public_key,encoder.encode(bsonData));
  }
 catch (  IOException e) {
    Log.error("Got IOException inside NDNUtils");
    e.printStackTrace();
  }
catch (  PDCEncryptionException e) {
    Log.error("Got PDCEncryption Exception inside NDNUtils");
  }
  return null;
}
 

Example 26

From project Ohmage_Server_2, under directory /src/edu/ucla/cens/pdc/libpdc/core/.

Source file: ManageCommand.java

  21 
vote

private boolean handleConfigurationKeyCmd(ContentName postfix,Interest interest){
  final GlobalConfig config=GlobalConfig.getInstance();
  final PDCKeyManager keymgr=config.getKeyManager();
  final PublisherPublicKeyDigest digest=OhmagePDVGlobals.getConfigurationDigest();
  final PublicKey key=keymgr.getPublicKey(digest);
  final CCNTime version=keymgr.getKeyVersion(digest);
  if (key == null) {
    LOGGER.error("Public for given digest " + digest + " Is null");
    return false;
  }
 else {
    LOGGER.info("Key : " + key);
  }
  if (version == null) {
    LOGGER.error("version key for given digest");
    return false;
  }
 else {
    LOGGER.info("Version : " + version);
  }
  final KeyLocator locator=new KeyLocator(interest.name(),digest);
  try {
    PublicKeyObject pko=new PublicKeyObject(interest.name(),key,SaveType.RAW,digest,locator,config.getCCNHandle());
    pko.getFlowControl().disable();
    pko.save(version,interest);
    pko.close();
    return true;
  }
 catch (  IOException e) {
    LOGGER.error("Manage Command get Configuration public key failed");
    e.printStackTrace();
  }
  return false;
}
 

Example 27

From project playframework-oauthprovider, under directory /app/net/oauth/signature/.

Source file: RSA_SHA1.java

  21 
vote

/** 
 * Gets the public key from pem.
 * @param pem the pem
 * @return the public key from pem
 * @throws GeneralSecurityException the general security exception
 * @throws IOException Signals that an I/O exception has occurred.
 */
private PublicKey getPublicKeyFromPem(String pem) throws GeneralSecurityException, IOException {
  InputStream stream=new ByteArrayInputStream(pem.getBytes("UTF-8"));
  PEMReader reader=new PEMReader(stream);
  byte[] bytes=reader.getDerBytes();
  PublicKey pubKey;
  if (PEMReader.PUBLIC_X509_MARKER.equals(reader.getBeginMarker())) {
    KeySpec keySpec=new X509EncodedKeySpec(bytes);
    KeyFactory fac=KeyFactory.getInstance("RSA");
    pubKey=fac.generatePublic(keySpec);
  }
 else   if (PEMReader.CERTIFICATE_X509_MARKER.equals(reader.getBeginMarker())) {
    pubKey=getPublicKeyFromDerCert(bytes);
  }
 else {
    throw new IOException("Invalid PEM fileL: Unknown marker for " + " public key or cert " + reader.getBeginMarker());
  }
  return pubKey;
}
 

Example 28

From project Red5, under directory /src/org/red5/server/net/rtmp/.

Source file: RTMPHandshake.java

  21 
vote

/** 
 * Determines the validation scheme for given input.
 * @param otherPublicKeyBytes
 * @param agreement
 * @return shared secret bytes if client used a supported validation scheme
 */
protected static byte[] getSharedSecret(byte[] otherPublicKeyBytes,KeyAgreement agreement){
  BigInteger otherPublicKeyInt=new BigInteger(1,otherPublicKeyBytes);
  try {
    KeyFactory keyFactory=KeyFactory.getInstance("DH");
    KeySpec otherPublicKeySpec=new DHPublicKeySpec(otherPublicKeyInt,RTMPHandshake.DH_MODULUS,RTMPHandshake.DH_BASE);
    PublicKey otherPublicKey=keyFactory.generatePublic(otherPublicKeySpec);
    agreement.doPhase(otherPublicKey,true);
  }
 catch (  Exception e) {
    log.error("Exception getting the shared secret",e);
  }
  byte[] sharedSecret=agreement.generateSecret();
  log.debug("Shared secret [{}]: {}",sharedSecret.length,Hex.encodeHexString(sharedSecret));
  return sharedSecret;
}
 

Example 29

From project red5-server, under directory /src/org/red5/server/net/rtmp/.

Source file: RTMPHandshake.java

  21 
vote

/** 
 * Determines the validation scheme for given input.
 * @param otherPublicKeyBytes
 * @param agreement
 * @return shared secret bytes if client used a supported validation scheme
 */
protected static byte[] getSharedSecret(byte[] otherPublicKeyBytes,KeyAgreement agreement){
  BigInteger otherPublicKeyInt=new BigInteger(1,otherPublicKeyBytes);
  try {
    KeyFactory keyFactory=KeyFactory.getInstance("DH");
    KeySpec otherPublicKeySpec=new DHPublicKeySpec(otherPublicKeyInt,RTMPHandshake.DH_MODULUS,RTMPHandshake.DH_BASE);
    PublicKey otherPublicKey=keyFactory.generatePublic(otherPublicKeySpec);
    agreement.doPhase(otherPublicKey,true);
  }
 catch (  Exception e) {
    log.error("Exception getting the shared secret",e);
  }
  byte[] sharedSecret=agreement.generateSecret();
  log.debug("Shared secret [{}]: {}",sharedSecret.length,Hex.encodeHexString(sharedSecret));
  return sharedSecret;
}
 

Example 30

From project Sage-Mobile-Calc, under directory /src/org/connectbot/.

Source file: GeneratePubkeyActivity.java

  21 
vote

public void run(){
  try {
    boolean encrypted=false;
    SecureRandom random=SecureRandom.getInstance("SHA1PRNG");
    random.setSeed(entropy);
    KeyPairGenerator keyPairGen=KeyPairGenerator.getInstance(keyType);
    keyPairGen.initialize(bits,random);
    KeyPair pair=keyPairGen.generateKeyPair();
    PrivateKey priv=pair.getPrivate();
    PublicKey pub=pair.getPublic();
    String secret=password1.getText().toString();
    if (secret.length() > 0)     encrypted=true;
    Log.d(TAG,"private: " + PubkeyUtils.formatKey(priv));
    Log.d(TAG,"public: " + PubkeyUtils.formatKey(pub));
    PubkeyBean pubkey=new PubkeyBean();
    pubkey.setNickname(nickname.getText().toString());
    pubkey.setType(keyType);
    pubkey.setPrivateKey(PubkeyUtils.getEncodedPrivate(priv,secret));
    pubkey.setPublicKey(PubkeyUtils.getEncodedPublic(pub));
    pubkey.setEncrypted(encrypted);
    pubkey.setStartup(unlockAtStartup.isChecked());
    pubkey.setConfirmUse(confirmUse.isChecked());
    PubkeyDatabase pubkeydb=new PubkeyDatabase(GeneratePubkeyActivity.this);
    pubkeydb.savePubkey(pubkey);
    pubkeydb.close();
  }
 catch (  Exception e) {
    Log.e(TAG,"Could not generate key pair");
    e.printStackTrace();
  }
  handler.sendEmptyMessage(0);
}
 

Example 31

From project platform_external_oauth, under directory /core/src/main/java/net/oauth/signature/.

Source file: RSA_SHA1.java

  20 
vote

private PublicKey getPublicKeyFromPemCert(String certObject) throws GeneralSecurityException {
  CertificateFactory fac=CertificateFactory.getInstance("X509");
  ByteArrayInputStream in=new ByteArrayInputStream(certObject.getBytes());
  X509Certificate cert=(X509Certificate)fac.generateCertificate(in);
  return cert.getPublicKey();
}
 

Example 32

From project Airports, under directory /src/com/nadmm/airports/billing/.

Source file: Security.java

  19 
vote

/** 
 * Generates a PublicKey instance from a string containing the Base64-encoded public key.
 * @param encodedPublicKey Base64-encoded public key
 * @throws IllegalArgumentException if encodedPublicKey is invalid
 */
public static PublicKey generatePublicKey(String encodedPublicKey){
  try {
    byte[] decodedKey=Base64.decode(encodedPublicKey);
    KeyFactory keyFactory=KeyFactory.getInstance(KEY_FACTORY_ALGORITHM);
    return keyFactory.generatePublic(new X509EncodedKeySpec(decodedKey));
  }
 catch (  NoSuchAlgorithmException e) {
    throw new RuntimeException(e);
  }
catch (  InvalidKeySpecException e) {
    Log.e(TAG,"Invalid key specification.");
    throw new IllegalArgumentException(e);
  }
catch (  Base64DecoderException e) {
    Log.e(TAG,"Base64 decoding failed.");
    throw new IllegalArgumentException(e);
  }
}
 

Example 33

From project android-donations-lib, under directory /org_donations/src/org/donations/google/.

Source file: Security.java

  19 
vote

/** 
 * Generates a PublicKey instance from a string containing the Base64-encoded public key.
 * @param encodedPublicKey Base64-encoded public key
 * @throws IllegalArgumentException if encodedPublicKey is invalid
 */
public static PublicKey generatePublicKey(String encodedPublicKey){
  try {
    byte[] decodedKey=Base64.decode(encodedPublicKey);
    KeyFactory keyFactory=KeyFactory.getInstance(KEY_FACTORY_ALGORITHM);
    return keyFactory.generatePublic(new X509EncodedKeySpec(decodedKey));
  }
 catch (  NoSuchAlgorithmException e) {
    throw new RuntimeException(e);
  }
catch (  InvalidKeySpecException e) {
    Log.e(TAG,"Invalid key specification.");
    throw new IllegalArgumentException(e);
  }
catch (  Base64DecoderException e) {
    Log.e(TAG,"Base64 decoding failed.");
    throw new IllegalArgumentException(e);
  }
}
 

Example 34

From project android_external_oauth, under directory /core/src/main/java/net/oauth/signature/.

Source file: RSA_SHA1.java

  19 
vote

private PublicKey getPublicKeyFromPemCert(String certObject) throws GeneralSecurityException {
  CertificateFactory fac=CertificateFactory.getInstance("X509");
  ByteArrayInputStream in=new ByteArrayInputStream(certObject.getBytes());
  X509Certificate cert=(X509Certificate)fac.generateCertificate(in);
  return cert.getPublicKey();
}
 

Example 35

From project BazaarUtils, under directory /src/com/android/vending/licensing/.

Source file: LicenseChecker.java

  19 
vote

/** 
 * Generates a PublicKey instance from a string containing the Base64-encoded public key.
 * @param encodedPublicKey Base64-encoded public key
 * @throws IllegalArgumentException if encodedPublicKey is invalid
 */
private static PublicKey generatePublicKey(String encodedPublicKey){
  try {
    byte[] decodedKey=Base64.decode(encodedPublicKey);
    KeyFactory keyFactory=KeyFactory.getInstance(KEY_FACTORY_ALGORITHM);
    return keyFactory.generatePublic(new X509EncodedKeySpec(decodedKey));
  }
 catch (  NoSuchAlgorithmException e) {
    throw new RuntimeException(e);
  }
catch (  Base64DecoderException e) {
    Log.e(TAG,"Could not decode from Base64.");
    throw new IllegalArgumentException(e);
  }
catch (  InvalidKeySpecException e) {
    Log.e(TAG,"Invalid key specification.");
    throw new IllegalArgumentException(e);
  }
}
 

Example 36

From project cas, under directory /cas-server-core/src/main/java/org/jasig/cas/authentication/principal/.

Source file: GoogleAccountsService.java

  19 
vote

protected GoogleAccountsService(final String id,final String originalUrl,final String artifactId,final String relayState,final String requestId,final PrivateKey privateKey,final PublicKey publicKey,final String alternateUserName){
  super(id,originalUrl,artifactId,null);
  this.relayState=relayState;
  this.privateKey=privateKey;
  this.publicKey=publicKey;
  this.requestId=requestId;
  this.alternateUserName=alternateUserName;
}
 

Example 37

From project dnieprov, under directory /src/org/dnieprov/driver/.

Source file: DnieInterface.java

  19 
vote

public static PublicKey getCaComponentPubkey() throws NoSuchAlgorithmException, InvalidKeySpecException, UnsupportedEncodingException {
  BigInteger modulus=new BigInteger(1,CA_COMPONENT_MODULUS);
  BigInteger exponent=new BigInteger(1,CA_COMPONENT_EXPONENT);
  RSAPublicKeySpec publicKeySpec=new RSAPublicKeySpec(modulus,exponent);
  KeyFactory keyFactory=KeyFactory.getInstance("RSA");
  return keyFactory.generatePublic(publicKeySpec);
}
 

Example 38

From project Gaggle, under directory /src/com/geeksville/billing/.

Source file: Security.java

  19 
vote

/** 
 * Generates a PublicKey instance from a string containing the Base64-encoded public key.
 * @param encodedPublicKey Base64-encoded public key
 * @throws IllegalArgumentException if encodedPublicKey is invalid
 */
public static PublicKey generatePublicKey(String encodedPublicKey){
  try {
    byte[] decodedKey=Base64.decode(encodedPublicKey);
    KeyFactory keyFactory=KeyFactory.getInstance(KEY_FACTORY_ALGORITHM);
    return keyFactory.generatePublic(new X509EncodedKeySpec(decodedKey));
  }
 catch (  NoSuchAlgorithmException e) {
    throw new RuntimeException(e);
  }
catch (  InvalidKeySpecException e) {
    Log.e(TAG,"Invalid key specification.");
    throw new IllegalArgumentException(e);
  }
catch (  Base64DecoderException e) {
    Log.e(TAG,"Base64 decoding failed.");
    throw new IllegalArgumentException(e);
  }
}
 

Example 39

From project gerrit-trigger-plugin, under directory /gerrithudsontrigger/src/test/java/com/sonyericsson/hudson/plugins/gerrit/trigger/mock/.

Source file: SshdServerMock.java

  19 
vote

/** 
 * Starts a ssh server on the provided port.
 * @param port the port to listen to.
 * @return the server.
 * @throws IOException if so.
 */
public static SshServer startServer(int port) throws IOException {
  SshServer sshd=SshServer.setUpDefaultServer();
  sshd.setPort(port);
  sshd.setKeyPairProvider(new SimpleGeneratorHostKeyProvider("hostkey.ser"));
  sshd.setPublickeyAuthenticator(new PublickeyAuthenticator(){
    @Override public boolean authenticate(    String s,    PublicKey publicKey,    ServerSession serverSession){
      return true;
    }
  }
);
  sshd.setCommandFactory(getInstance());
  sshd.start();
  return sshd;
}
 

Example 40

From project IOCipherServer, under directory /src/info/guardianproject/iocipher/server/.

Source file: KeyStoreGenerator.java

  19 
vote

public static X509Certificate makeCertificate(PrivateKey issuerPrivateKey,PublicKey subjectPublicKey,String cn,String o,String ou,String l,String st,String c) throws Exception {
  final org.spongycastle.asn1.x509.X509Name issuerDN=new org.spongycastle.asn1.x509.X509Name("CN=" + cn + ", OU="+ ou+ ", O="+ o+ ", L="+ l+ ", ST="+ st+ ", C="+ c);
  final org.spongycastle.asn1.x509.X509Name subjectDN=new org.spongycastle.asn1.x509.X509Name("CN=" + cn + ", OU="+ ou+ ", O="+ o+ ", L="+ l+ ", ST="+ st+ ", C="+ c);
  final int daysTillExpiry=10 * 365;
  final Calendar expiry=Calendar.getInstance();
  expiry.add(Calendar.DAY_OF_YEAR,daysTillExpiry);
  final org.spongycastle.x509.X509V3CertificateGenerator certificateGenerator=new org.spongycastle.x509.X509V3CertificateGenerator();
  certificateGenerator.setSerialNumber(java.math.BigInteger.valueOf(System.currentTimeMillis()));
  certificateGenerator.setIssuerDN(issuerDN);
  certificateGenerator.setSubjectDN(subjectDN);
  certificateGenerator.setPublicKey(subjectPublicKey);
  certificateGenerator.setNotBefore(new Date());
  certificateGenerator.setNotAfter(expiry.getTime());
  certificateGenerator.setSignatureAlgorithm("MD5WithRSA");
  return certificateGenerator.generate(issuerPrivateKey);
}
 

Example 41

From project jclouds-chef, under directory /core/src/main/java/org/jclouds/chef/config/.

Source file: ChefParserModule.java

  19 
vote

@Override public PublicKey deserialize(JsonElement json,Type typeOfT,JsonDeserializationContext context) throws JsonParseException {
  String keyText=json.getAsString().replaceAll("\\n","\n");
  try {
    return crypto.rsaKeyFactory().generatePublic(Pems.publicKeySpec(InputSuppliers.of(keyText)));
  }
 catch (  UnsupportedEncodingException e) {
    Throwables.propagate(e);
    return null;
  }
catch (  InvalidKeySpecException e) {
    Throwables.propagate(e);
    return null;
  }
catch (  IOException e) {
    Throwables.propagate(e);
    return null;
  }
}
 

Example 42

From project jentrata-msh, under directory /Ext/ebxml-pkg/src/main/java/hk/hku/cecid/ebms/pkg/pki/.

Source file: CertSource.java

  19 
vote

/** 
 * Verifies whether the certificate is signed by the private key  corresponding to the specified public key.
 * @param pubKey the public key for verification
 * @return true if the verification is passed, false if otherwise.
 */
public boolean verify(PublicKey pubKey) throws InitializationException {
  if (x509Cert == null) {
    throw new InitializationException("Not yet initialized.");
  }
  boolean ret=false;
  try {
    x509Cert.verify(pubKey);
    ret=true;
  }
 catch (  CertificateException e) {
  }
catch (  NoSuchAlgorithmException e) {
  }
catch (  InvalidKeyException e) {
  }
catch (  NoSuchProviderException e) {
  }
catch (  SignatureException e) {
  }
  return ret;
}
 

Example 43

From project Jota-Text-Editor, under directory /src/jp/sblo/pandora/billing/.

Source file: Security.java

  19 
vote

/** 
 * Generates a PublicKey instance from a string containing the Base64-encoded public key.
 * @param encodedPublicKey Base64-encoded public key
 * @throws IllegalArgumentException if encodedPublicKey is invalid
 */
public static PublicKey generatePublicKey(String encodedPublicKey){
  try {
    byte[] decodedKey=Base64.decode(encodedPublicKey);
    KeyFactory keyFactory=KeyFactory.getInstance(KEY_FACTORY_ALGORITHM);
    return keyFactory.generatePublic(new X509EncodedKeySpec(decodedKey));
  }
 catch (  NoSuchAlgorithmException e) {
    throw new RuntimeException(e);
  }
catch (  InvalidKeySpecException e) {
    Log.e(TAG,"Invalid key specification.");
    throw new IllegalArgumentException(e);
  }
catch (  Base64DecoderException e) {
    Log.e(TAG,"Base64 decoding failed.");
    throw new IllegalArgumentException(e);
  }
}
 

Example 44

From project LVLPractice, under directory /src/com/android/vending/licensing/.

Source file: LicenseChecker.java

  19 
vote

/** 
 * Generates a PublicKey instance from a string containing the Base64-encoded public key.
 * @param encodedPublicKey Base64-encoded public key
 * @throws IllegalArgumentException if encodedPublicKey is invalid
 */
private static PublicKey generatePublicKey(String encodedPublicKey){
  try {
    byte[] decodedKey=Base64.decode(encodedPublicKey);
    KeyFactory keyFactory=KeyFactory.getInstance(KEY_FACTORY_ALGORITHM);
    return keyFactory.generatePublic(new X509EncodedKeySpec(decodedKey));
  }
 catch (  NoSuchAlgorithmException e) {
    throw new RuntimeException(e);
  }
catch (  Base64DecoderException e) {
    Log.e(TAG,"Could not decode from Base64.");
    throw new IllegalArgumentException(e);
  }
catch (  InvalidKeySpecException e) {
    Log.e(TAG,"Invalid key specification.");
    throw new IllegalArgumentException(e);
  }
}
 

Example 45

From project miso-lims, under directory /integration-tools/src/main/java/uk/ac/bbsrc/tgac/miso/integration/util/.

Source file: SignatureHelper.java

  19 
vote

private static PublicKey decodePublicKey(String publicKey) throws Exception {
  KeyFactory keyFactory=KeyFactory.getInstance(ALGORITHM);
  byte[] publicKeyBytes=Base64.decodeBase64(publicKey);
  EncodedKeySpec publicKeySpec=new X509EncodedKeySpec(publicKeyBytes);
  return keyFactory.generatePublic(publicKeySpec);
}
 

Example 46

From project Monetizing-Android-Demo-Project, under directory /src/dk/trifork/geeknight/billing/.

Source file: Security.java

  19 
vote

/** 
 * Generates a PublicKey instance from a string containing the Base64-encoded public key.
 * @param encodedPublicKey Base64-encoded public key
 * @throws IllegalArgumentException if encodedPublicKey is invalid
 */
public static PublicKey generatePublicKey(String encodedPublicKey){
  try {
    byte[] decodedKey=Base64.decode(encodedPublicKey);
    KeyFactory keyFactory=KeyFactory.getInstance(KEY_FACTORY_ALGORITHM);
    return keyFactory.generatePublic(new X509EncodedKeySpec(decodedKey));
  }
 catch (  NoSuchAlgorithmException e) {
    throw new RuntimeException(e);
  }
catch (  InvalidKeySpecException e) {
    Log.e(TAG,"Invalid key specification.");
    throw new IllegalArgumentException(e);
  }
catch (  Base64DecoderException e) {
    Log.e(TAG,"Base64 decoding failed.");
    throw new IllegalArgumentException(e);
  }
}
 

Example 47

From project QuotaForAndroid, under directory /Quota/src/com/southfreo/quota/billing/.

Source file: Security.java

  19 
vote

/** 
 * Generates a PublicKey instance from a string containing the Base64-encoded public key.
 * @param encodedPublicKey Base64-encoded public key
 * @throws IllegalArgumentException if encodedPublicKey is invalid
 */
public static PublicKey generatePublicKey(String encodedPublicKey){
  try {
    byte[] decodedKey=Base64.decode(encodedPublicKey);
    KeyFactory keyFactory=KeyFactory.getInstance(KEY_FACTORY_ALGORITHM);
    return keyFactory.generatePublic(new X509EncodedKeySpec(decodedKey));
  }
 catch (  NoSuchAlgorithmException e) {
    throw new RuntimeException(e);
  }
catch (  InvalidKeySpecException e) {
    Log.e(TAG,"Invalid key specification.");
    throw new IllegalArgumentException(e);
  }
catch (  Base64DecoderException e) {
    Log.e(TAG,"Base64 decoding failed.");
    throw new IllegalArgumentException(e);
  }
}
 

Example 48

From project Schedule, under directory /android/src/com/happytap/schedule/service/.

Source file: Security.java

  19 
vote

/** 
 * Generates a PublicKey instance from a string containing the Base64-encoded public key.
 * @param encodedPublicKey Base64-encoded public key
 * @throws IllegalArgumentException if encodedPublicKey is invalid
 */
public static PublicKey generatePublicKey(String encodedPublicKey){
  try {
    byte[] decodedKey=Base64.decode(encodedPublicKey);
    KeyFactory keyFactory=KeyFactory.getInstance(KEY_FACTORY_ALGORITHM);
    return keyFactory.generatePublic(new X509EncodedKeySpec(decodedKey));
  }
 catch (  NoSuchAlgorithmException e) {
    throw new RuntimeException(e);
  }
catch (  InvalidKeySpecException e) {
    Log.e(TAG,"Invalid key specification.");
    throw new IllegalArgumentException(e);
  }
catch (  Base64DecoderException e) {
    Log.e(TAG,"Base64 decoding failed.");
    throw new IllegalArgumentException(e);
  }
}
 

Example 49

From project security_1, under directory /security-realms/security-public-key-realm/src/main/java/org/sonatype/security/realms/publickey/.

Source file: PublicKeyCredentialsMatcher.java

  19 
vote

protected Collection<PublicKeyWithEquals> getInfoKeys(AuthenticationInfo info){
  final Set<PublicKeyWithEquals> result=new HashSet<PublicKeyWithEquals>();
  final Object credentials=info.getCredentials();
  if (Collection.class.isAssignableFrom(credentials.getClass())) {
    Collection<PublicKey> credentialsCollection=(Collection<PublicKey>)credentials;
    for (    PublicKey publicKey : credentialsCollection) {
      result.add(new PublicKeyWithEquals(publicKey));
    }
  }
 else {
    result.add(new PublicKeyWithEquals((PublicKey)credentials));
  }
  return result;
}