How to codesign an existing Mac OS X .app file for gatekeeper?

Make sure you have a valid developer certificate and a private key in your keychain. If you have some problems with it, the certificate should be revoked via developer.apple.com and generated from the scratch (XCode > Accounts > Manage Certificates).

Then you can use codesign:

codesign --force --deep --sign "Apple Development: FirstName LastName (XXXXXXXXXX)" /Applications/ApplicationName.app

To summarize the comments to my questions, here are the commands I run to sign my .app file for Gatekeeper:

export CODESIGN_ALLOCATE="/Applications/Xcode.app/Contents/Developer/usr/bin/codesign_allocate"
codesign --force --sign "Developer ID Application: <my name>" /path/to/my.app

Thanks, Gordon Davisson and JWWalker!

(edit) If this fails, I realize that installing the "Command Line Tools" from within XCode was needed.

EDIT: To verify

$ codesign -dv --verbose=4 my.app

In Apple ID account make sure you have few types of certificate?

enter image description here enter image description here enter image description here